evalmath.class.php 17 KB

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