3 require_once $CFG->dirroot
.'/lib/evalmath/evalmath.class.php';
6 * This class abstracts evaluation of spreadsheet formulas.
7 * See unit tests in lib/simpletest/testmathslib.php for sample usage.
9 * @author Petr Skoda (skodak)
10 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
16 var $_nfx = false; // postfix notation
17 var $_error = false; // last error
20 * Constructor for spreadsheet formula with optional parameters
22 * @param string $formula with leading =
23 * @param array $params associative array of parameters used in formula. All parameter names must be lowercase!
25 function calc_formula($formula, $params=false) {
26 $this->_em
= new EvalMath();
27 $this->_em
->suppress_errors
= true;
28 if (strpos($formula, '=') !== 0) {
29 $this->_error
= "missing leading '='";
32 $formula = substr($formula, 1);
33 if (strpos($formula, '=') !== false) {
34 $this->_error
= "too many '='";
37 $this->_nfx
= $this->_em
->nfx($formula);
38 if ($this->_nfx
== false) {
39 $this->_error
= $this->_em
->last_error
;
42 if ($params != false) {
43 $this->set_params($params);
48 * Raplace parameters used in existing formula,
49 * parameter names must contain only lowercase [a-z] letters, no other characters are allowed!
51 * @param array $params associative array of parameters used in formula
53 function set_params($params) {
54 $this->_em
->v
= $params;
60 * @return mixed number if ok, false if error
63 if ($this->_nfx
== false) {
66 $res = $this->_em
->pfx($this->_nfx
);
68 $this->_error
= $this->_em
->last_error
;
71 $this->_error
= false;
78 * TODO: localize the strings from contructor and EvalMath library
80 * @return mixed string with last error description or false if ok
82 function get_error() {
87 * Similar to format_float, formats the numbers and list separators
88 * according to locale specifics.
89 * @param string $formula
90 * @return string localised formula
92 function localize($formula) {
93 $formula = str_replace('.', '$', $formula); // temp placeholder
94 $formula = str_replace(',', get_string('listsep'), $formula);
95 $formula = str_replace('$', get_string('decsep'), $formula);
100 * Similar to unformat_float, converts floats and lists to PHP standards.
101 * @param string $formula localised formula
104 function unlocalize($formula) {
105 $formula = str_replace(get_string('decsep'), '$', $formula);
106 $formula = str_replace(get_string('listsep'), ',', $formula);
107 $formula = str_replace('$', '.', $formula); // temp placeholder