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)
17
* @author Monte Ohrt <monte at ohrt dot com>
22
function smarty_function_math($params, &$smarty)
24
// be sure equation parameter is present
25
if (empty($params['equation'])) {
26
$smarty->trigger_error("math: missing equation parameter");
30
$equation = $params['equation'];
32
// make sure parenthesis are balanced
33
if (substr_count($equation,"(") != substr_count($equation,")")) {
34
$smarty->trigger_error("math: unbalanced parenthesis");
38
// match all vars in equation, make sure all are passed
39
preg_match_all("!(?:0x[a-fA-F0-9]+)|([a-zA-Z][a-zA-Z0-9_]+)!",$equation, $match);
40
$allowed_funcs = array('int','abs','ceil','cos','exp','floor','log','log10',
41
'max','min','pi','pow','rand','round','sin','sqrt','srand','tan');
43
foreach($match[1] as $curr_var) {
44
if ($curr_var && !in_array($curr_var, array_keys($params)) && !in_array($curr_var, $allowed_funcs)) {
45
$smarty->trigger_error("math: function call $curr_var not allowed");
50
foreach($params as $key => $val) {
51
if ($key != "equation" && $key != "format" && $key != "assign") {
52
// make sure value is not empty
53
if (strlen($val)==0) {
54
$smarty->trigger_error("math: parameter $key is empty");
57
if (!is_numeric($val)) {
58
$smarty->trigger_error("math: parameter $key: is not numeric");
61
$equation = preg_replace("/\b$key\b/", " \$params['$key'] ", $equation);
65
eval("\$smarty_math_result = ".$equation.";");
67
if (empty($params['format'])) {
68
if (empty($params['assign'])) {
69
return $smarty_math_result;
71
$smarty->assign($params['assign'],$smarty_math_result);
74
if (empty($params['assign'])){
75
printf($params['format'],$smarty_math_result);
77
$smarty->assign($params['assign'],sprintf($params['format'],$smarty_math_result));
82
/* vim: set expandtab: */