5 * This plugin is only for Smarty2 BC
7 * @subpackage PluginsFunction
11 * Smarty {math} function plugin
15 * Purpose: handle math computations in template
17 * @link http://www.smarty.net/manual/en/language.function.math.php {math}
18 * (Smarty online manual)
19 * @author Monte Ohrt <monte at ohrt dot com>
20 * @param array $params parameters
21 * @param Smarty_Internal_Template $template template object
24 function smarty_function_math($params, $template)
26 static $_allowed_funcs = array(
27 'int' => true, 'abs' => true, 'ceil' => true, 'cos' => true, 'exp' => true, 'floor' => true,
28 'log' => true, 'log10' => true, 'max' => true, 'min' => true, 'pi' => true, 'pow' => true,
29 'rand' => true, 'round' => true, 'sin' => true, 'sqrt' => true, 'srand' => true ,'tan' => true
31 // be sure equation parameter is present
32 if (empty($params['equation'])) {
33 trigger_error("math: missing equation parameter",E_USER_WARNING);
37 $equation = $params['equation'];
39 // make sure parenthesis are balanced
40 if (substr_count($equation,"(") != substr_count($equation,")")) {
41 trigger_error("math: unbalanced parenthesis",E_USER_WARNING);
45 // match all vars in equation, make sure all are passed
46 preg_match_all("!(?:0x[a-fA-F0-9]+)|([a-zA-Z][a-zA-Z0-9_]*)!",$equation, $match);
48 foreach($match[1] as $curr_var) {
49 if ($curr_var && !isset($params[$curr_var]) && !isset($_allowed_funcs[$curr_var])) {
50 trigger_error("math: function call $curr_var not allowed",E_USER_WARNING);
55 foreach($params as $key => $val) {
56 if ($key != "equation" && $key != "format" && $key != "assign") {
57 // make sure value is not empty
58 if (strlen($val)==0) {
59 trigger_error("math: parameter $key is empty",E_USER_WARNING);
62 if (!is_numeric($val)) {
63 trigger_error("math: parameter $key: is not numeric",E_USER_WARNING);
66 $equation = preg_replace("/\b$key\b/", " \$params['$key'] ", $equation);
69 $smarty_math_result = null;
70 eval("\$smarty_math_result = ".$equation.";");
72 if (empty($params['format'])) {
73 if (empty($params['assign'])) {
74 return $smarty_math_result;
76 $template->assign($params['assign'],$smarty_math_result);
79 if (empty($params['assign'])){
80 printf($params['format'],$smarty_math_result);
82 $template->assign($params['assign'],sprintf($params['format'],$smarty_math_result));