5 * -------------------------------------------------------------
8 * Purpose: handle math computations in template
9 * Taken from the original Smarty
10 * http://smarty.php.net
11 * -------------------------------------------------------------
13 function tpl_function_math($params, &$template_object)
15 // be sure equation parameter is present
16 if (empty($params['equation']))
18 throw new Template_Exception("math: missing equation parameter", $template_object);
22 $equation = $params['equation'];
24 // make sure parenthesis are balanced
25 if (substr_count($equation,"(") != substr_count($equation,")"))
27 throw new Template_Exception("math: unbalanced parenthesis", $template_object);
31 // match all vars in equation, make sure all are passed
32 preg_match_all("![a-zA-Z][a-zA-Z0-9_]*!",$equation, $match);
33 $allowed_funcs = array('int','abs','ceil','cos','exp','floor','log','log10',
34 'max','min','pi','pow','rand','round','sin','sqrt','srand','tan');
36 foreach($match[0] as $curr_var)
38 if (!in_array($curr_var,array_keys($params)) && !in_array($curr_var, $allowed_funcs))
40 throw new Template_Exception("math: parameter $curr_var not passed as argument", $template_object);
45 foreach($params as $key => $val)
47 if ($key != "equation" && $key != "format" && $key != "assign")
49 // make sure value is not empty
52 throw new Template_Exception("math: parameter $key is empty", $template_object);
55 if (!is_numeric($val))
57 throw new Template_Exception("math: parameter $key: is not numeric", $template_object);
60 $equation = preg_replace("/\b$key\b/",$val, $equation);
64 eval("\$template_object_math_result = ".$equation.";");
66 if (empty($params['format']))
68 if (empty($params['assign']))
70 return $template_object_math_result;
74 $template_object->assign($params['assign'],$template_object_math_result);
79 if (empty($params['assign']))
81 printf($params['format'],$template_object_math_result);
85 $template_object->assign($params['assign'],sprintf($params['format'],$template_object_math_result));