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