class-wc-eval-math.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. <?php
  2. if ( ! defined( 'ABSPATH' ) ) {
  3. exit;
  4. }
  5. if ( ! class_exists( 'WC_Eval_Math', false ) ) {
  6. /**
  7. * Class WC_Eval_Math. Supports basic math only (removed eval function).
  8. *
  9. * Based on EvalMath by Miles Kaufman Copyright (C) 2005 Miles Kaufmann http://www.twmagic.com/.
  10. */
  11. class WC_Eval_Math {
  12. /**
  13. * Last error.
  14. *
  15. * @var string
  16. */
  17. public static $last_error = null;
  18. /**
  19. * Variables (and constants).
  20. *
  21. * @var array
  22. */
  23. public static $v = array( 'e' => 2.71, 'pi' => 3.14 );
  24. /**
  25. * User-defined functions.
  26. *
  27. * @var array
  28. */
  29. public static $f = array();
  30. /**
  31. * Constants.
  32. *
  33. * @var array
  34. */
  35. public static $vb = array( 'e', 'pi' );
  36. /**
  37. * Built-in functions.
  38. *
  39. * @var array
  40. */
  41. public static $fb = array();
  42. /**
  43. * Evaluate maths string.
  44. *
  45. * @param string $expr
  46. * @return mixed
  47. */
  48. public static function evaluate( $expr ) {
  49. self::$last_error = null;
  50. $expr = trim( $expr );
  51. if ( substr( $expr, -1, 1 ) == ';' ) {
  52. $expr = substr( $expr, 0, strlen( $expr ) -1 ); // strip semicolons at the end
  53. }
  54. // ===============
  55. // is it a variable assignment?
  56. if ( preg_match( '/^\s*([a-z]\w*)\s*=\s*(.+)$/', $expr, $matches ) ) {
  57. if ( in_array( $matches[1], self::$vb ) ) { // make sure we're not assigning to a constant
  58. return self::trigger( "cannot assign to constant '$matches[1]'" );
  59. }
  60. if ( ( $tmp = self::pfx( self::nfx( $matches[2] ) ) ) === false ) {
  61. return false; // get the result and make sure it's good
  62. }
  63. self::$v[ $matches[1] ] = $tmp; // if so, stick it in the variable array
  64. return self::$v[ $matches[1] ]; // and return the resulting value
  65. // ===============
  66. // is it a function assignment?
  67. } elseif ( preg_match( '/^\s*([a-z]\w*)\s*\(\s*([a-z]\w*(?:\s*,\s*[a-z]\w*)*)\s*\)\s*=\s*(.+)$/', $expr, $matches ) ) {
  68. $fnn = $matches[1]; // get the function name
  69. if ( in_array( $matches[1], self::$fb ) ) { // make sure it isn't built in
  70. return self::trigger( "cannot redefine built-in function '$matches[1]()'" );
  71. }
  72. $args = explode( ",", preg_replace( "/\s+/", "", $matches[2] ) ); // get the arguments
  73. if ( ( $stack = self::nfx( $matches[3] ) ) === false ) {
  74. return false; // see if it can be converted to postfix
  75. }
  76. $stack_size = count( $stack );
  77. for ( $i = 0; $i < $stack_size; $i++ ) { // freeze the state of the non-argument variables
  78. $token = $stack[ $i ];
  79. if ( preg_match( '/^[a-z]\w*$/', $token ) and ! in_array( $token, $args ) ) {
  80. if ( array_key_exists( $token, self::$v ) ) {
  81. $stack[ $i ] = self::$v[ $token ];
  82. } else {
  83. return self::trigger( "undefined variable '$token' in function definition" );
  84. }
  85. }
  86. }
  87. self::$f[ $fnn ] = array( 'args' => $args, 'func' => $stack );
  88. return true;
  89. // ===============
  90. } else {
  91. return self::pfx( self::nfx( $expr ) ); // straight up evaluation, woo
  92. }
  93. }
  94. /**
  95. * Convert infix to postfix notation.
  96. *
  97. * @param string $expr
  98. *
  99. * @return array|string
  100. */
  101. private static function nfx( $expr ) {
  102. $index = 0;
  103. $stack = new WC_Eval_Math_Stack;
  104. $output = array(); // postfix form of expression, to be passed to pfx()
  105. $expr = trim( $expr );
  106. $ops = array( '+', '-', '*', '/', '^', '_' );
  107. $ops_r = array( '+' => 0, '-' => 0, '*' => 0, '/' => 0, '^' => 1 ); // right-associative operator?
  108. $ops_p = array( '+' => 0, '-' => 0, '*' => 1, '/' => 1, '_' => 1, '^' => 2 ); // operator precedence
  109. $expecting_op = false; // we use this in syntax-checking the expression
  110. // and determining when a - is a negation
  111. if ( preg_match( "/[^\w\s+*^\/()\.,-]/", $expr, $matches ) ) { // make sure the characters are all good
  112. return self::trigger( "illegal character '{$matches[0]}'" );
  113. }
  114. while ( 1 ) { // 1 Infinite Loop ;)
  115. $op = substr( $expr, $index, 1 ); // get the first character at the current index
  116. // find out if we're currently at the beginning of a number/variable/function/parenthesis/operand
  117. $ex = preg_match( '/^([A-Za-z]\w*\(?|\d+(?:\.\d*)?|\.\d+|\()/', substr( $expr, $index ), $match );
  118. // ===============
  119. if ( '-' === $op and ! $expecting_op ) { // is it a negation instead of a minus?
  120. $stack->push( '_' ); // put a negation on the stack
  121. $index++;
  122. } elseif ( '_' === $op ) { // we have to explicitly deny this, because it's legal on the stack
  123. return self::trigger( "illegal character '_'" ); // but not in the input expression
  124. // ===============
  125. } elseif ( ( in_array( $op, $ops ) or $ex ) and $expecting_op ) { // are we putting an operator on the stack?
  126. if ( $ex ) { // are we expecting an operator but have a number/variable/function/opening parenthesis?
  127. $op = '*';
  128. $index--; // it's an implicit multiplication
  129. }
  130. // heart of the algorithm:
  131. 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 ] ) ) {
  132. $output[] = $stack->pop(); // pop stuff off the stack into the output
  133. }
  134. // many thanks: https://en.wikipedia.org/wiki/Reverse_Polish_notation#The_algorithm_in_detail
  135. $stack->push( $op ); // finally put OUR operator onto the stack
  136. $index++;
  137. $expecting_op = false;
  138. // ===============
  139. } elseif ( ')' === $op && $expecting_op ) { // ready to close a parenthesis?
  140. while ( ( $o2 = $stack->pop() ) != '(' ) { // pop off the stack back to the last (
  141. if ( is_null( $o2 ) ) {
  142. return self::trigger( "unexpected ')'" );
  143. } else {
  144. $output[] = $o2;
  145. }
  146. }
  147. if ( preg_match( "/^([A-Za-z]\w*)\($/", $stack->last( 2 ), $matches ) ) { // did we just close a function?
  148. $fnn = $matches[1]; // get the function name
  149. $arg_count = $stack->pop(); // see how many arguments there were (cleverly stored on the stack, thank you)
  150. $output[] = $stack->pop(); // pop the function and push onto the output
  151. if ( in_array( $fnn, self::$fb ) ) { // check the argument count
  152. if ( $arg_count > 1 ) {
  153. return self::trigger( "too many arguments ($arg_count given, 1 expected)" );
  154. }
  155. } elseif ( array_key_exists( $fnn, self::$f ) ) {
  156. if ( count( self::$f[ $fnn ]['args'] ) != $arg_count ) {
  157. return self::trigger( "wrong number of arguments ($arg_count given, " . count( self::$f[ $fnn ]['args'] ) . " expected)" );
  158. }
  159. } else { // did we somehow push a non-function on the stack? this should never happen
  160. return self::trigger( "internal error" );
  161. }
  162. }
  163. $index++;
  164. // ===============
  165. } elseif ( ',' === $op and $expecting_op ) { // did we just finish a function argument?
  166. while ( ( $o2 = $stack->pop() ) != '(' ) {
  167. if ( is_null( $o2 ) ) {
  168. return self::trigger( "unexpected ','" ); // oops, never had a (
  169. } else {
  170. $output[] = $o2; // pop the argument expression stuff and push onto the output
  171. }
  172. }
  173. // make sure there was a function
  174. if ( ! preg_match( "/^([A-Za-z]\w*)\($/", $stack->last( 2 ), $matches ) ) {
  175. return self::trigger( "unexpected ','" );
  176. }
  177. $stack->push( $stack->pop() + 1 ); // increment the argument count
  178. $stack->push( '(' ); // put the ( back on, we'll need to pop back to it again
  179. $index++;
  180. $expecting_op = false;
  181. // ===============
  182. } elseif ( '(' === $op and ! $expecting_op ) {
  183. $stack->push( '(' ); // that was easy
  184. $index++;
  185. // ===============
  186. } elseif ( $ex and ! $expecting_op ) { // do we now have a function/variable/number?
  187. $expecting_op = true;
  188. $val = $match[1];
  189. if ( preg_match( "/^([A-Za-z]\w*)\($/", $val, $matches ) ) { // may be func, or variable w/ implicit multiplication against parentheses...
  190. if ( in_array( $matches[1], self::$fb ) or array_key_exists( $matches[1], self::$f ) ) { // it's a func
  191. $stack->push( $val );
  192. $stack->push( 1 );
  193. $stack->push( '(' );
  194. $expecting_op = false;
  195. } else { // it's a var w/ implicit multiplication
  196. $val = $matches[1];
  197. $output[] = $val;
  198. }
  199. } else { // it's a plain old var or num
  200. $output[] = $val;
  201. }
  202. $index += strlen( $val );
  203. // ===============
  204. } elseif ( ')' === $op ) { // miscellaneous error checking
  205. return self::trigger( "unexpected ')'" );
  206. } elseif ( in_array( $op, $ops ) and ! $expecting_op ) {
  207. return self::trigger( "unexpected operator '$op'" );
  208. } else { // I don't even want to know what you did to get here
  209. return self::trigger( "an unexpected error occurred" );
  210. }
  211. if ( strlen( $expr ) == $index ) {
  212. if ( in_array( $op, $ops ) ) { // did we end with an operator? bad.
  213. return self::trigger( "operator '$op' lacks operand" );
  214. } else {
  215. break;
  216. }
  217. }
  218. while ( substr( $expr, $index, 1 ) == ' ' ) { // step the index past whitespace (pretty much turns whitespace
  219. $index++; // into implicit multiplication if no operator is there)
  220. }
  221. }
  222. while ( ! is_null( $op = $stack->pop() ) ) { // pop everything off the stack and push onto output
  223. if ( '(' === $op ) {
  224. return self::trigger( "expecting ')'" ); // if there are (s on the stack, ()s were unbalanced
  225. }
  226. $output[] = $op;
  227. }
  228. return $output;
  229. }
  230. /**
  231. * Evaluate postfix notation.
  232. *
  233. * @param mixed $tokens
  234. * @param array $vars
  235. *
  236. * @return mixed
  237. */
  238. private static function pfx( $tokens, $vars = array() ) {
  239. if ( false == $tokens ) {
  240. return false;
  241. }
  242. $stack = new WC_Eval_Math_Stack;
  243. foreach ( $tokens as $token ) { // nice and easy
  244. // if the token is a binary operator, pop two values off the stack, do the operation, and push the result back on
  245. if ( in_array( $token, array( '+', '-', '*', '/', '^' ) ) ) {
  246. if ( is_null( $op2 = $stack->pop() ) ) {
  247. return self::trigger( "internal error" );
  248. }
  249. if ( is_null( $op1 = $stack->pop() ) ) {
  250. return self::trigger( "internal error" );
  251. }
  252. switch ( $token ) {
  253. case '+':
  254. $stack->push( $op1 + $op2 );
  255. break;
  256. case '-':
  257. $stack->push( $op1 - $op2 );
  258. break;
  259. case '*':
  260. $stack->push( $op1 * $op2 );
  261. break;
  262. case '/':
  263. if ( 0 == $op2 ) {
  264. return self::trigger( 'division by zero' );
  265. }
  266. $stack->push( $op1 / $op2 );
  267. break;
  268. case '^':
  269. $stack->push( pow( $op1, $op2 ) );
  270. break;
  271. }
  272. // if the token is a unary operator, pop one value off the stack, do the operation, and push it back on
  273. } elseif ( '_' === $token ) {
  274. $stack->push( -1 * $stack->pop() );
  275. // if the token is a function, pop arguments off the stack, hand them to the function, and push the result back on
  276. } elseif ( ! preg_match( "/^([a-z]\w*)\($/", $token, $matches ) ) {
  277. if ( is_numeric( $token ) ) {
  278. $stack->push( $token );
  279. } elseif ( array_key_exists( $token, self::$v ) ) {
  280. $stack->push( self::$v[ $token ] );
  281. } elseif ( array_key_exists( $token, $vars ) ) {
  282. $stack->push( $vars[ $token ] );
  283. } else {
  284. return self::trigger( "undefined variable '$token'" );
  285. }
  286. }
  287. }
  288. // when we're out of tokens, the stack should have a single element, the final result
  289. if ( 1 != $stack->count ) {
  290. return self::trigger( "internal error" );
  291. }
  292. return $stack->pop();
  293. }
  294. /**
  295. * Trigger an error, but nicely, if need be.
  296. *
  297. * @param string $msg
  298. *
  299. * @return bool
  300. */
  301. private static function trigger( $msg ) {
  302. self::$last_error = $msg;
  303. if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
  304. echo "\nError found in:";
  305. self::debugPrintCallingFunction();
  306. trigger_error( $msg, E_USER_WARNING );
  307. }
  308. return false;
  309. }
  310. /**
  311. * Prints the file name, function name, and
  312. * line number which called your function
  313. * (not this function, then one that called
  314. * it to begin with)
  315. */
  316. private static function debugPrintCallingFunction() {
  317. $file = 'n/a';
  318. $func = 'n/a';
  319. $line = 'n/a';
  320. $debugTrace = debug_backtrace();
  321. if ( isset( $debugTrace[1] ) ) {
  322. $file = $debugTrace[1]['file'] ? $debugTrace[1]['file'] : 'n/a';
  323. $line = $debugTrace[1]['line'] ? $debugTrace[1]['line'] : 'n/a';
  324. }
  325. if ( isset( $debugTrace[2] ) ) {
  326. $func = $debugTrace[2]['function'] ? $debugTrace[2]['function'] : 'n/a';
  327. }
  328. echo "\n$file, $func, $line\n";
  329. }
  330. }
  331. /**
  332. * Class WC_Eval_Math_Stack.
  333. */
  334. class WC_Eval_Math_Stack {
  335. /**
  336. * Stack array.
  337. *
  338. * @var array
  339. */
  340. public $stack = array();
  341. /**
  342. * Stack counter.
  343. *
  344. * @var integer
  345. */
  346. public $count = 0;
  347. /**
  348. * Push value into stack.
  349. *
  350. * @param mixed $val
  351. */
  352. public function push( $val ) {
  353. $this->stack[ $this->count ] = $val;
  354. $this->count++;
  355. }
  356. /**
  357. * Pop value from stack.
  358. *
  359. * @return mixed
  360. */
  361. public function pop() {
  362. if ( $this->count > 0 ) {
  363. $this->count--;
  364. return $this->stack[ $this->count ];
  365. }
  366. return null;
  367. }
  368. /**
  369. * Get last value from stack.
  370. *
  371. * @param int $n
  372. *
  373. * @return mixed
  374. */
  375. public function last( $n=1 ) {
  376. $key = $this->count - $n;
  377. return array_key_exists( $key, $this->stack ) ? $this->stack[ $key ] : null;
  378. }
  379. }
  380. }