danielebarchiesi@0: danielebarchiesi@0: danielebarchiesi@0: ================================================================================ danielebarchiesi@0: danielebarchiesi@0: NAME danielebarchiesi@0: ctools_math_expr - safely evaluate math expressions danielebarchiesi@0: danielebarchiesi@0: SYNOPSIS danielebarchiesi@0: include('ctools_math_expr.class.php'); danielebarchiesi@0: $m = new ctools_math_expr; danielebarchiesi@0: // basic evaluation: danielebarchiesi@0: $result = $m->evaluate('2+2'); danielebarchiesi@0: // supports: order of operation; parentheses; negation; built-in functions danielebarchiesi@0: $result = $m->evaluate('-8(5/2)^2*(1-sqrt(4))-8'); danielebarchiesi@0: // create your own variables danielebarchiesi@0: $m->evaluate('a = e^(ln(pi))'); danielebarchiesi@0: // or functions danielebarchiesi@0: $m->evaluate('f(x,y) = x^2 + y^2 - 2x*y + 1'); danielebarchiesi@0: // and then use them danielebarchiesi@0: $result = $m->evaluate('3*f(42,a)'); danielebarchiesi@0: danielebarchiesi@0: DESCRIPTION danielebarchiesi@0: Use the ctools_math_expr class when you want to evaluate mathematical expressions danielebarchiesi@0: from untrusted sources. You can define your own variables and functions, danielebarchiesi@0: which are stored in the object. Try it, it's fun! danielebarchiesi@0: danielebarchiesi@0: METHODS danielebarchiesi@0: $m->evalute($expr) danielebarchiesi@0: Evaluates the expression and returns the result. If an error occurs, danielebarchiesi@0: prints a warning and returns false. If $expr is a function assignment, danielebarchiesi@0: returns true on success. danielebarchiesi@0: danielebarchiesi@0: $m->e($expr) danielebarchiesi@0: A synonym for $m->evaluate(). danielebarchiesi@0: danielebarchiesi@0: $m->vars() danielebarchiesi@0: Returns an associative array of all user-defined variables and values. danielebarchiesi@0: danielebarchiesi@0: $m->funcs() danielebarchiesi@0: Returns an array of all user-defined functions. danielebarchiesi@0: danielebarchiesi@0: PARAMETERS danielebarchiesi@0: $m->suppress_errors danielebarchiesi@0: Set to true to turn off warnings when evaluating expressions danielebarchiesi@0: danielebarchiesi@0: $m->last_error danielebarchiesi@0: If the last evaluation failed, contains a string describing the error. danielebarchiesi@0: (Useful when suppress_errors is on). danielebarchiesi@0: danielebarchiesi@0: AUTHOR INFORMATION danielebarchiesi@0: Copyright 2005, Miles Kaufmann. danielebarchiesi@0: danielebarchiesi@0: LICENSE danielebarchiesi@0: Redistribution and use in source and binary forms, with or without danielebarchiesi@0: modification, are permitted provided that the following conditions are danielebarchiesi@0: met: danielebarchiesi@0: danielebarchiesi@0: 1 Redistributions of source code must retain the above copyright danielebarchiesi@0: notice, this list of conditions and the following disclaimer. danielebarchiesi@0: 2. Redistributions in binary form must reproduce the above copyright danielebarchiesi@0: notice, this list of conditions and the following disclaimer in the danielebarchiesi@0: documentation and/or other materials provided with the distribution. danielebarchiesi@0: 3. The name of the author may not be used to endorse or promote danielebarchiesi@0: products derived from this software without specific prior written danielebarchiesi@0: permission. danielebarchiesi@0: danielebarchiesi@0: THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR danielebarchiesi@0: IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED danielebarchiesi@0: WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE danielebarchiesi@0: DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, danielebarchiesi@0: INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES danielebarchiesi@0: (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR danielebarchiesi@0: SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) danielebarchiesi@0: HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, danielebarchiesi@0: STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN danielebarchiesi@0: ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE danielebarchiesi@0: POSSIBILITY OF SUCH DAMAGE. danielebarchiesi@0: danielebarchiesi@0: */ danielebarchiesi@0: danielebarchiesi@0: class ctools_math_expr { danielebarchiesi@0: var $suppress_errors = false; danielebarchiesi@0: var $last_error = null; danielebarchiesi@0: danielebarchiesi@0: var $v = array('e'=>2.71,'pi'=>3.14); // variables (and constants) danielebarchiesi@0: var $f = array(); // user-defined functions danielebarchiesi@0: var $vb = array('e', 'pi'); // constants danielebarchiesi@0: var $fb = array( // built-in functions danielebarchiesi@0: 'sin','sinh','arcsin','asin','arcsinh','asinh', danielebarchiesi@0: 'cos','cosh','arccos','acos','arccosh','acosh', danielebarchiesi@0: 'tan','tanh','arctan','atan','arctanh','atanh', danielebarchiesi@0: 'pow', 'exp', danielebarchiesi@0: 'sqrt','abs','ln','log', danielebarchiesi@0: 'time', 'ceil', 'floor', 'min', 'max', 'round'); danielebarchiesi@0: danielebarchiesi@0: function ctools_math_expr() { danielebarchiesi@0: // make the variables a little more accurate danielebarchiesi@0: $this->v['pi'] = pi(); danielebarchiesi@0: $this->v['e'] = exp(1); danielebarchiesi@0: drupal_alter('ctools_math_expression_functions', $this->fb); danielebarchiesi@0: } danielebarchiesi@0: danielebarchiesi@0: function e($expr) { danielebarchiesi@0: return $this->evaluate($expr); danielebarchiesi@0: } danielebarchiesi@0: danielebarchiesi@0: function evaluate($expr) { danielebarchiesi@0: $this->last_error = null; danielebarchiesi@0: $expr = trim($expr); danielebarchiesi@0: if (substr($expr, -1, 1) == ';') $expr = substr($expr, 0, strlen($expr)-1); // strip semicolons at the end danielebarchiesi@0: //=============== danielebarchiesi@0: // is it a variable assignment? danielebarchiesi@0: if (preg_match('/^\s*([a-z]\w*)\s*=\s*(.+)$/', $expr, $matches)) { danielebarchiesi@0: if (in_array($matches[1], $this->vb)) { // make sure we're not assigning to a constant danielebarchiesi@0: return $this->trigger("cannot assign to constant '$matches[1]'"); danielebarchiesi@0: } danielebarchiesi@0: if (($tmp = $this->pfx($this->nfx($matches[2]))) === false) return false; // get the result and make sure it's good danielebarchiesi@0: $this->v[$matches[1]] = $tmp; // if so, stick it in the variable array danielebarchiesi@0: return $this->v[$matches[1]]; // and return the resulting value danielebarchiesi@0: //=============== danielebarchiesi@0: // is it a function assignment? danielebarchiesi@0: } elseif (preg_match('/^\s*([a-z]\w*)\s*\(\s*([a-z]\w*(?:\s*,\s*[a-z]\w*)*)\s*\)\s*=\s*(.+)$/', $expr, $matches)) { danielebarchiesi@0: $fnn = $matches[1]; // get the function name danielebarchiesi@0: if (in_array($matches[1], $this->fb)) { // make sure it isn't built in danielebarchiesi@0: return $this->trigger("cannot redefine built-in function '$matches[1]()'"); danielebarchiesi@0: } danielebarchiesi@0: $args = explode(",", preg_replace("/\s+/", "", $matches[2])); // get the arguments danielebarchiesi@0: if (($stack = $this->nfx($matches[3])) === false) return false; // see if it can be converted to postfix danielebarchiesi@0: for ($i = 0; $iv)) { danielebarchiesi@0: $stack[$i] = $this->v[$token]; danielebarchiesi@0: } else { danielebarchiesi@0: return $this->trigger("undefined variable '$token' in function definition"); danielebarchiesi@0: } danielebarchiesi@0: } danielebarchiesi@0: } danielebarchiesi@0: $this->f[$fnn] = array('args'=>$args, 'func'=>$stack); danielebarchiesi@0: return true; danielebarchiesi@0: //=============== danielebarchiesi@0: } else { danielebarchiesi@0: return $this->pfx($this->nfx($expr)); // straight up evaluation, woo danielebarchiesi@0: } danielebarchiesi@0: } danielebarchiesi@0: danielebarchiesi@0: function vars() { danielebarchiesi@0: $output = $this->v; danielebarchiesi@0: unset($output['pi']); danielebarchiesi@0: unset($output['e']); danielebarchiesi@0: return $output; danielebarchiesi@0: } danielebarchiesi@0: danielebarchiesi@0: function funcs() { danielebarchiesi@0: $output = array(); danielebarchiesi@0: foreach ($this->f as $fnn=>$dat) danielebarchiesi@0: $output[] = $fnn . '(' . implode(',', $dat['args']) . ')'; danielebarchiesi@0: return $output; danielebarchiesi@0: } danielebarchiesi@0: danielebarchiesi@0: //===================== HERE BE INTERNAL METHODS ====================\\ danielebarchiesi@0: danielebarchiesi@0: // Convert infix to postfix notation danielebarchiesi@0: function nfx($expr) { danielebarchiesi@0: danielebarchiesi@0: $index = 0; danielebarchiesi@0: $stack = new ctools_math_expr_stack; danielebarchiesi@0: $output = array(); // postfix form of expression, to be passed to pfx() danielebarchiesi@0: $expr = trim(strtolower($expr)); danielebarchiesi@0: danielebarchiesi@0: $ops = array('+', '-', '*', '/', '^', '_'); danielebarchiesi@0: $ops_r = array('+'=>0,'-'=>0,'*'=>0,'/'=>0,'^'=>1); // right-associative operator? danielebarchiesi@0: $ops_p = array('+'=>0,'-'=>0,'*'=>1,'/'=>1,'_'=>1,'^'=>2); // operator precedence danielebarchiesi@0: danielebarchiesi@0: $expecting_op = false; // we use this in syntax-checking the expression danielebarchiesi@0: // and determining when a - is a negation danielebarchiesi@0: danielebarchiesi@0: if (preg_match("/[^\w\s+*^\/()\.,-]/", $expr, $matches)) { // make sure the characters are all good danielebarchiesi@0: return $this->trigger("illegal character '{$matches[0]}'"); danielebarchiesi@0: } danielebarchiesi@0: danielebarchiesi@0: while(1) { // 1 Infinite Loop ;) danielebarchiesi@0: $op = substr($expr, $index, 1); // get the first character at the current index danielebarchiesi@0: // find out if we're currently at the beginning of a number/variable/function/parenthesis/operand danielebarchiesi@0: $ex = preg_match('/^([a-z]\w*\(?|\d+(?:\.\d*)?|\.\d+|\()/', substr($expr, $index), $match); danielebarchiesi@0: //=============== danielebarchiesi@0: if ($op == '-' and !$expecting_op) { // is it a negation instead of a minus? danielebarchiesi@0: $stack->push('_'); // put a negation on the stack danielebarchiesi@0: $index++; danielebarchiesi@0: } elseif ($op == '_') { // we have to explicitly deny this, because it's legal on the stack danielebarchiesi@0: return $this->trigger("illegal character '_'"); // but not in the input expression danielebarchiesi@0: //=============== danielebarchiesi@0: } elseif ((in_array($op, $ops) or $ex) and $expecting_op) { // are we putting an operator on the stack? danielebarchiesi@0: if ($ex) { // are we expecting an operator but have a number/variable/function/opening parethesis? danielebarchiesi@0: $op = '*'; $index--; // it's an implicit multiplication danielebarchiesi@0: } danielebarchiesi@0: // heart of the algorithm: danielebarchiesi@0: while($stack->count > 0 and ($o2 = $stack->last()) and in_array($o2, $ops) and ($ops_r[$op] ? $ops_p[$op] < $ops_p[$o2] : $ops_p[$op] <= $ops_p[$o2])) { danielebarchiesi@0: $output[] = $stack->pop(); // pop stuff off the stack into the output danielebarchiesi@0: } danielebarchiesi@0: // many thanks: http://en.wikipedia.org/wiki/Reverse_Polish_notation#The_algorithm_in_detail danielebarchiesi@0: $stack->push($op); // finally put OUR operator onto the stack danielebarchiesi@0: $index++; danielebarchiesi@0: $expecting_op = false; danielebarchiesi@0: //=============== danielebarchiesi@0: } elseif ($op == ')' and $expecting_op) { // ready to close a parenthesis? danielebarchiesi@0: while (($o2 = $stack->pop()) != '(') { // pop off the stack back to the last ( danielebarchiesi@0: if (is_null($o2)) return $this->trigger("unexpected ')'"); danielebarchiesi@0: else $output[] = $o2; danielebarchiesi@0: } danielebarchiesi@0: if (preg_match("/^([a-z]\w*)\($/", $stack->last(2), $matches)) { // did we just close a function? danielebarchiesi@0: $fnn = $matches[1]; // get the function name danielebarchiesi@0: $arg_count = $stack->pop(); // see how many arguments there were (cleverly stored on the stack, thank you) danielebarchiesi@0: $output[] = $stack->pop(); // pop the function and push onto the output danielebarchiesi@0: if (in_array($fnn, $this->fb)) { // check the argument count danielebarchiesi@0: if($arg_count > 1) danielebarchiesi@0: return $this->trigger("too many arguments ($arg_count given, 1 expected)"); danielebarchiesi@0: } elseif (array_key_exists($fnn, $this->f)) { danielebarchiesi@0: if ($arg_count != count($this->f[$fnn]['args'])) danielebarchiesi@0: return $this->trigger("wrong number of arguments ($arg_count given, " . count($this->f[$fnn]['args']) . " expected)"); danielebarchiesi@0: } else { // did we somehow push a non-function on the stack? this should never happen danielebarchiesi@0: return $this->trigger("internal error"); danielebarchiesi@0: } danielebarchiesi@0: } danielebarchiesi@0: $index++; danielebarchiesi@0: //=============== danielebarchiesi@0: } elseif ($op == ',' and $expecting_op) { // did we just finish a function argument? danielebarchiesi@0: while (($o2 = $stack->pop()) != '(') { danielebarchiesi@0: if (is_null($o2)) return $this->trigger("unexpected ','"); // oops, never had a ( danielebarchiesi@0: else $output[] = $o2; // pop the argument expression stuff and push onto the output danielebarchiesi@0: } danielebarchiesi@0: // make sure there was a function danielebarchiesi@0: if (!preg_match("/^([a-z]\w*)\($/", $stack->last(2), $matches)) danielebarchiesi@0: return $this->trigger("unexpected ','"); danielebarchiesi@0: $stack->push($stack->pop()+1); // increment the argument count danielebarchiesi@0: $stack->push('('); // put the ( back on, we'll need to pop back to it again danielebarchiesi@0: $index++; danielebarchiesi@0: $expecting_op = false; danielebarchiesi@0: //=============== danielebarchiesi@0: } elseif ($op == '(' and !$expecting_op) { danielebarchiesi@0: $stack->push('('); // that was easy danielebarchiesi@0: $index++; danielebarchiesi@0: $allow_neg = true; danielebarchiesi@0: //=============== danielebarchiesi@0: } elseif ($ex and !$expecting_op) { // do we now have a function/variable/number? danielebarchiesi@0: $expecting_op = true; danielebarchiesi@0: $val = $match[1]; danielebarchiesi@0: if (preg_match("/^([a-z]\w*)\($/", $val, $matches)) { // may be func, or variable w/ implicit multiplication against parentheses... danielebarchiesi@0: if (in_array($matches[1], $this->fb) or array_key_exists($matches[1], $this->f)) { // it's a func danielebarchiesi@0: $stack->push($val); danielebarchiesi@0: $stack->push(1); danielebarchiesi@0: $stack->push('('); danielebarchiesi@0: $expecting_op = false; danielebarchiesi@0: } else { // it's a var w/ implicit multiplication danielebarchiesi@0: $val = $matches[1]; danielebarchiesi@0: $output[] = $val; danielebarchiesi@0: } danielebarchiesi@0: } else { // it's a plain old var or num danielebarchiesi@0: $output[] = $val; danielebarchiesi@0: } danielebarchiesi@0: $index += strlen($val); danielebarchiesi@0: //=============== danielebarchiesi@0: } elseif ($op == ')') { // miscellaneous error checking danielebarchiesi@0: return $this->trigger("unexpected ')'"); danielebarchiesi@0: } elseif (in_array($op, $ops) and !$expecting_op) { danielebarchiesi@0: return $this->trigger("unexpected operator '$op'"); danielebarchiesi@0: } else { // I don't even want to know what you did to get here danielebarchiesi@0: return $this->trigger("an unexpected error occured"); danielebarchiesi@0: } danielebarchiesi@0: if ($index == strlen($expr)) { danielebarchiesi@0: if (in_array($op, $ops)) { // did we end with an operator? bad. danielebarchiesi@0: return $this->trigger("operator '$op' lacks operand"); danielebarchiesi@0: } else { danielebarchiesi@0: break; danielebarchiesi@0: } danielebarchiesi@0: } danielebarchiesi@0: while (substr($expr, $index, 1) == ' ') { // step the index past whitespace (pretty much turns whitespace danielebarchiesi@0: $index++; // into implicit multiplication if no operator is there) danielebarchiesi@0: } danielebarchiesi@0: danielebarchiesi@0: } danielebarchiesi@0: while (!is_null($op = $stack->pop())) { // pop everything off the stack and push onto output danielebarchiesi@0: if ($op == '(') return $this->trigger("expecting ')'"); // if there are (s on the stack, ()s were unbalanced danielebarchiesi@0: $output[] = $op; danielebarchiesi@0: } danielebarchiesi@0: return $output; danielebarchiesi@0: } danielebarchiesi@0: danielebarchiesi@0: // evaluate postfix notation danielebarchiesi@0: function pfx($tokens, $vars = array()) { danielebarchiesi@0: danielebarchiesi@0: if ($tokens == false) return false; danielebarchiesi@0: danielebarchiesi@0: $stack = new ctools_math_expr_stack; danielebarchiesi@0: danielebarchiesi@0: foreach ($tokens as $token) { // nice and easy danielebarchiesi@0: // if the token is a binary operator, pop two values off the stack, do the operation, and push the result back on danielebarchiesi@0: if (in_array($token, array('+', '-', '*', '/', '^'))) { danielebarchiesi@0: if (is_null($op2 = $stack->pop())) return $this->trigger("internal error"); danielebarchiesi@0: if (is_null($op1 = $stack->pop())) return $this->trigger("internal error"); danielebarchiesi@0: switch ($token) { danielebarchiesi@0: case '+': danielebarchiesi@0: $stack->push($op1+$op2); break; danielebarchiesi@0: case '-': danielebarchiesi@0: $stack->push($op1-$op2); break; danielebarchiesi@0: case '*': danielebarchiesi@0: $stack->push($op1*$op2); break; danielebarchiesi@0: case '/': danielebarchiesi@0: if ($op2 == 0) return $this->trigger("division by zero"); danielebarchiesi@0: $stack->push($op1/$op2); break; danielebarchiesi@0: case '^': danielebarchiesi@0: $stack->push(pow($op1, $op2)); break; danielebarchiesi@0: } danielebarchiesi@0: // if the token is a unary operator, pop one value off the stack, do the operation, and push it back on danielebarchiesi@0: } elseif ($token == "_") { danielebarchiesi@0: $stack->push(-1*$stack->pop()); danielebarchiesi@0: // if the token is a function, pop arguments off the stack, hand them to the function, and push the result back on danielebarchiesi@0: } elseif (preg_match("/^([a-z]\w*)\($/", $token, $matches)) { // it's a function! danielebarchiesi@0: $fnn = $matches[1]; danielebarchiesi@0: if (in_array($fnn, $this->fb)) { // built-in function: danielebarchiesi@0: if (is_null($op1 = $stack->pop())) return $this->trigger("internal error"); danielebarchiesi@0: $fnn = preg_replace("/^arc/", "a", $fnn); // for the 'arc' trig synonyms danielebarchiesi@0: if ($fnn == 'ln') $fnn = 'log'; danielebarchiesi@0: eval('$stack->push(' . $fnn . '($op1));'); // perfectly safe eval() danielebarchiesi@0: } elseif (array_key_exists($fnn, $this->f)) { // user function danielebarchiesi@0: // get args danielebarchiesi@0: $args = array(); danielebarchiesi@0: for ($i = count($this->f[$fnn]['args'])-1; $i >= 0; $i--) { danielebarchiesi@0: if (is_null($args[$this->f[$fnn]['args'][$i]] = $stack->pop())) return $this->trigger("internal error"); danielebarchiesi@0: } danielebarchiesi@0: $stack->push($this->pfx($this->f[$fnn]['func'], $args)); // yay... recursion!!!! danielebarchiesi@0: } danielebarchiesi@0: // if the token is a number or variable, push it on the stack danielebarchiesi@0: } else { danielebarchiesi@0: if (is_numeric($token)) { danielebarchiesi@0: $stack->push($token); danielebarchiesi@0: } elseif (array_key_exists($token, $this->v)) { danielebarchiesi@0: $stack->push($this->v[$token]); danielebarchiesi@0: } elseif (array_key_exists($token, $vars)) { danielebarchiesi@0: $stack->push($vars[$token]); danielebarchiesi@0: } else { danielebarchiesi@0: return $this->trigger("undefined variable '$token'"); danielebarchiesi@0: } danielebarchiesi@0: } danielebarchiesi@0: } danielebarchiesi@0: // when we're out of tokens, the stack should have a single element, the final result danielebarchiesi@0: if ($stack->count != 1) return $this->trigger("internal error"); danielebarchiesi@0: return $stack->pop(); danielebarchiesi@0: } danielebarchiesi@0: danielebarchiesi@0: // trigger an error, but nicely, if need be danielebarchiesi@0: function trigger($msg) { danielebarchiesi@0: $this->last_error = $msg; danielebarchiesi@0: if (!$this->suppress_errors) trigger_error($msg, E_USER_WARNING); danielebarchiesi@0: return false; danielebarchiesi@0: } danielebarchiesi@0: } danielebarchiesi@0: danielebarchiesi@0: // for internal use danielebarchiesi@0: class ctools_math_expr_stack { danielebarchiesi@0: danielebarchiesi@0: var $stack = array(); danielebarchiesi@0: var $count = 0; danielebarchiesi@0: danielebarchiesi@0: function push($val) { danielebarchiesi@0: $this->stack[$this->count] = $val; danielebarchiesi@0: $this->count++; danielebarchiesi@0: } danielebarchiesi@0: danielebarchiesi@0: function pop() { danielebarchiesi@0: if ($this->count > 0) { danielebarchiesi@0: $this->count--; danielebarchiesi@0: return $this->stack[$this->count]; danielebarchiesi@0: } danielebarchiesi@0: return null; danielebarchiesi@0: } danielebarchiesi@0: danielebarchiesi@0: function last($n=1) { danielebarchiesi@0: return !empty($this->stack[$this->count-$n]) ? $this->stack[$this->count-$n] : NULL; danielebarchiesi@0: } danielebarchiesi@0: } danielebarchiesi@0: