10 * Smarty {math} function plugin
14 * Purpose: handle math computations in template<br>
15 * @link http://smarty.php.net/manual/en/language.function.math.php {math}
16 * (Smarty online manual)
21 function smarty_function_math($params, &$smarty)
23 // be sure equation parameter is present
24 if (empty($params['equation'])) {
25 $smarty->trigger_error("math: missing equation parameter");
29 $equation = $params['equation'];
31 // make sure parenthesis are balanced
32 if (substr_count($equation,"(") != substr_count($equation,")")) {
33 $smarty->trigger_error("math: unbalanced parenthesis");
37 // match all vars in equation, make sure all are passed
38 preg_match_all("!(?:0x[a-fA-F0-9]+)|([a-zA-Z][a-zA-Z0-9_]+)!",$equation, $match);
39 $allowed_funcs = array('int','abs','ceil','cos','exp','floor','log','log10',
40 'max','min','pi','pow','rand','round','sin','sqrt','srand','tan');
42 foreach($match[1] as $curr_var) {
43 if ($curr_var && !in_array($curr_var, array_keys($params)) && !in_array($curr_var, $allowed_funcs)) {
44 $smarty->trigger_error("math: function call $curr_var not allowed");
49 foreach($params as $key => $val) {
50 if ($key != "equation" && $key != "format" && $key != "assign") {
51 // make sure value is not empty
52 if (strlen($val)==0) {
53 $smarty->trigger_error("math: parameter $key is empty");
56 if (!is_numeric($val)) {
57 $smarty->trigger_error("math: parameter $key: is not numeric");
60 $equation = preg_replace("/\b$key\b/",$val, $equation);
64 eval("\$smarty_math_result = ".$equation.";");
66 if (empty($params['format'])) {
67 if (empty($params['assign'])) {
68 return $smarty_math_result;
70 $smarty->assign($params['assign'],$smarty_math_result);
73 if (empty($params['assign'])){
74 printf($params['format'],$smarty_math_result);
76 $smarty->assign($params['assign'],sprintf($params['format'],$smarty_math_result));
81 /* vim: set expandtab: */