| 1 |
<?php |
| 2 |
/** |
| 3 |
* Smarty plugin |
| 4 |
* @package Smarty |
| 5 |
* @subpackage plugins |
| 6 |
*/ |
| 7 |
|
| 8 |
|
| 9 |
/** |
| 10 |
* Smarty {math} function plugin |
| 11 |
* |
| 12 |
* Type: function<br> |
| 13 |
* Name: math<br> |
| 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 |
* @param array |
| 18 |
* @param Smarty |
| 19 |
* @return string |
| 20 |
*/ |
| 21 |
function smarty_function_math($params, &$smarty) |
| 22 |
{ |
| 23 |
// be sure equation parameter is present |
| 24 |
if (empty($params['equation'])) { |
| 25 |
$smarty->trigger_error("math: missing equation parameter"); |
| 26 |
return; |
| 27 |
} |
| 28 |
|
| 29 |
$equation = $params['equation']; |
| 30 |
|
| 31 |
// make sure parenthesis are balanced |
| 32 |
if (substr_count($equation,"(") != substr_count($equation,")")) { |
| 33 |
$smarty->trigger_error("math: unbalanced parenthesis"); |
| 34 |
return; |
| 35 |
} |
| 36 |
|
| 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"); |
| 44 |
return; |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 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"); |
| 53 |
return; |
| 54 |
} |
| 55 |
if (!is_numeric($val)) { |
| 56 |
$smarty->trigger_error("math: parameter $key: is not numeric"); |
| 57 |
return; |
| 58 |
} |
| 59 |
$equation = preg_replace("/\b$key\b/",$val, $equation); |
| 60 |
} |
| 61 |
} |
| 62 |
|
| 63 |
eval("\$smarty_math_result = ".$equation.";"); |
| 64 |
|
| 65 |
if (empty($params['format'])) { |
| 66 |
if (empty($params['assign'])) { |
| 67 |
return $smarty_math_result; |
| 68 |
} else { |
| 69 |
$smarty->assign($params['assign'],$smarty_math_result); |
| 70 |
} |
| 71 |
} else { |
| 72 |
if (empty($params['assign'])){ |
| 73 |
printf($params['format'],$smarty_math_result); |
| 74 |
} else { |
| 75 |
$smarty->assign($params['assign'],sprintf($params['format'],$smarty_math_result)); |
| 76 |
} |
| 77 |
} |
| 78 |
} |
| 79 |
|
| 80 |
/* vim: set expandtab: */ |
| 81 |
|
| 82 |
?> |