5 * @subpackage plugins
\r
10 * Smarty {math} function plugin
\r
12 * Type: function<br>
\r
14 * Purpose: handle math computations in template<br>
\r
15 * @link http://smarty.php.net/manual/en/language.function.math.php {math}
\r
16 * (Smarty online manual)
\r
21 function smarty_function_math($params, &$smarty)
\r
23 // be sure equation parameter is present
\r
24 if (empty($params['equation'])) {
\r
25 $smarty->trigger_error("math: missing equation parameter");
\r
29 $equation = $params['equation'];
\r
31 // make sure parenthesis are balanced
\r
32 if (substr_count($equation,"(") != substr_count($equation,")")) {
\r
33 $smarty->trigger_error("math: unbalanced parenthesis");
\r
37 // match all vars in equation, make sure all are passed
\r
38 preg_match_all("!\!(0x)([a-zA-Z][a-zA-Z0-9_]*)!",$equation, $match);
\r
39 $allowed_funcs = array('int','abs','ceil','cos','exp','floor','log','log10',
\r
40 'max','min','pi','pow','rand','round','sin','sqrt','srand','tan');
\r
41 foreach($match[2] as $curr_var) {
\r
42 if (!in_array($curr_var,array_keys($params)) && !in_array($curr_var, $allowed_funcs)) {
\r
43 $smarty->trigger_error("math: parameter $curr_var not passed as argument");
\r
48 foreach($params as $key => $val) {
\r
49 if ($key != "equation" && $key != "format" && $key != "assign") {
\r
50 // make sure value is not empty
\r
51 if (strlen($val)==0) {
\r
52 $smarty->trigger_error("math: parameter $key is empty");
\r
55 if (!is_numeric($val)) {
\r
56 $smarty->trigger_error("math: parameter $key: is not numeric");
\r
59 $equation = preg_replace("/\b$key\b/",$val, $equation);
\r
63 eval("\$smarty_math_result = ".$equation.";");
\r
65 if (empty($params['format'])) {
\r
66 if (empty($params['assign'])) {
\r
67 return $smarty_math_result;
\r
69 $smarty->assign($params['assign'],$smarty_math_result);
\r
72 if (empty($params['assign'])){
\r
73 printf($params['format'],$smarty_math_result);
\r
75 $smarty->assign($params['assign'],sprintf($params['format'],$smarty_math_result));
\r
80 /* vim: set expandtab: */
\r