PageRenderTime 35ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-content/plugins/woocommerce/includes/shipping/flat-rate/includes/class-wc-eval-math.php

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