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