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-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');
41
foreach($match[2] as $curr_var) {
42
if (!in_array($curr_var,array_keys($params)) && !in_array($curr_var, $allowed_funcs)) {
43
$smarty->trigger_error("math: parameter $curr_var not passed as argument");
48
foreach($params as $key => $val) {
49
if ($key != "equation" && $key != "format" && $key != "assign") {
50
// make sure value is not empty
51
if (strlen($val)==0) {
52
$smarty->trigger_error("math: parameter $key is empty");
55
if (!is_numeric($val)) {
56
$smarty->trigger_error("math: parameter $key: is not numeric");
59
$equation = preg_replace("/\b$key\b/",$val, $equation);
63
eval("\$smarty_math_result = ".$equation.";");
65
if (empty($params['format'])) {
66
if (empty($params['assign'])) {
67
return $smarty_math_result;
69
$smarty->assign($params['assign'],$smarty_math_result);
72
if (empty($params['assign'])){
73
printf($params['format'],$smarty_math_result);
75
$smarty->assign($params['assign'],sprintf($params['format'],$smarty_math_result));
80
/* vim: set expandtab: */