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

/includes/shipping/legacy-flat-rate/includes/class-wc-eval-math.php

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