dolibarr 19.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
98{
99 public $suppress_errors = false;
100
101 public $last_error = null;
102
103 public $last_error_code = null;
104
105 public $v = array('e' => 2.71, 'pi' => 3.14159);
106
107 // variables (and constants)
108 public $f = array();
109
110 // user-defined functions
111 public $vb = array('e', 'pi');
112
113 // constants
114 public $fb = array( // built-in functions
115 'sin', 'sinh', 'arcsin', 'asin', 'arcsinh', 'asinh', 'cos', 'cosh', 'arccos', 'acos', 'arccosh', 'acosh', 'tan', 'tanh', 'arctan', 'atan', 'arctanh', 'atanh', 'sqrt', 'abs', 'ln', 'log', 'intval', 'ceil',
116 );
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
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 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
525 return '';
526 }
527}
Class EvalMath.
vars()
Function vars.
trigger($code, $msg, $info=null)
trigger an error, but nicely, if need be
evaluate($expr)
Evaluate.
funcs()
Function funcs.
e($expr)
Evaluate.
__construct()
Constructor.
nfx($expr)
Convert infix to postfix notation.
pfx($tokens, $vars=array())
Evaluate postfix notation.
Class for internal use.