evalmath.class.php 17 KB

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