5,"big","small")". * * A small tokenizer + recursive-descent parser (no eval). Cells are addressed on the physical stored grid * (A1 = $data[0][0]). Results are returned as safe HTML (escaped, "[" neutralised, never starts with "="). * * @package NitidaTables */ namespace NitidaTables; defined( 'ABSPATH' ) || exit; /** Formula error carrying the text shown in the cell (#REF!, #DIV/0! ...). */ final class FormulaError extends \Exception { public $code_text; public function __construct( $code_text ) { parent::__construct( $code_text ); $this->code_text = $code_text; } } final class Formula { const MAX_LEN = 2000; const MAX_VISIT = 100000; const MAX_DEPTH = 1000; const MAX_NEST = 200; private $grid; private $rows = 0; private $cols = 0; private $memo = array(); private $busy = array(); private $asts = array(); private $ncache = array(); private $visits = 0; private $depth = 0; private $cur = array( 0, 0 ); private $toks = array(); private $tp = 0; private $nest = 0; /* --------------------------------------------------------------------- * Public API * ------------------------------------------------------------------ */ /** True when the stored cell is a formula ("=" plus something). */ public static function is_formula( $cell ) { if ( ! is_string( $cell ) ) { return false; } $t = trim( $cell ); return strlen( $t ) > 1 && '=' === $t[0]; } /** Column letters to 0-based index: A=0, Z=25, AA=26. */ public static function col_index( $letters ) { $letters = strtoupper( (string) $letters ); $n = 0; $len = strlen( $letters ); for ( $i = 0; $i < $len; $i++ ) { $o = ord( $letters[ $i ] ); if ( $o < 65 || $o > 90 ) { continue; } $n = $n * 26 + ( $o - 64 ); } return $n - 1 < 0 ? 0 : $n - 1; } /** 0-based index to column letters. */ public static function col_letters( $index ) { $index = (int) $index; if ( $index < 0 ) { return ''; } $s = ''; $n = $index + 1; while ( $n > 0 ) { $m = ( $n - 1 ) % 26; $s = chr( 65 + $m ) . $s; $n = intdiv( $n - 1, 26 ); } return $s; } /** Replace every formula cell with its result as safe HTML. Never throws. */ public static function evaluate( array $data ) { try { $grid = array(); foreach ( $data as $row ) { if ( ! is_array( $row ) ) { return $data; } $grid[] = array_values( $row ); } $self = new self(); $self->grid = $grid; $self->rows = count( $grid ); foreach ( $grid as $row ) { $self->cols = max( $self->cols, count( $row ) ); } $out = $data; $r = 0; foreach ( $data as $rk => $row ) { $c = 0; foreach ( $row as $ck => $cell ) { if ( is_string( $cell ) ) { $t = trim( $cell ); if ( strlen( $t ) > 1 && "'" === $t[0] && '=' === $t[1] ) { $out[ $rk ][ $ck ] = self::esc( substr( $t, 1 ) ); } elseif ( self::is_formula( $cell ) ) { $out[ $rk ][ $ck ] = $self->result_html( $r, $c ); } } $c++; } $r++; } return $out; } catch ( \Throwable $e ) { return $data; } } /* --------------------------------------------------------------------- * Output * ------------------------------------------------------------------ */ /** Escape for output: HTML-escaped, "[" neutralised, leading "=" written as an entity (idempotence). */ private static function esc( $s ) { $s = str_replace( '[', '[', htmlspecialchars( (string) $s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8' ) ); return preg_replace( '/^(\s*)=/', '$1=', $s ); } private function result_html( $r, $c ) { try { $v = $this->cell_value( $r, $c ); if ( null === $v ) { $v = 0.0; } return self::esc( $this->txt( $v ) ); } catch ( FormulaError $e ) { return $e->code_text; } catch ( \Throwable $e ) { return '#ERROR!'; } } /* --------------------------------------------------------------------- * Cells * ------------------------------------------------------------------ */ private function cell_value( $r, $c ) { if ( ++$this->visits > self::MAX_VISIT ) { throw new FormulaError( '#ERROR!' ); } if ( $r < 0 || $c < 0 || $r >= $this->rows || $c >= $this->cols ) { throw new FormulaError( '#REF!' ); } $k = $r * 100000 + $c; if ( array_key_exists( $k, $this->memo ) ) { $v = $this->memo[ $k ]; if ( $v instanceof FormulaError ) { throw $v; } return $v; } $raw = isset( $this->grid[ $r ][ $c ] ) ? $this->grid[ $r ][ $c ] : ''; if ( ! is_string( $raw ) ) { $raw = is_scalar( $raw ) ? (string) $raw : ''; } if ( ! self::is_formula( $raw ) ) { return $this->memo[ $k ] = $this->plain( $raw ); } if ( isset( $this->busy[ $k ] ) ) { throw new FormulaError( '#CIRC!' ); } if ( $this->depth >= self::MAX_DEPTH ) { throw new FormulaError( '#ERROR!' ); } $this->busy[ $k ] = true; $this->depth++; $prev = $this->cur; $this->cur = array( $r, $c ); try { $v = $this->eval_formula( $raw ); if ( is_array( $v ) ) { throw new FormulaError( '#VALUE!' ); } if ( null === $v ) { $v = 0.0; } $this->memo[ $k ] = $v; } catch ( FormulaError $e ) { $this->memo[ $k ] = $e; } catch ( \Throwable $e ) { $this->memo[ $k ] = new FormulaError( '#ERROR!' ); } $this->cur = $prev; $this->depth--; unset( $this->busy[ $k ] ); $v = $this->memo[ $k ]; if ( $v instanceof FormulaError ) { throw $v; } return $v; } /** Stored non-formula cell: text without tags/entities, or null when empty. */ private function plain( $raw ) { $t = trim( $raw ); if ( '' === $t || '#colspan#' === $t || '#rowspan#' === $t || '#span#' === $t ) { return null; } if ( false !== strpos( $t, '<' ) ) { $t = wp_strip_all_tags( $t ); } if ( false !== strpos( $t, '&' ) ) { $t = html_entity_decode( $t, ENT_QUOTES | ENT_HTML5, 'UTF-8' ); } $t = preg_replace( '/^[\s\x{00A0}]+|[\s\x{00A0}]+$/u', '', $t ); if ( null === $t || '' === $t ) { return null; } return $t; } private function range_values( $n ) { list( , $r1, $c1, $r2, $c2 ) = $n; if ( $r1 < 0 || $c1 < 0 || $r2 >= $this->rows || $c2 >= $this->cols ) { throw new FormulaError( '#REF!' ); } $out = array(); for ( $r = $r1; $r <= $r2; $r++ ) { for ( $c = $c1; $c <= $c2; $c++ ) { $out[] = $this->cell_value( $r, $c ); } } return $out; } /* --------------------------------------------------------------------- * Parsing * ------------------------------------------------------------------ */ private function eval_formula( $raw ) { if ( ! isset( $this->asts[ $raw ] ) ) { try { $this->asts[ $raw ] = $this->parse_text( $raw ); } catch ( FormulaError $e ) { $this->asts[ $raw ] = $e->code_text; } } $ast = $this->asts[ $raw ]; if ( is_string( $ast ) ) { throw new FormulaError( esc_html( $ast ) ); } // Error codes such as #REF!; escaping changes nothing. return $this->ev( $ast ); } private function parse_text( $raw ) { $t = trim( $raw ); if ( strlen( $t ) > self::MAX_LEN ) { throw new FormulaError( '#ERROR!' ); } $t = preg_replace( '#]*>#i', '', $t ); $t = html_entity_decode( $t, ENT_QUOTES | ENT_HTML5, 'UTF-8' ); $t = str_replace( array( "\xC2\xA0", "\xE2\x80\x9C", "\xE2\x80\x9D" ), array( ' ', '"', '"' ), $t ); $t = trim( $t ); if ( '' === $t || '=' !== $t[0] ) { throw new FormulaError( '#ERROR!' ); } $this->toks = $this->tokenize( substr( $t, 1 ) ); $this->tp = 0; $this->nest = 0; if ( ! $this->toks ) { throw new FormulaError( '#ERROR!' ); } $n = $this->p_cmp(); if ( $this->tp < count( $this->toks ) ) { throw new FormulaError( '#ERROR!' ); } return $n; } private function tokenize( $s ) { $toks = array(); $pos = 0; $len = strlen( $s ); while ( $pos < $len ) { $ch = $s[ $pos ]; if ( ' ' === $ch || "\t" === $ch || "\n" === $ch || "\r" === $ch ) { $pos++; continue; } if ( '"' === $ch ) { $buf = ''; $pos++; while ( true ) { $q = strpos( $s, '"', $pos ); if ( false === $q ) { throw new FormulaError( '#ERROR!' ); } $buf .= substr( $s, $pos, $q - $pos ); if ( $q + 1 < $len && '"' === $s[ $q + 1 ] ) { $buf .= '"'; $pos = $q + 2; continue; } $pos = $q + 1; break; } $toks[] = array( 's', $buf ); continue; } if ( ( $ch >= '0' && $ch <= '9' ) || ( '.' === $ch && $pos + 1 < $len && $s[ $pos + 1 ] >= '0' && $s[ $pos + 1 ] <= '9' ) ) { if ( ! preg_match( '/\G(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/', $s, $m, 0, $pos ) ) { throw new FormulaError( '#ERROR!' ); } $toks[] = array( 'n', (float) $m[0] ); $pos += strlen( $m[0] ); continue; } if ( '$' === $ch || ctype_alpha( $ch ) || '_' === $ch ) { if ( preg_match( '/\G\$?([A-Za-z]{1,3})\$?(\d{1,7})(?::\$?([A-Za-z]{1,3})\$?(\d{1,7}))?(?![A-Za-z0-9_(.])/', $s, $m, 0, $pos ) ) { $r1 = (int) $m[2] - 1; $c1 = self::col_index( $m[1] ); if ( isset( $m[3] ) && '' !== $m[3] ) { $r2 = (int) $m[4] - 1; $c2 = self::col_index( $m[3] ); $toks[] = array( 'g', min( $r1, $r2 ), min( $c1, $c2 ), max( $r1, $r2 ), max( $c1, $c2 ) ); } else { $toks[] = array( 'r', $r1, $c1 ); } $pos += strlen( $m[0] ); continue; } if ( preg_match( '/\G[A-Za-z_][A-Za-z0-9_.]*/', $s, $m, 0, $pos ) ) { $pos += strlen( $m[0] ); $name = strtoupper( $m[0] ); $p2 = $pos; while ( $p2 < $len && ' ' === $s[ $p2 ] ) { $p2++; } if ( $p2 < $len && '(' === $s[ $p2 ] ) { $toks[] = array( 'f', $name ); } elseif ( 'TRUE' === $name || 'FALSE' === $name ) { $toks[] = array( 'b', 'TRUE' === $name ); } else { $toks[] = array( 'e', '#NAME?' ); } continue; } throw new FormulaError( '#ERROR!' ); } $two = substr( $s, $pos, 2 ); if ( '<>' === $two || '<=' === $two || '>=' === $two ) { $toks[] = array( 'o', $two ); $pos += 2; continue; } if ( false !== strpos( '+-*/^&=<>(),;%', $ch ) ) { $toks[] = array( 'o', ';' === $ch ? ',' : $ch ); $pos++; continue; } throw new FormulaError( '#ERROR!' ); } return $toks; } private function peek_op( $ops ) { if ( $this->tp >= count( $this->toks ) ) { return null; } $t = $this->toks[ $this->tp ]; return ( 'o' === $t[0] && in_array( $t[1], $ops, true ) ) ? $t[1] : null; } private function p_enter() { if ( ++$this->nest > self::MAX_NEST ) { throw new FormulaError( '#ERROR!' ); } } private function p_cmp() { $this->p_enter(); $l = $this->p_cat(); while ( null !== ( $op = $this->peek_op( array( '=', '<>', '<', '>', '<=', '>=' ) ) ) ) { $this->tp++; $l = array( 'bin', $op, $l, $this->p_cat() ); } $this->nest--; return $l; } private function p_cat() { $l = $this->p_add(); while ( null !== $this->peek_op( array( '&' ) ) ) { $this->tp++; $l = array( 'bin', '&', $l, $this->p_add() ); } return $l; } private function p_add() { $l = $this->p_mul(); while ( null !== ( $op = $this->peek_op( array( '+', '-' ) ) ) ) { $this->tp++; $l = array( 'bin', $op, $l, $this->p_mul() ); } return $l; } private function p_mul() { $l = $this->p_pow(); while ( null !== ( $op = $this->peek_op( array( '*', '/' ) ) ) ) { $this->tp++; $l = array( 'bin', $op, $l, $this->p_pow() ); } return $l; } private function p_pow() { $this->p_enter(); $b = $this->p_unary(); if ( null !== $this->peek_op( array( '^' ) ) ) { $this->tp++; $b = array( 'bin', '^', $b, $this->p_pow() ); } $this->nest--; return $b; } private function p_unary() { $this->p_enter(); if ( null !== ( $op = $this->peek_op( array( '+', '-' ) ) ) ) { $this->tp++; $n = array( 'un', $op, $this->p_unary() ); } else { $n = $this->p_postfix(); } $this->nest--; return $n; } private function p_postfix() { $n = $this->p_primary(); while ( null !== $this->peek_op( array( '%' ) ) ) { $this->tp++; $n = array( 'pct', $n ); } return $n; } private function p_primary() { if ( $this->tp >= count( $this->toks ) ) { throw new FormulaError( '#ERROR!' ); } $t = $this->toks[ $this->tp++ ]; switch ( $t[0] ) { case 'n': case 's': case 'b': case 'e': case 'r': case 'g': return $t; case 'o': if ( '(' === $t[1] ) { $n = $this->p_cmp(); if ( null === $this->peek_op( array( ')' ) ) ) { throw new FormulaError( '#ERROR!' ); } $this->tp++; return $n; } throw new FormulaError( '#ERROR!' ); case 'f': $this->tp++; // The "(". $args = array(); if ( null !== $this->peek_op( array( ')' ) ) ) { $this->tp++; return array( 'fn', $t[1], $args ); } while ( true ) { $args[] = $this->p_cmp(); if ( null !== $this->peek_op( array( ',' ) ) ) { $this->tp++; continue; } if ( null !== $this->peek_op( array( ')' ) ) ) { $this->tp++; break; } throw new FormulaError( '#ERROR!' ); } return array( 'fn', $t[1], $args ); } throw new FormulaError( '#ERROR!' ); } /* --------------------------------------------------------------------- * Evaluation * ------------------------------------------------------------------ */ private function ev( $n ) { switch ( $n[0] ) { case 'n': case 's': case 'b': return $n[1]; case 'e': throw new FormulaError( esc_html( $n[1] ) ); // A stored error code such as #NAME?. case 'r': return $this->cell_value( $n[1], $n[2] ); case 'g': return $this->range_values( $n ); case 'un': $v = $this->num( $this->sc( $n[2] ) ); return '-' === $n[1] ? -$v : $v; case 'pct': return $this->num( $this->sc( $n[1] ) ) / 100; case 'bin': return $this->binary( $n[1], $this->sc( $n[2] ), $this->sc( $n[3] ) ); case 'fn': return $this->call( $n[1], $n[2] ); } throw new FormulaError( '#ERROR!' ); } /** Evaluate to a scalar (a range here is a #VALUE!). */ private function sc( $n ) { $v = $this->ev( $n ); if ( is_array( $v ) ) { throw new FormulaError( '#VALUE!' ); } return $v; } private function binary( $op, $a, $b ) { switch ( $op ) { case '&': return $this->txt( $a ) . $this->txt( $b ); case '=': case '<>': case '<': case '>': case '<=': case '>=': $d = $this->compare( $a, $b ); switch ( $op ) { case '=': return 0 === $d; case '<>': return 0 !== $d; case '<': return $d < 0; case '>': return $d > 0; case '<=': return $d <= 0; default: return $d >= 0; } } $x = $this->num( $a ); $y = $this->num( $b ); switch ( $op ) { case '+': $r = $x + $y; break; case '-': $r = $x - $y; break; case '*': $r = $x * $y; break; case '/': if ( 0.0 === $y ) { throw new FormulaError( '#DIV/0!' ); } $r = $x / $y; break; default: $r = $this->power( $x, $y ); } return $this->finite( $r ); } private function power( $x, $y ) { if ( 0.0 === $x && $y < 0 ) { throw new FormulaError( '#DIV/0!' ); } return $this->finite( pow( $x, $y ) ); } private function finite( $r ) { if ( is_nan( $r ) || is_infinite( $r ) ) { throw new FormulaError( '#VALUE!' ); } return $r; } /** Comparison: numeric when both sides read as numbers, otherwise case-insensitive text. */ private function compare( $a, $b ) { if ( null === $a && null === $b ) { return 0; } if ( null === $a ) { $a = is_string( $b ) ? '' : 0.0; } if ( null === $b ) { $b = is_string( $a ) ? '' : 0.0; } $na = $this->cmp_num( $a ); $nb = $this->cmp_num( $b ); if ( null !== $na && null !== $nb ) { return $na <=> $nb; } $x = $this->txt( $a ); $y = $this->txt( $b ); if ( function_exists( 'mb_strtolower' ) ) { $x = mb_strtolower( $x, 'UTF-8' ); $y = mb_strtolower( $y, 'UTF-8' ); } else { $x = strtolower( $x ); $y = strtolower( $y ); } return strcmp( $x, $y ) <=> 0; } private function cmp_num( $v ) { if ( is_bool( $v ) ) { return $v ? 1.0 : 0.0; } if ( is_int( $v ) || is_float( $v ) ) { return (float) $v; } return $this->parse_number( (string) $v ); } private function num( $v ) { if ( null === $v ) { return 0.0; } if ( is_bool( $v ) ) { return $v ? 1.0 : 0.0; } if ( is_int( $v ) || is_float( $v ) ) { return (float) $v; } if ( is_string( $v ) ) { $n = $this->parse_number( $v ); if ( null !== $n ) { return $n; } } throw new FormulaError( '#VALUE!' ); } private function txt( $v ) { if ( null === $v ) { return ''; } if ( is_bool( $v ) ) { return $v ? 'TRUE' : 'FALSE'; } if ( is_int( $v ) || is_float( $v ) ) { return self::fmt( (float) $v ); } if ( is_array( $v ) ) { throw new FormulaError( '#VALUE!' ); } return (string) $v; } private function truthy( $v ) { if ( is_bool( $v ) ) { return $v; } if ( null === $v ) { return false; } if ( is_int( $v ) || is_float( $v ) ) { return 0.0 !== (float) $v; } $u = strtoupper( trim( (string) $v ) ); if ( 'TRUE' === $u ) { return true; } if ( 'FALSE' === $u ) { return false; } $n = $this->parse_number( (string) $v ); if ( null === $n ) { throw new FormulaError( '#VALUE!' ); } return 0.0 !== $n; } /** Number to text: integers plain, others up to 10 decimals, no exponent, "." decimal separator. */ private static function fmt( $x ) { if ( is_nan( $x ) || is_infinite( $x ) ) { throw new FormulaError( '#VALUE!' ); } if ( $x == floor( $x ) && abs( $x ) < 1e15 ) { return (string) (int) $x; } $abs = abs( $x ); if ( $abs < 5e-11 ) { return '0'; } $dec = 10; if ( $abs >= 1 ) { $dec = max( 0, min( 10, 14 - (int) floor( log10( $abs ) ) ) ); } $s = number_format( $x, $dec, '.', '' ); if ( false !== strpos( $s, '.' ) ) { $s = rtrim( rtrim( $s, '0' ), '.' ); } return ( '' === $s || '-0' === $s ) ? '0' : $s; } /* --------------------------------------------------------------------- * Number parsing * ------------------------------------------------------------------ */ private function parse_number( $s ) { if ( array_key_exists( $s, $this->ncache ) ) { return $this->ncache[ $s ]; } return $this->ncache[ $s ] = self::pn( $s ); } /** "1,234.56", "1.234,56", "1 234,5", "$5", "12%", "₺15" to float; null when not a number. */ private static function pn( $s ) { $s = trim( str_replace( array( "\xC2\xA0", "\xE2\x80\xAF", "\xE2\x80\x89", "\xE2\x88\x92" ), array( ' ', ' ', ' ', '-' ), $s ) ); if ( '' === $s ) { return null; } $pct = false; if ( '%' === substr( $s, -1 ) ) { $pct = true; $s = rtrim( substr( $s, 0, -1 ) ); } if ( ! preg_match( '/^([-+]?)\s*(?:[$€£¥₺]\s*)?([-+]?)\s*(\d[\d.,\s]*|[.,]\d+)\s*(?:[$€£¥₺])?$/u', $s, $m ) ) { return null; } $neg = '-' === $m[1] || '-' === $m[2]; $b = trim( $m[3] ); if ( preg_match( '/\s/', $b ) ) { if ( ! preg_match( '/^\d{1,3}(?:\s\d{3})+(?:[.,]\d+)?$/', $b ) ) { return null; } $b = preg_replace( '/\s/', '', $b ); } $nd = substr_count( $b, '.' ); $nc = substr_count( $b, ',' ); if ( ! $nd && ! $nc ) { $v = (float) $b; } elseif ( $nd && $nc ) { $dec = strrpos( $b, '.' ) > strrpos( $b, ',' ) ? '.' : ','; $th = '.' === $dec ? ',' : '.'; if ( 1 !== substr_count( $b, $dec ) ) { return null; } if ( ! preg_match( '/^\d{1,3}(?:' . preg_quote( $th, '/' ) . '\d{3})+' . preg_quote( $dec, '/' ) . '\d+$/', $b ) ) { return null; } $v = (float) str_replace( array( $th, $dec ), array( '', '.' ), $b ); } else { $sep = $nd ? '.' : ','; if ( max( $nd, $nc ) > 1 ) { if ( ! preg_match( '/^\d{1,3}(?:' . preg_quote( $sep, '/' ) . '\d{3})+$/', $b ) ) { return null; } $v = (float) str_replace( $sep, '', $b ); } elseif ( ',' === $sep && preg_match( '/^[1-9]\d{0,2},\d{3}$/', $b ) ) { $v = (float) str_replace( ',', '', $b ); } else { $v = (float) str_replace( ',', '.', $b ); } } if ( $pct ) { $v /= 100; } return $neg ? -$v : $v; } /* --------------------------------------------------------------------- * Functions * ------------------------------------------------------------------ */ private function need( array $a, $min, $max ) { $n = count( $a ); if ( $n < $min || $n > $max ) { throw new FormulaError( '#ERROR!' ); } } /** Numbers from arguments; ranges/references skip text and empties (like Excel). */ private function collect( array $args, $lenient = false ) { $out = array(); foreach ( $args as $a ) { $v = $this->ev( $a ); if ( is_array( $v ) || 'r' === $a[0] ) { foreach ( is_array( $v ) ? $v : array( $v ) as $x ) { if ( is_float( $x ) || is_int( $x ) ) { $out[] = (float) $x; } elseif ( is_string( $x ) ) { $n = $this->parse_number( $x ); if ( null !== $n ) { $out[] = $n; } } } } elseif ( $lenient ) { if ( is_bool( $v ) ) { $out[] = $v ? 1.0 : 0.0; } elseif ( null !== $v ) { $n = is_string( $v ) ? $this->parse_number( $v ) : (float) $v; if ( null !== $n ) { $out[] = $n; } } } else { $out[] = $this->num( $v ); } } return $out; } /** All values flattened (ranges expanded). */ private function flat( array $args ) { $out = array(); foreach ( $args as $a ) { $v = $this->ev( $a ); if ( is_array( $v ) ) { foreach ( $v as $x ) { $out[] = $x; } } else { $out[] = $v; } } return $out; } private function round_dir( $x, $n, $mode ) { $m = pow( 10, $n ); $y = round( abs( $x ) * $m, 6 ); $y = 'up' === $mode ? ceil( $y ) : floor( $y ); return ( $x < 0 ? -1 : 1 ) * $y / $m; } private function call( $name, array $a ) { switch ( $name ) { case 'SUM': return array_sum( $this->collect( $a ) ); case 'AVERAGE': case 'AVG': $n = $this->collect( $a ); if ( ! $n ) { throw new FormulaError( '#DIV/0!' ); } return array_sum( $n ) / count( $n ); case 'MIN': case 'MAX': $n = $this->collect( $a ); if ( ! $n ) { return 0.0; } return 'MIN' === $name ? min( $n ) : max( $n ); case 'COUNT': return (float) count( $this->collect( $a, true ) ); case 'COUNTA': $k = 0; foreach ( $this->flat( $a ) as $v ) { if ( null !== $v && '' !== $v ) { $k++; } } return (float) $k; case 'PRODUCT': $n = $this->collect( $a ); return $n ? $this->finite( array_product( $n ) ) : 0.0; case 'MEDIAN': $n = $this->collect( $a ); if ( ! $n ) { throw new FormulaError( '#VALUE!' ); } sort( $n ); $h = intdiv( count( $n ), 2 ); return count( $n ) % 2 ? $n[ $h ] : ( $n[ $h - 1 ] + $n[ $h ] ) / 2; case 'ROUND': case 'ROUNDUP': case 'ROUNDDOWN': $this->need( $a, 1, 2 ); $x = $this->num( $this->sc( $a[0] ) ); $d = isset( $a[1] ) ? (int) $this->num( $this->sc( $a[1] ) ) : 0; if ( 'ROUND' === $name ) { return $this->finite( round( $x, $d ) ); } return $this->finite( $this->round_dir( $x, $d, 'ROUNDUP' === $name ? 'up' : 'down' ) ); case 'INT': $this->need( $a, 1, 1 ); return floor( $this->num( $this->sc( $a[0] ) ) ); case 'ABS': $this->need( $a, 1, 1 ); return abs( $this->num( $this->sc( $a[0] ) ) ); case 'SQRT': $this->need( $a, 1, 1 ); $x = $this->num( $this->sc( $a[0] ) ); if ( $x < 0 ) { throw new FormulaError( '#VALUE!' ); } return sqrt( $x ); case 'POWER': $this->need( $a, 2, 2 ); return $this->power( $this->num( $this->sc( $a[0] ) ), $this->num( $this->sc( $a[1] ) ) ); case 'MOD': $this->need( $a, 2, 2 ); $x = $this->num( $this->sc( $a[0] ) ); $y = $this->num( $this->sc( $a[1] ) ); if ( 0.0 === $y ) { throw new FormulaError( '#DIV/0!' ); } return $x - $y * floor( $x / $y ); case 'PI': $this->need( $a, 0, 0 ); return M_PI; case 'TRUE': case 'FALSE': $this->need( $a, 0, 0 ); return 'TRUE' === $name; case 'IF': $this->need( $a, 2, 3 ); if ( $this->truthy( $this->sc( $a[0] ) ) ) { return $this->ev( $a[1] ); } return isset( $a[2] ) ? $this->ev( $a[2] ) : false; case 'AND': case 'OR': $vals = array(); foreach ( $a as $node ) { $v = $this->ev( $node ); if ( is_array( $v ) || 'r' === $node[0] ) { foreach ( is_array( $v ) ? $v : array( $v ) as $x ) { if ( is_bool( $x ) || is_float( $x ) || is_int( $x ) ) { $vals[] = $this->truthy( $x ); } elseif ( is_string( $x ) ) { try { $vals[] = $this->truthy( $x ); } catch ( FormulaError $e ) { continue; } } } } else { $vals[] = $this->truthy( $v ); } } if ( ! $vals ) { throw new FormulaError( '#VALUE!' ); } return 'AND' === $name ? ! in_array( false, $vals, true ) : in_array( true, $vals, true ); case 'NOT': $this->need( $a, 1, 1 ); return ! $this->truthy( $this->sc( $a[0] ) ); case 'IFERROR': $this->need( $a, 2, 2 ); try { $v = $this->sc( $a[0] ); return $v; } catch ( FormulaError $e ) { return $this->ev( $a[1] ); } case 'CONCAT': case 'CONCATENATE': $s = ''; foreach ( $this->flat( $a ) as $v ) { $s .= $this->txt( $v ); } return $s; case 'FIXED': $this->need( $a, 1, 3 ); $x = $this->num( $this->sc( $a[0] ) ); $d = isset( $a[1] ) ? (int) $this->num( $this->sc( $a[1] ) ) : 2; $nc = isset( $a[2] ) ? $this->truthy( $this->sc( $a[2] ) ) : false; $x = round( $x, $d ); $s = number_format( $x, max( 0, $d ), '.', $nc ? '' : ',' ); if ( 0.0 === (float) $x && '-' === substr( $s, 0, 1 ) ) { $s = substr( $s, 1 ); } return $s; case 'ROW': case 'COLUMN': $this->need( $a, 0, 1 ); $i = 'ROW' === $name ? 0 : 1; if ( ! $a ) { return (float) ( $this->cur[ $i ] + 1 ); } if ( 'r' === $a[0][0] ) { return (float) ( $a[0][1 + $i] + 1 ); } if ( 'g' === $a[0][0] ) { return (float) ( $a[0][1 + $i] + 1 ); } throw new FormulaError( '#VALUE!' ); } throw new FormulaError( '#NAME?' ); } }