dolibarr  16.0.5
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  if (empty($expr)) {
148  return false;
149  }
150 
151  $this->last_error = null;
152  $this->last_error_code = null;
153  $expr = trim($expr);
154  if (substr($expr, - 1, 1) == ';') {
155  $expr = substr($expr, 0, strlen($expr) - 1); // strip semicolons at the end
156  }
157  // ===============
158  // is it a variable assignment?
159  $matches = array();
160  if (preg_match('/^\s*([a-z]\w*)\s*=\s*(.+)$/', $expr, $matches)) {
161  if (in_array($matches[1], $this->vb)) { // make sure we're not assigning to a constant
162  return $this->trigger(1, "cannot assign to constant '$matches[1]'", $matches[1]);
163  }
164  if (($tmp = $this->pfx($this->nfx($matches[2]))) === false) {
165  return false; // get the result and make sure it's good
166  }
167  $this->v[$matches[1]] = $tmp; // if so, stick it in the variable array
168  return $this->v[$matches[1]]; // and return the resulting value
169  // ===============
170  // is it a function assignment?
171  } elseif (preg_match('/^\s*([a-z]\w*)\s*\(\s*([a-z]\w*(?:\s*,\s*[a-z]\w*)*)\s*\)\s*=\s*(.+)$/', $expr, $matches)) {
172  $fnn = $matches[1]; // get the function name
173  if (in_array($matches[1], $this->fb)) { // make sure it isn't built in
174  return $this->trigger(2, "cannot redefine built-in function '$matches[1]()'", $matches[1]);
175  }
176  $args = explode(",", preg_replace("/\s+/", "", $matches[2])); // get the arguments
177  if (($stack = $this->nfx($matches[3])) === false) {
178  return false; // see if it can be converted to postfix
179  }
180  $nbstack = count($stack);
181  for ($i = 0; $i < $nbstack; $i++) { // freeze the state of the non-argument variables
182  $token = $stack[$i];
183  if (preg_match('/^[a-z]\w*$/', $token) and !in_array($token, $args)) {
184  if (array_key_exists($token, $this->v)) {
185  $stack[$i] = $this->v[$token];
186  } else {
187  return $this->trigger(3, "undefined variable '$token' in function definition", $token);
188  }
189  }
190  }
191  $this->f[$fnn] = array('args' => $args, 'func' => $stack);
192  return true;
193  // ===============
194  } else {
195  return $this->pfx($this->nfx($expr)); // straight up evaluation, woo
196  }
197  }
198 
204  public function vars()
205  {
206  $output = $this->v;
207  unset($output['pi']);
208  unset($output['e']);
209  return $output;
210  }
211 
217  private function funcs()
218  {
219  $output = array();
220  foreach ($this->f as $fnn => $dat) {
221  $output[] = $fnn.'('.implode(',', $dat['args']).')';
222  }
223  return $output;
224  }
225 
226  // ===================== HERE BE INTERNAL METHODS ====================\\
227 
234  private function nfx($expr)
235  {
236  $index = 0;
237  $stack = new EvalMathStack();
238  $output = array(); // postfix form of expression, to be passed to pfx()
239  $expr = trim(strtolower($expr));
240 
241  $ops = array('+', '-', '*', '/', '^', '_');
242  $ops_r = array('+' => 0, '-' => 0, '*' => 0, '/' => 0, '^' => 1); // right-associative operator?
243  $ops_p = array('+' => 0, '-' => 0, '*' => 1, '/' => 1, '_' => 1, '^' => 2); // operator precedence
244 
245  $expecting_op = false; // we use this in syntax-checking the expression
246  // and determining when a - is a negation
247 
248  $matches = array();
249  if (preg_match("/[^\w\s+*^\/()\.,-]/", $expr, $matches)) { // make sure the characters are all good
250  return $this->trigger(4, "illegal character '{$matches[0]}'", $matches[0]);
251  }
252 
253  while (1) { // 1 Infinite Loop ;)
254  $op = substr($expr, $index, 1); // get the first character at the current index
255  // find out if we're currently at the beginning of a number/variable/function/parenthesis/operand
256  $match = array();
257  $ex = preg_match('/^([a-z]\w*\(?|\d+(?:\.\d*)?|\.\d+|\()/', substr($expr, $index), $match);
258  // ===============
259  if ($op == '-' and !$expecting_op) { // is it a negation instead of a minus?
260  $stack->push('_'); // put a negation on the stack
261  $index++;
262  } elseif ($op == '_') { // we have to explicitly deny this, because it's legal on the stack
263  return $this->trigger(4, "illegal character '_'", "_"); // but not in the input expression
264  // ===============
265  } elseif ((in_array($op, $ops) or $ex) and $expecting_op) { // are we putting an operator on the stack?
266  if ($ex) { // are we expecting an operator but have a number/variable/function/opening parethesis?
267  $op = '*';
268  $index--; // it's an implicit multiplication
269  }
270  // heart of the algorithm:
271  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])) {
272  $output[] = $stack->pop(); // pop stuff off the stack into the output
273  }
274  // many thanks: http://en.wikipedia.org/wiki/Reverse_Polish_notation#The_algorithm_in_detail
275  $stack->push($op); // finally put OUR operator onto the stack
276  $index++;
277  $expecting_op = false;
278  // ===============
279  } elseif ($op == ')' and $expecting_op) { // ready to close a parenthesis?
280  while (($o2 = $stack->pop()) != '(') { // pop off the stack back to the last (
281  if (is_null($o2)) {
282  return $this->trigger(5, "unexpected ')'", ")");
283  } else {
284  $output[] = $o2;
285  }
286  }
287  if (preg_match("/^([a-z]\w*)\($/", $stack->last(2), $matches)) { // did we just close a function?
288  $fnn = $matches[1]; // get the function name
289  $arg_count = $stack->pop(); // see how many arguments there were (cleverly stored on the stack, thank you)
290  $output[] = $stack->pop(); // pop the function and push onto the output
291  if (in_array($fnn, $this->fb)) { // check the argument count
292  if ($arg_count > 1) {
293  return $this->trigger(6, "wrong number of arguments ($arg_count given, 1 expected)", array($arg_count, 1));
294  }
295  } elseif (array_key_exists($fnn, $this->f)) {
296  if ($arg_count != count($this->f[$fnn]['args'])) {
297  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'])));
298  }
299  } else { // did we somehow push a non-function on the stack? this should never happen
300  return $this->trigger(7, "internal error");
301  }
302  }
303  $index++;
304  // ===============
305  } elseif ($op == ',' and $expecting_op) { // did we just finish a function argument?
306  while (($o2 = $stack->pop()) != '(') {
307  if (is_null($o2)) {
308  return $this->trigger(5, "unexpected ','", ","); // oops, never had a (
309  } else {
310  $output[] = $o2; // pop the argument expression stuff and push onto the output
311  }
312  }
313  // make sure there was a function
314  if (!preg_match("/^([a-z]\w*)\($/", $stack->last(2), $matches)) {
315  return $this->trigger(5, "unexpected ','", ",");
316  }
317  $stack->push($stack->pop() + 1); // increment the argument count
318  $stack->push('('); // put the ( back on, we'll need to pop back to it again
319  $index++;
320  $expecting_op = false;
321  // ===============
322  } elseif ($op == '(' and !$expecting_op) {
323  $stack->push('('); // that was easy
324  $index++;
325  $allow_neg = true;
326  // ===============
327  } elseif ($ex and !$expecting_op) { // do we now have a function/variable/number?
328  $expecting_op = true;
329  $val = $match[1];
330  if (preg_match("/^([a-z]\w*)\($/", $val, $matches)) { // may be func, or variable w/ implicit multiplication against parentheses...
331  if (in_array($matches[1], $this->fb) or array_key_exists($matches[1], $this->f)) { // it's a func
332  $stack->push($val);
333  $stack->push(1);
334  $stack->push('(');
335  $expecting_op = false;
336  } else { // it's a var w/ implicit multiplication
337  $val = $matches[1];
338  $output[] = $val;
339  }
340  } else { // it's a plain old var or num
341  $output[] = $val;
342  }
343  $index += strlen($val);
344  // ===============
345  } elseif ($op == ')') { // miscellaneous error checking
346  return $this->trigger(5, "unexpected ')'", ")");
347  } elseif (in_array($op, $ops) and !$expecting_op) {
348  return $this->trigger(8, "unexpected operator '$op'", $op);
349  } else { // I don't even want to know what you did to get here
350  return $this->trigger(9, "an unexpected error occured");
351  }
352  if ($index == strlen($expr)) {
353  if (in_array($op, $ops)) { // did we end with an operator? bad.
354  return $this->trigger(10, "operator '$op' lacks operand", $op);
355  } else {
356  break;
357  }
358  }
359  while (substr($expr, $index, 1) == ' ') { // step the index past whitespace (pretty much turns whitespace
360  $index++; // into implicit multiplication if no operator is there)
361  }
362  }
363  while (!is_null($op = $stack->pop())) { // pop everything off the stack and push onto output
364  if ($op == '(') {
365  return $this->trigger(11, "expecting ')'", ")"); // if there are (s on the stack, ()s were unbalanced
366  }
367  $output[] = $op;
368  }
369  return $output;
370  }
371 
379  private function pfx($tokens, $vars = array())
380  {
381  $stack = new EvalMathStack();
382 
383  foreach ($tokens as $token) { // nice and easy
384  // if the token is a binary operator, pop two values off the stack, do the operation, and push the result back on
385  $matches = array();
386  if (in_array($token, array('+', '-', '*', '/', '^'))) {
387  if (is_null($op2 = $stack->pop())) {
388  return $this->trigger(12, "internal error");
389  }
390  if (is_null($op1 = $stack->pop())) {
391  return $this->trigger(13, "internal error");
392  }
393  switch ($token) {
394  case '+':
395  $stack->push($op1 + $op2);
396  break;
397  case '-':
398  $stack->push($op1 - $op2);
399  break;
400  case '*':
401  $stack->push($op1 * $op2);
402  break;
403  case '/':
404  if ($op2 == 0) {
405  return $this->trigger(14, "division by zero");
406  }
407  $stack->push($op1 / $op2);
408  break;
409  case '^':
410  $stack->push(pow($op1, $op2));
411  break;
412  }
413  // if the token is a unary operator, pop one value off the stack, do the operation, and push it back on
414  } elseif ($token == "_") {
415  $stack->push(-1 * $stack->pop());
416  // if the token is a function, pop arguments off the stack, hand them to the function, and push the result back on
417  } elseif (preg_match("/^([a-z]\w*)\($/", $token, $matches)) { // it's a function!
418  $fnn = $matches[1];
419  if (in_array($fnn, $this->fb)) { // built-in function:
420  if (is_null($op1 = $stack->pop())) {
421  return $this->trigger(15, "internal error");
422  }
423  $fnn = preg_replace("/^arc/", "a", $fnn); // for the 'arc' trig synonyms
424  if ($fnn == 'ln') {
425  $fnn = 'log';
426  }
427  eval('$stack->push('.$fnn.'($op1));'); // perfectly safe eval()
428  } elseif (array_key_exists($fnn, $this->f)) { // user function
429  // get args
430  $args = array();
431  for ($i = count($this->f[$fnn]['args']) - 1; $i >= 0; $i--) {
432  if (is_null($args[$this->f[$fnn]['args'][$i]] = $stack->pop())) {
433  return $this->trigger(16, "internal error");
434  }
435  }
436  $stack->push($this->pfx($this->f[$fnn]['func'], $args)); // yay... recursion!!!!
437  }
438  // if the token is a number or variable, push it on the stack
439  } else {
440  if (is_numeric($token)) {
441  $stack->push($token);
442  } elseif (array_key_exists($token, $this->v)) {
443  $stack->push($this->v[$token]);
444  } elseif (array_key_exists($token, $vars)) {
445  $stack->push($vars[$token]);
446  } else {
447  return $this->trigger(17, "undefined variable '$token'", $token);
448  }
449  }
450  }
451  // when we're out of tokens, the stack should have a single element, the final result
452  if ($stack->count != 1) {
453  return $this->trigger(18, "internal error");
454  }
455  return $stack->pop();
456  }
457 
466  public function trigger($code, $msg, $info = null)
467  {
468  $this->last_error = $msg;
469  $this->last_error_code = array($code, $info);
470  if (!$this->suppress_errors) {
471  trigger_error($msg, E_USER_WARNING);
472  }
473  return false;
474  }
475 }
476 
481 {
482 
483  public $stack = array();
484 
485  public $count = 0;
486 
493  public function push($val)
494  {
495  $this->stack[$this->count] = $val;
496  $this->count++;
497  }
498 
504  public function pop()
505  {
506  if ($this->count > 0) {
507  $this->count--;
508  return $this->stack[$this->count];
509  }
510  return null;
511  }
512 
519  public function last($n = 1)
520  {
521  if (isset($this->stack[$this->count - $n])) {
522  return $this->stack[$this->count - $n];
523  }
524  return;
525  }
526 }
EvalMathStack\pop
pop()
pop
Definition: evalmath.class.php:504
EvalMath\nfx
nfx($expr)
Convert infix to postfix notation.
Definition: evalmath.class.php:234
EvalMath\funcs
funcs()
vars
Definition: evalmath.class.php:217
EvalMath\vars
vars()
vars
Definition: evalmath.class.php:204
EvalMath\e
e($expr)
Evaluate.
Definition: evalmath.class.php:134
EvalMath
Class EvalMath.
Definition: evalmath.class.php:97
EvalMathStack\last
last($n=1)
last
Definition: evalmath.class.php:519
EvalMath\evaluate
evaluate($expr)
Evaluate.
Definition: evalmath.class.php:145
EvalMathStack\push
push($val)
push
Definition: evalmath.class.php:493
EvalMath\pfx
pfx($tokens, $vars=array())
Evaluate postfix notation.
Definition: evalmath.class.php:379
EvalMath\__construct
__construct()
Constructor.
Definition: evalmath.class.php:121
EvalMathStack
Class for internal use.
Definition: evalmath.class.php:480
EvalMath\trigger
trigger($code, $msg, $info=null)
trigger an error, but nicely, if need be
Definition: evalmath.class.php:466