dolibarr  13.0.2
evalmath.class.php
Go to the documentation of this file.
1 <?php
2 /*
3  * ================================================================================
4  *
5  * EvalMath - PHP Class to safely evaluate math expressions
6  * Copyright (C) 2005 Miles Kaufmann <http://www.twmagic.com/>
7  *
8  * ================================================================================
9  *
10  * NAME
11  * EvalMath - safely evaluate math expressions
12  *
13  * SYNOPSIS
14  * include('evalmath.class.php');
15  * $m = new EvalMath;
16  * // basic evaluation:
17  * $result = $m->evaluate('2+2');
18  * // supports: order of operation; parentheses; negation; built-in functions
19  * $result = $m->evaluate('-8(5/2)^2*(1-sqrt(4))-8');
20  * // create your own variables
21  * $m->evaluate('a = e^(ln(pi))');
22  * // or functions
23  * $m->evaluate('f(x,y) = x^2 + y^2 - 2x*y + 1');
24  * // and then use them
25  * $result = $m->evaluate('3*f(42,a)');
26  *
27  * DESCRIPTION
28  * Use the EvalMath class when you want to evaluate mathematical expressions
29  * from untrusted sources. You can define your own variables and functions,
30  * which are stored in the object. Try it, it's fun!
31  *
32  * METHODS
33  * $m->evalute($expr)
34  * Evaluates the expression and returns the result. If an error occurs,
35  * prints a warning and returns false. If $expr is a function assignment,
36  * returns true on success.
37  *
38  * $m->e($expr)
39  * A synonym for $m->evaluate().
40  *
41  * $m->vars()
42  * Returns an associative array of all user-defined variables and values.
43  *
44  * $m->funcs()
45  * Returns an array of all user-defined functions.
46  *
47  * PARAMETERS
48  * $m->suppress_errors
49  * Set to true to turn off warnings when evaluating expressions
50  *
51  * $m->last_error
52  * If the last evaluation failed, contains a string describing the error.
53  * (Useful when suppress_errors is on).
54  *
55  * $m->last_error_code
56  * If the last evaluation failed, 2 element array with numeric code and extra info
57  *
58  * AUTHOR INFORMATION
59  * Copyright 2005, Miles Kaufmann.
60  *
61  * LICENSE
62  * Redistribution and use in source and binary forms, with or without
63  * modification, are permitted provided that the following conditions are
64  * met:
65  *
66  * 1 Redistributions of source code must retain the above copyright
67  * notice, this list of conditions and the following disclaimer.
68  * 2. Redistributions in binary form must reproduce the above copyright
69  * notice, this list of conditions and the following disclaimer in the
70  * documentation and/or other materials provided with the distribution.
71  * 3. The name of the author may not be used to endorse or promote
72  * products derived from this software without specific prior written
73  * permission.
74  *
75  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
76  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
77  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
78  * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
79  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
80  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
81  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
82  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
83  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
84  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
85  * POSSIBILITY OF SUCH DAMAGE.
86  */
87 
97 class EvalMath
98 {
99 
100  public $suppress_errors = false;
101 
102  public $last_error = null;
103 
104  public $last_error_code = null;
105 
106  public $v = array('e' => 2.71, 'pi' => 3.14159);
107 
108  // variables (and constants)
109  public $f = array();
110 
111  // user-defined functions
112  public $vb = array('e', 'pi');
113 
114  // constants
115  public $fb = array( // built-in functions
116  'sin', 'sinh', 'arcsin', 'asin', 'arcsinh', 'asinh', 'cos', 'cosh', 'arccos', 'acos', 'arccosh', 'acosh', 'tan', 'tanh', 'arctan', 'atan', 'arctanh', 'atanh', 'sqrt', 'abs', 'ln', 'log', 'intval');
117 
121  public function __construct()
122  {
123  // make the variables a little more accurate
124  $this->v['pi'] = pi();
125  $this->v['e'] = exp(1);
126  }
127 
134  public function e($expr)
135  {
136  return $this->evaluate($expr);
137  }
138 
145  public function evaluate($expr)
146  {
147  $this->last_error = null;
148  $this->last_error_code = null;
149  $expr = trim($expr);
150  if (substr($expr, - 1, 1) == ';')
151  $expr = substr($expr, 0, strlen($expr) - 1); // strip semicolons at the end
152  // ===============
153  // is it a variable assignment?
154  $matches = array();
155  if (preg_match('/^\s*([a-z]\w*)\s*=\s*(.+)$/', $expr, $matches)) {
156  if (in_array($matches[1], $this->vb)) { // make sure we're not assigning to a constant
157  return $this->trigger(1, "cannot assign to constant '$matches[1]'", $matches[1]);
158  }
159  if (($tmp = $this->pfx($this->nfx($matches[2]))) === false)
160  return false; // get the result and make sure it's good
161  $this->v[$matches[1]] = $tmp; // if so, stick it in the variable array
162  return $this->v[$matches[1]]; // and return the resulting value
163  // ===============
164  // is it a function assignment?
165  } elseif (preg_match('/^\s*([a-z]\w*)\s*\(\s*([a-z]\w*(?:\s*,\s*[a-z]\w*)*)\s*\)\s*=\s*(.+)$/', $expr, $matches)) {
166  $fnn = $matches[1]; // get the function name
167  if (in_array($matches[1], $this->fb)) { // make sure it isn't built in
168  return $this->trigger(2, "cannot redefine built-in function '$matches[1]()'", $matches[1]);
169  }
170  $args = explode(",", preg_replace("/\s+/", "", $matches[2])); // get the arguments
171  if (($stack = $this->nfx($matches[3])) === false)
172  return false; // see if it can be converted to postfix
173  $nbstack = count($stack);
174  for ($i = 0; $i < $nbstack; $i++) { // freeze the state of the non-argument variables
175  $token = $stack[$i];
176  if (preg_match('/^[a-z]\w*$/', $token) and !in_array($token, $args)) {
177  if (array_key_exists($token, $this->v)) {
178  $stack[$i] = $this->v[$token];
179  } else {
180  return $this->trigger(3, "undefined variable '$token' in function definition", $token);
181  }
182  }
183  }
184  $this->f[$fnn] = array('args' => $args, 'func' => $stack);
185  return true;
186  // ===============
187  } else {
188  return $this->pfx($this->nfx($expr)); // straight up evaluation, woo
189  }
190  }
191 
197  public function vars()
198  {
199  $output = $this->v;
200  unset($output['pi']);
201  unset($output['e']);
202  return $output;
203  }
204 
210  private function funcs()
211  {
212  $output = array();
213  foreach ($this->f as $fnn => $dat)
214  $output[] = $fnn.'('.implode(',', $dat['args']).')';
215  return $output;
216  }
217 
218  // ===================== HERE BE INTERNAL METHODS ====================\\
219 
226  private function nfx($expr)
227  {
228  $index = 0;
229  $stack = new EvalMathStack();
230  $output = array(); // postfix form of expression, to be passed to pfx()
231  $expr = trim(strtolower($expr));
232 
233  $ops = array('+', '-', '*', '/', '^', '_');
234  $ops_r = array('+' => 0, '-' => 0, '*' => 0, '/' => 0, '^' => 1); // right-associative operator?
235  $ops_p = array('+' => 0, '-' => 0, '*' => 1, '/' => 1, '_' => 1, '^' => 2); // operator precedence
236 
237  $expecting_op = false; // we use this in syntax-checking the expression
238  // and determining when a - is a negation
239 
240  $matches = array();
241  if (preg_match("/[^\w\s+*^\/()\.,-]/", $expr, $matches)) { // make sure the characters are all good
242  return $this->trigger(4, "illegal character '{$matches[0]}'", $matches[0]);
243  }
244 
245  while (1) { // 1 Infinite Loop ;)
246  $op = substr($expr, $index, 1); // get the first character at the current index
247  // find out if we're currently at the beginning of a number/variable/function/parenthesis/operand
248  $match = array();
249  $ex = preg_match('/^([a-z]\w*\(?|\d+(?:\.\d*)?|\.\d+|\()/', substr($expr, $index), $match);
250  // ===============
251  if ($op == '-' and !$expecting_op) { // is it a negation instead of a minus?
252  $stack->push('_'); // put a negation on the stack
253  $index++;
254  } elseif ($op == '_') { // we have to explicitly deny this, because it's legal on the stack
255  return $this->trigger(4, "illegal character '_'", "_"); // but not in the input expression
256  // ===============
257  } elseif ((in_array($op, $ops) or $ex) and $expecting_op) { // are we putting an operator on the stack?
258  if ($ex) { // are we expecting an operator but have a number/variable/function/opening parethesis?
259  $op = '*';
260  $index--; // it's an implicit multiplication
261  }
262  // heart of the algorithm:
263  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])) {
264  $output[] = $stack->pop(); // pop stuff off the stack into the output
265  }
266  // many thanks: http://en.wikipedia.org/wiki/Reverse_Polish_notation#The_algorithm_in_detail
267  $stack->push($op); // finally put OUR operator onto the stack
268  $index++;
269  $expecting_op = false;
270  // ===============
271  } elseif ($op == ')' and $expecting_op) { // ready to close a parenthesis?
272  while (($o2 = $stack->pop()) != '(') { // pop off the stack back to the last (
273  if (is_null($o2)) {
274  return $this->trigger(5, "unexpected ')'", ")");
275  } else {
276  $output[] = $o2;
277  }
278  }
279  if (preg_match("/^([a-z]\w*)\($/", $stack->last(2), $matches)) { // did we just close a function?
280  $fnn = $matches[1]; // get the function name
281  $arg_count = $stack->pop(); // see how many arguments there were (cleverly stored on the stack, thank you)
282  $output[] = $stack->pop(); // pop the function and push onto the output
283  if (in_array($fnn, $this->fb)) { // check the argument count
284  if ($arg_count > 1)
285  return $this->trigger(6, "wrong number of arguments ($arg_count given, 1 expected)", array($arg_count, 1));
286  } elseif (array_key_exists($fnn, $this->f)) {
287  if ($arg_count != count($this->f[$fnn]['args']))
288  return $this->trigger(6, "wrong number of arguments ($arg_count given, ".count($this->f[$fnn]['args'])." expected)", array($arg_count, count($this->f[$fnn]['args'])));
289  } else { // did we somehow push a non-function on the stack? this should never happen
290  return $this->trigger(7, "internal error");
291  }
292  }
293  $index++;
294  // ===============
295  } elseif ($op == ',' and $expecting_op) { // did we just finish a function argument?
296  while (($o2 = $stack->pop()) != '(') {
297  if (is_null($o2)) {
298  return $this->trigger(5, "unexpected ','", ","); // oops, never had a (
299  } else {
300  $output[] = $o2; // pop the argument expression stuff and push onto the output
301  }
302  }
303  // make sure there was a function
304  if (!preg_match("/^([a-z]\w*)\($/", $stack->last(2), $matches))
305  return $this->trigger(5, "unexpected ','", ",");
306  $stack->push($stack->pop() + 1); // increment the argument count
307  $stack->push('('); // put the ( back on, we'll need to pop back to it again
308  $index++;
309  $expecting_op = false;
310  // ===============
311  } elseif ($op == '(' and !$expecting_op) {
312  $stack->push('('); // that was easy
313  $index++;
314  $allow_neg = true;
315  // ===============
316  } elseif ($ex and !$expecting_op) { // do we now have a function/variable/number?
317  $expecting_op = true;
318  $val = $match[1];
319  if (preg_match("/^([a-z]\w*)\($/", $val, $matches)) { // may be func, or variable w/ implicit multiplication against parentheses...
320  if (in_array($matches[1], $this->fb) or array_key_exists($matches[1], $this->f)) { // it's a func
321  $stack->push($val);
322  $stack->push(1);
323  $stack->push('(');
324  $expecting_op = false;
325  } else { // it's a var w/ implicit multiplication
326  $val = $matches[1];
327  $output[] = $val;
328  }
329  } else { // it's a plain old var or num
330  $output[] = $val;
331  }
332  $index += strlen($val);
333  // ===============
334  } elseif ($op == ')') { // miscellaneous error checking
335  return $this->trigger(5, "unexpected ')'", ")");
336  } elseif (in_array($op, $ops) and !$expecting_op) {
337  return $this->trigger(8, "unexpected operator '$op'", $op);
338  } else { // I don't even want to know what you did to get here
339  return $this->trigger(9, "an unexpected error occured");
340  }
341  if ($index == strlen($expr)) {
342  if (in_array($op, $ops)) { // did we end with an operator? bad.
343  return $this->trigger(10, "operator '$op' lacks operand", $op);
344  } else {
345  break;
346  }
347  }
348  while (substr($expr, $index, 1) == ' ') { // step the index past whitespace (pretty much turns whitespace
349  $index++; // into implicit multiplication if no operator is there)
350  }
351  }
352  while (!is_null($op = $stack->pop())) { // pop everything off the stack and push onto output
353  if ($op == '(')
354  return $this->trigger(11, "expecting ')'", ")"); // if there are (s on the stack, ()s were unbalanced
355  $output[] = $op;
356  }
357  return $output;
358  }
359 
367  private function pfx($tokens, $vars = array())
368  {
369  if ($tokens == false)
370  return false;
371 
372  $stack = new EvalMathStack();
373 
374  foreach ($tokens as $token) { // nice and easy
375  // if the token is a binary operator, pop two values off the stack, do the operation, and push the result back on
376  $matches = array();
377  if (in_array($token, array('+', '-', '*', '/', '^'))) {
378  if (is_null($op2 = $stack->pop()))
379  return $this->trigger(12, "internal error");
380  if (is_null($op1 = $stack->pop()))
381  return $this->trigger(13, "internal error");
382  switch ($token) {
383  case '+':
384  $stack->push($op1 + $op2);
385  break;
386  case '-':
387  $stack->push($op1 - $op2);
388  break;
389  case '*':
390  $stack->push($op1 * $op2);
391  break;
392  case '/':
393  if ($op2 == 0)
394  return $this->trigger(14, "division by zero");
395  $stack->push($op1 / $op2);
396  break;
397  case '^':
398  $stack->push(pow($op1, $op2));
399  break;
400  }
401  // if the token is a unary operator, pop one value off the stack, do the operation, and push it back on
402  } elseif ($token == "_") {
403  $stack->push(-1 * $stack->pop());
404  // if the token is a function, pop arguments off the stack, hand them to the function, and push the result back on
405  } elseif (preg_match("/^([a-z]\w*)\($/", $token, $matches)) { // it's a function!
406  $fnn = $matches[1];
407  if (in_array($fnn, $this->fb)) { // built-in function:
408  if (is_null($op1 = $stack->pop()))
409  return $this->trigger(15, "internal error");
410  $fnn = preg_replace("/^arc/", "a", $fnn); // for the 'arc' trig synonyms
411  if ($fnn == 'ln')
412  $fnn = 'log';
413  eval('$stack->push('.$fnn.'($op1));'); // perfectly safe eval()
414  } elseif (array_key_exists($fnn, $this->f)) { // user function
415  // get args
416  $args = array();
417  for ($i = count($this->f[$fnn]['args']) - 1; $i >= 0; $i--) {
418  if (is_null($args[$this->f[$fnn]['args'][$i]] = $stack->pop()))
419  return $this->trigger(16, "internal error");
420  }
421  $stack->push($this->pfx($this->f[$fnn]['func'], $args)); // yay... recursion!!!!
422  }
423  // if the token is a number or variable, push it on the stack
424  } else {
425  if (is_numeric($token)) {
426  $stack->push($token);
427  } elseif (array_key_exists($token, $this->v)) {
428  $stack->push($this->v[$token]);
429  } elseif (array_key_exists($token, $vars)) {
430  $stack->push($vars[$token]);
431  } else {
432  return $this->trigger(17, "undefined variable '$token'", $token);
433  }
434  }
435  }
436  // when we're out of tokens, the stack should have a single element, the final result
437  if ($stack->count != 1)
438  return $this->trigger(18, "internal error");
439  return $stack->pop();
440  }
441 
450  public function trigger($code, $msg, $info = null)
451  {
452  $this->last_error = $msg;
453  $this->last_error_code = array($code, $info);
454  if (!$this->suppress_errors)
455  trigger_error($msg, E_USER_WARNING);
456  return false;
457  }
458 }
459 
464 {
465 
466  public $stack = array();
467 
468  public $count = 0;
469 
476  public function push($val)
477  {
478  $this->stack[$this->count] = $val;
479  $this->count++;
480  }
481 
487  public function pop()
488  {
489  if ($this->count > 0) {
490  $this->count--;
491  return $this->stack[$this->count];
492  }
493  return null;
494  }
495 
502  public function last($n = 1)
503  {
504  if (isset($this->stack[$this->count - $n])) {
505  return $this->stack[$this->count - $n];
506  }
507  return;
508  }
509 }
evaluate($expr)
Evaluate.
funcs()
vars
trigger($code, $msg, $info=null)
trigger an error, but nicely, if need be
last($n=1)
last
push($val)
push
nfx($expr)
Convert infix to postfix notation.
__construct()
Constructor.
Class for internal use.
pfx($tokens, $vars=array())
evaluate postfix notation
Class EvalMath.
e($expr)
Evaluate.