]> git.mjollnir.org Git - moodle.git/commitdiff
MDL-9643 evalmath library import - tweaks and wrapper class ahead
authorskodak <skodak>
Thu, 24 May 2007 19:12:18 +0000 (19:12 +0000)
committerskodak <skodak>
Thu, 24 May 2007 19:12:18 +0000 (19:12 +0000)
lib/evalmath/evalmath.class.php [new file with mode: 0644]
lib/evalmath/example.html [new file with mode: 0644]
lib/evalmath/example.php [new file with mode: 0644]

diff --git a/lib/evalmath/evalmath.class.php b/lib/evalmath/evalmath.class.php
new file mode 100644 (file)
index 0000000..8b3f6e0
--- /dev/null
@@ -0,0 +1,388 @@
+<?\r
+\r
+/*\r
+================================================================================\r
+\r
+EvalMath - PHP Class to safely evaluate math expressions\r
+Copyright (C) 2005 Miles Kaufmann <http://www.twmagic.com/>\r
+\r
+================================================================================\r
+\r
+NAME\r
+    EvalMath - safely evaluate math expressions\r
+    \r
+SYNOPSIS\r
+    <?\r
+      include('evalmath.class.php');\r
+      $m = new EvalMath;\r
+      // basic evaluation:\r
+      $result = $m->evaluate('2+2');\r
+      // supports: order of operation; parentheses; negation; built-in functions\r
+      $result = $m->evaluate('-8(5/2)^2*(1-sqrt(4))-8');\r
+      // create your own variables\r
+      $m->evaluate('a = e^(ln(pi))');\r
+      // or functions\r
+      $m->evaluate('f(x,y) = x^2 + y^2 - 2x*y + 1');\r
+      // and then use them\r
+      $result = $m->evaluate('3*f(42,a)');\r
+    ?>\r
+      \r
+DESCRIPTION\r
+    Use the EvalMath class when you want to evaluate mathematical expressions \r
+    from untrusted sources.  You can define your own variables and functions,\r
+    which are stored in the object.  Try it, it's fun!\r
+\r
+METHODS\r
+    $m->evalute($expr)\r
+        Evaluates the expression and returns the result.  If an error occurs,\r
+        prints a warning and returns false.  If $expr is a function assignment,\r
+        returns true on success.\r
+    \r
+    $m->e($expr)\r
+        A synonym for $m->evaluate().\r
+    \r
+    $m->vars()\r
+        Returns an associative array of all user-defined variables and values.\r
+        \r
+    $m->funcs()\r
+        Returns an array of all user-defined functions.\r
+\r
+PARAMETERS\r
+    $m->suppress_errors\r
+        Set to true to turn off warnings when evaluating expressions\r
+\r
+    $m->last_error\r
+        If the last evaluation failed, contains a string describing the error.\r
+        (Useful when suppress_errors is on).\r
+\r
+AUTHOR INFORMATION\r
+    Copyright 2005, Miles Kaufmann.\r
+\r
+LICENSE\r
+    Redistribution and use in source and binary forms, with or without\r
+    modification, are permitted provided that the following conditions are\r
+    met:\r
+    \r
+    1   Redistributions of source code must retain the above copyright\r
+        notice, this list of conditions and the following disclaimer.\r
+    2.  Redistributions in binary form must reproduce the above copyright\r
+        notice, this list of conditions and the following disclaimer in the\r
+        documentation and/or other materials provided with the distribution.\r
+    3.  The name of the author may not be used to endorse or promote\r
+        products derived from this software without specific prior written\r
+        permission.\r
+    \r
+    THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\r
+    IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\r
+    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r
+    DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,\r
+    INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\r
+    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\r
+    SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\r
+    HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\r
+    STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\r
+    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r
+    POSSIBILITY OF SUCH DAMAGE.\r
+\r
+*/\r
+\r
+class EvalMath {\r
+\r
+    var $suppress_errors = false;\r
+    var $last_error = null;\r
+    \r
+    var $v = array('e'=>2.71,'pi'=>3.14); // variables (and constants)\r
+    var $f = array(); // user-defined functions\r
+    var $vb = array('e', 'pi'); // constants\r
+    var $fb = array(  // built-in functions\r
+        'sin','sinh','arcsin','asin','arcsinh','asinh',\r
+        'cos','cosh','arccos','acos','arccosh','acosh',\r
+        'tan','tanh','arctan','atan','arctanh','atanh',\r
+        'sqrt','abs','ln','log');\r
+    \r
+    function EvalMath() {\r
+        // make the variables a little more accurate\r
+        $this->v['pi'] = pi();\r
+        $this->v['e'] = exp(1);\r
+    }\r
+    \r
+    function e($expr) {\r
+        return $this->evaluate($expr);\r
+    }\r
+    \r
+    function evaluate($expr) {\r
+        $this->last_error = null;\r
+        $expr = trim($expr);\r
+        if (substr($expr, -1, 1) == ';') $expr = substr($expr, 0, strlen($expr)-1); // strip semicolons at the end\r
+        //===============\r
+        // is it a variable assignment?\r
+        if (preg_match('/^\s*([a-z]\w*)\s*=\s*(.+)$/', $expr, $matches)) {\r
+            if (in_array($matches[1], $this->vb)) { // make sure we're not assigning to a constant\r
+                return $this->trigger("cannot assign to constant '$matches[1]'");\r
+            }\r
+            if (($tmp = $this->pfx($this->nfx($matches[2]))) === false) return false; // get the result and make sure it's good\r
+            $this->v[$matches[1]] = $tmp; // if so, stick it in the variable array\r
+            return $this->v[$matches[1]]; // and return the resulting value\r
+        //===============\r
+        // is it a function assignment?\r
+        } elseif (preg_match('/^\s*([a-z]\w*)\s*\(\s*([a-z]\w*(?:\s*,\s*[a-z]\w*)*)\s*\)\s*=\s*(.+)$/', $expr, $matches)) {\r
+            $fnn = $matches[1]; // get the function name\r
+            if (in_array($matches[1], $this->fb)) { // make sure it isn't built in\r
+                return $this->trigger("cannot redefine built-in function '$matches[1]()'");\r
+            }\r
+            $args = explode(",", preg_replace("/\s+/", "", $matches[2])); // get the arguments\r
+            if (($stack = $this->nfx($matches[3])) === false) return false; // see if it can be converted to postfix\r
+            for ($i = 0; $i<count($stack); $i++) { // freeze the state of the non-argument variables\r
+                $token = $stack[$i];\r
+                if (preg_match('/^[a-z]\w*$/', $token) and !in_array($token, $args)) {\r
+                    if (array_key_exists($token, $this->v)) {\r
+                        $stack[$i] = $this->v[$token];\r
+                    } else {\r
+                        return $this->trigger("undefined variable '$token' in function definition");\r
+                    }\r
+                }\r
+            }\r
+            $this->f[$fnn] = array('args'=>$args, 'func'=>$stack);\r
+            return true;\r
+        //===============\r
+        } else {\r
+            return $this->pfx($this->nfx($expr)); // straight up evaluation, woo\r
+        }\r
+    }\r
+    \r
+    function vars() {\r
+        $output = $this->v;\r
+        unset($output['pi']);\r
+        unset($output['e']);\r
+        return $output;\r
+    }\r
+    \r
+    function funcs() {\r
+        $output = array();\r
+        foreach ($this->f as $fnn=>$dat)\r
+            $output[] = $fnn . '(' . implode(',', $dat['args']) . ')';\r
+        return $output;\r
+    }\r
+\r
+    //===================== HERE BE INTERNAL METHODS ====================\\\r
+\r
+    // Convert infix to postfix notation\r
+    function nfx($expr) {\r
+    \r
+        $index = 0;\r
+        $stack = new EvalMathStack;\r
+        $output = array(); // postfix form of expression, to be passed to pfx()\r
+        $expr = trim(strtolower($expr));\r
+        \r
+        $ops   = array('+', '-', '*', '/', '^', '_');\r
+        $ops_r = array('+'=>0,'-'=>0,'*'=>0,'/'=>0,'^'=>1); // right-associative operator?  \r
+        $ops_p = array('+'=>0,'-'=>0,'*'=>1,'/'=>1,'_'=>1,'^'=>2); // operator precedence\r
+        \r
+        $expecting_op = false; // we use this in syntax-checking the expression\r
+                               // and determining when a - is a negation\r
+    \r
+        if (preg_match("/[^\w\s+*^\/()\.,-]/", $expr, $matches)) { // make sure the characters are all good\r
+            return $this->trigger("illegal character '{$matches[0]}'");\r
+        }\r
+    \r
+        while(1) { // 1 Infinite Loop ;)\r
+            $op = substr($expr, $index, 1); // get the first character at the current index\r
+            // find out if we're currently at the beginning of a number/variable/function/parenthesis/operand\r
+            $ex = preg_match('/^([a-z]\w*\(?|\d+(?:\.\d*)?|\.\d+|\()/', substr($expr, $index), $match);\r
+            //===============\r
+            if ($op == '-' and !$expecting_op) { // is it a negation instead of a minus?\r
+                $stack->push('_'); // put a negation on the stack\r
+                $index++;\r
+            } elseif ($op == '_') { // we have to explicitly deny this, because it's legal on the stack \r
+                return $this->trigger("illegal character '_'"); // but not in the input expression\r
+            //===============\r
+            } elseif ((in_array($op, $ops) or $ex) and $expecting_op) { // are we putting an operator on the stack?\r
+                if ($ex) { // are we expecting an operator but have a number/variable/function/opening parethesis?\r
+                    $op = '*'; $index--; // it's an implicit multiplication\r
+                }\r
+                // heart of the algorithm:\r
+                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])) {\r
+                    $output[] = $stack->pop(); // pop stuff off the stack into the output\r
+                }\r
+                // many thanks: http://en.wikipedia.org/wiki/Reverse_Polish_notation#The_algorithm_in_detail\r
+                $stack->push($op); // finally put OUR operator onto the stack\r
+                $index++;\r
+                $expecting_op = false;\r
+            //===============\r
+            } elseif ($op == ')' and $expecting_op) { // ready to close a parenthesis?\r
+                while (($o2 = $stack->pop()) != '(') { // pop off the stack back to the last (\r
+                    if (is_null($o2)) return $this->trigger("unexpected ')'");\r
+                    else $output[] = $o2;\r
+                }\r
+                if (preg_match("/^([a-z]\w*)\($/", $stack->last(2), $matches)) { // did we just close a function?\r
+                    $fnn = $matches[1]; // get the function name\r
+                    $arg_count = $stack->pop(); // see how many arguments there were (cleverly stored on the stack, thank you)\r
+                    $output[] = $stack->pop(); // pop the function and push onto the output\r
+                    if (in_array($fnn, $this->fb)) { // check the argument count\r
+                        if($arg_count > 1)\r
+                            return $this->trigger("too many arguments ($arg_count given, 1 expected)");\r
+                    } elseif (array_key_exists($fnn, $this->f)) {\r
+                        if ($arg_count != count($this->f[$fnn]['args']))\r
+                            return $this->trigger("wrong number of arguments ($arg_count given, " . count($this->f[$fnn]['args']) . " expected)");\r
+                    } else { // did we somehow push a non-function on the stack? this should never happen\r
+                        return $this->trigger("internal error");\r
+                    }\r
+                }\r
+                $index++;\r
+            //===============\r
+            } elseif ($op == ',' and $expecting_op) { // did we just finish a function argument?\r
+                while (($o2 = $stack->pop()) != '(') { \r
+                    if (is_null($o2)) return $this->trigger("unexpected ','"); // oops, never had a (\r
+                    else $output[] = $o2; // pop the argument expression stuff and push onto the output\r
+                }\r
+                // make sure there was a function\r
+                if (!preg_match("/^([a-z]\w*)\($/", $stack->last(2), $matches))\r
+                    return $this->trigger("unexpected ','");\r
+                $stack->push($stack->pop()+1); // increment the argument count\r
+                $stack->push('('); // put the ( back on, we'll need to pop back to it again\r
+                $index++;\r
+                $expecting_op = false;\r
+            //===============\r
+            } elseif ($op == '(' and !$expecting_op) {\r
+                $stack->push('('); // that was easy\r
+                $index++;\r
+                $allow_neg = true;\r
+            //===============\r
+            } elseif ($ex and !$expecting_op) { // do we now have a function/variable/number?\r
+                $expecting_op = true;\r
+                $val = $match[1];\r
+                if (preg_match("/^([a-z]\w*)\($/", $val, $matches)) { // may be func, or variable w/ implicit multiplication against parentheses...\r
+                    if (in_array($matches[1], $this->fb) or array_key_exists($matches[1], $this->f)) { // it's a func\r
+                        $stack->push($val);\r
+                        $stack->push(1);\r
+                        $stack->push('(');\r
+                        $expecting_op = false;\r
+                    } else { // it's a var w/ implicit multiplication\r
+                        $val = $matches[1];\r
+                        $output[] = $val;\r
+                    }\r
+                } else { // it's a plain old var or num\r
+                    $output[] = $val;\r
+                }\r
+                $index += strlen($val);\r
+            //===============\r
+            } elseif ($op == ')') { // miscellaneous error checking\r
+                return $this->trigger("unexpected ')'");\r
+            } elseif (in_array($op, $ops) and !$expecting_op) {\r
+                return $this->trigger("unexpected operator '$op'");\r
+            } else { // I don't even want to know what you did to get here\r
+                return $this->trigger("an unexpected error occured");\r
+            }\r
+            if ($index == strlen($expr)) {\r
+                if (in_array($op, $ops)) { // did we end with an operator? bad.\r
+                    return $this->trigger("operator '$op' lacks operand");\r
+                } else {\r
+                    break;\r
+                }\r
+            }\r
+            while (substr($expr, $index, 1) == ' ') { // step the index past whitespace (pretty much turns whitespace \r
+                $index++;                             // into implicit multiplication if no operator is there)\r
+            }\r
+        \r
+        } \r
+        while (!is_null($op = $stack->pop())) { // pop everything off the stack and push onto output\r
+            if ($op == '(') return $this->trigger("expecting ')'"); // if there are (s on the stack, ()s were unbalanced\r
+            $output[] = $op;\r
+        }\r
+        return $output;\r
+    }\r
+\r
+    // evaluate postfix notation\r
+    function pfx($tokens, $vars = array()) {\r
+        \r
+        if ($tokens == false) return false;\r
+    \r
+        $stack = new EvalMathStack;\r
+        \r
+        foreach ($tokens as $token) { // nice and easy\r
+            // if the token is a binary operator, pop two values off the stack, do the operation, and push the result back on\r
+            if (in_array($token, array('+', '-', '*', '/', '^'))) {\r
+                if (is_null($op2 = $stack->pop())) return $this->trigger("internal error");\r
+                if (is_null($op1 = $stack->pop())) return $this->trigger("internal error");\r
+                switch ($token) {\r
+                    case '+':\r
+                        $stack->push($op1+$op2); break;\r
+                    case '-':\r
+                        $stack->push($op1-$op2); break;\r
+                    case '*':\r
+                        $stack->push($op1*$op2); break;\r
+                    case '/':\r
+                        if ($op2 == 0) return $this->trigger("division by zero");\r
+                        $stack->push($op1/$op2); break;\r
+                    case '^':\r
+                        $stack->push(pow($op1, $op2)); break;\r
+                }\r
+            // if the token is a unary operator, pop one value off the stack, do the operation, and push it back on\r
+            } elseif ($token == "_") {\r
+                $stack->push(-1*$stack->pop());\r
+            // if the token is a function, pop arguments off the stack, hand them to the function, and push the result back on\r
+            } elseif (preg_match("/^([a-z]\w*)\($/", $token, $matches)) { // it's a function!\r
+                $fnn = $matches[1];\r
+                if (in_array($fnn, $this->fb)) { // built-in function:\r
+                    if (is_null($op1 = $stack->pop())) return $this->trigger("internal error");\r
+                    $fnn = preg_replace("/^arc/", "a", $fnn); // for the 'arc' trig synonyms\r
+                    if ($fnn == 'ln') $fnn = 'log';\r
+                    eval('$stack->push(' . $fnn . '($op1));'); // perfectly safe eval()\r
+                } elseif (array_key_exists($fnn, $this->f)) { // user function\r
+                    // get args\r
+                    $args = array();\r
+                    for ($i = count($this->f[$fnn]['args'])-1; $i >= 0; $i--) {\r
+                        if (is_null($args[$this->f[$fnn]['args'][$i]] = $stack->pop())) return $this->trigger("internal error");\r
+                    }\r
+                    $stack->push($this->pfx($this->f[$fnn]['func'], $args)); // yay... recursion!!!!\r
+                }\r
+            // if the token is a number or variable, push it on the stack\r
+            } else {\r
+                if (is_numeric($token)) {\r
+                    $stack->push($token);\r
+                } elseif (array_key_exists($token, $this->v)) {\r
+                    $stack->push($this->v[$token]);\r
+                } elseif (array_key_exists($token, $vars)) {\r
+                    $stack->push($vars[$token]);\r
+                } else {\r
+                    return $this->trigger("undefined variable '$token'");\r
+                }\r
+            }\r
+        }\r
+        // when we're out of tokens, the stack should have a single element, the final result\r
+        if ($stack->count != 1) return $this->trigger("internal error");\r
+        return $stack->pop();\r
+    }\r
+    \r
+    // trigger an error, but nicely, if need be\r
+    function trigger($msg) {\r
+        $this->last_error = $msg;\r
+        if (!$this->suppress_errors) trigger_error($msg, E_USER_WARNING);\r
+        return false;\r
+    }\r
+}\r
+\r
+// for internal use\r
+class EvalMathStack {\r
+\r
+    var $stack = array();\r
+    var $count = 0;\r
+    \r
+    function push($val) {\r
+        $this->stack[$this->count] = $val;\r
+        $this->count++;\r
+    }\r
+    \r
+    function pop() {\r
+        if ($this->count > 0) {\r
+            $this->count--;\r
+            return $this->stack[$this->count];\r
+        }\r
+        return null;\r
+    }\r
+    \r
+    function last($n=1) {\r
+        return $this->stack[$this->count-$n];\r
+    }\r
+}\r
+\r
diff --git a/lib/evalmath/example.html b/lib/evalmath/example.html
new file mode 100644 (file)
index 0000000..a5acdad
--- /dev/null
@@ -0,0 +1,37 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">\r
+<html>\r
+<head>\r
+    <title>Example use of EvalMath</title>\r
+</head>\r
+\r
+<body>\r
+    <form method="post" action="">\r
+        y(x) = <input type="text" name="function" value="ln(100-99/(1+e^-(3x)))">\r
+        <input type="submit">\r
+    </form>\r
+       <table border="1">\r
+               <tr><th>x</th><th>y(x)</th>\r
+               <tr><td>-2</td><td>4.6027192880649</td></tr>\r
+               <tr><td>-1.8</td><td>4.6007089389783</td></tr>\r
+               <tr><td>-1.6</td><td>4.5970564127341</td></tr>\r
+               <tr><td>-1.4</td><td>4.5904358758421</td></tr>\r
+               <tr><td>-1.2</td><td>4.5784862928819</td></tr>\r
+               <tr><td>-1</td><td>4.5570805812015</td></tr>\r
+               <tr><td>-0.8</td><td>4.5192408021284</td></tr>\r
+               <tr><td>-0.6</td><td>4.4538441996618</td></tr>\r
+               <tr><td>-0.4</td><td>4.3448951339589</td></tr>\r
+               <tr><td>-0.2</td><td>4.1731553470264</td></tr>\r
+               <tr><td>0</td><td>3.9219733362813</td></tr>\r
+               <tr><td>0.2</td><td>3.5857394070469</td></tr>\r
+               <tr><td>0.4</td><td>3.1745496325453</td></tr>\r
+               <tr><td>0.6</td><td>2.7109297462397</td></tr>\r
+               <tr><td>0.8</td><td>2.2229028235855</td></tr>\r
+               <tr><td>1</td><td>1.7396169449748</td></tr>\r
+               <tr><td>1.2</td><td>1.2900869290353</td></tr>\r
+               <tr><td>1.4</td><td>0.90122953436788</td></tr>\r
+               <tr><td>1.6</td><td>0.59227355272826</td></tr>\r
+               <tr><td>1.8</td><td>0.36820000460355</td></tr>\r
+               <tr><td>2</td><td>0.21896659396653</td></tr>\r
+       </table>\r
+</body>\r
+</html>\r
diff --git a/lib/evalmath/example.php b/lib/evalmath/example.php
new file mode 100644 (file)
index 0000000..191bf28
--- /dev/null
@@ -0,0 +1,31 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">\r
+<html>\r
+<head>\r
+    <title>Example use of EvalMath</title>\r
+</head>\r
+\r
+<body>\r
+    <form method="post" action="<?=$_SERVER['PHP_SELF']?>">\r
+        y(x) = <input type="text" name="function" value="<?=(isset($_POST['function']) ? htmlspecialchars($_POST['function']) : '')?>">\r
+        <input type="submit">\r
+    </form>\r
+    <?\r
+if (isset($_POST['function']) and $_POST['function']) {\r
+       include('evalmath.class.php');\r
+       $m = new EvalMath;\r
+       $m->suppress_errors = true;\r
+       if ($m->evaluate('y(x) = ' . $_POST['function'])) {\r
+               print "\t<table border=\"1\">\n";\r
+               print "\t\t<tr><th>x</th><th>y(x)</th>\n";\r
+               for ($x = -2; $x <= 2; $x+=.2) {\r
+                       $x = round($x, 2);\r
+                       print "\t\t<tr><td>$x</td><td>" . $m->e("y($x)") . "</td></tr>\n";\r
+               }\r
+               print "\t</table>\n";\r
+       } else {\r
+               print "\t<p>Could not evaluate function: " . $m->last_error . "</p>\n";\r
+       }\r
+}\r
+?>\r
+</body>\r
+</html>\r