1 <?php
2 /**
3 * Smarty plugin
4 *
5 * This plugin is only for Smarty2 BC
6 * @package Smarty
7 * @subpackage PluginsFunction
8 */
11 /**
12 * Smarty {math} function plugin
13 *
14 * Type: function<br>
15 * Name: math<br>
16 * Purpose: handle math computations in template<br>
17 * @link http://smarty.php.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 object $smarty Smarty object
22 * @param object $template template object
23 * @return string|null
24 */
25 function smarty_function_math($params, $smarty, $template)
26 {
27 // be sure equation parameter is present
28 if (empty($params['equation'])) {
29 trigger_error("math: missing equation parameter",E_USER_WARNING);
30 return;
31 }
33 $equation = $params['equation'];
35 // make sure parenthesis are balanced
36 if (substr_count($equation,"(") != substr_count($equation,")")) {
37 trigger_error("math: unbalanced parenthesis",E_USER_WARNING);
38 return;
39 }
41 // match all vars in equation, make sure all are passed
42 preg_match_all("!(?:0x[a-fA-F0-9]+)|([a-zA-Z][a-zA-Z0-9_]+)!",$equation, $match);
43 $allowed_funcs = array('int','abs','ceil','cos','exp','floor','log','log10',
44 'max','min','pi','pow','rand','round','sin','sqrt','srand','tan');
46 foreach($match[1] as $curr_var) {
47 if ($curr_var && !in_array($curr_var, array_keys($params)) && !in_array($curr_var, $allowed_funcs)) {
48 trigger_error("math: function call $curr_var not allowed",E_USER_WARNING);
49 return;
50 }
51 }
53 foreach($params as $key => $val) {
54 if ($key != "equation" && $key != "format" && $key != "assign") {
55 // make sure value is not empty
56 if (strlen($val)==0) {
57 trigger_error("math: parameter $key is empty",E_USER_WARNING);
58 return;
59 }
60 if (!is_numeric($val)) {
61 trigger_error("math: parameter $key: is not numeric",E_USER_WARNING);
62 return;
63 }
64 $equation = preg_replace("/\b$key\b/", " \$params['$key'] ", $equation);
65 }
66 }
68 eval("\$smarty_math_result = ".$equation.";");
70 if (empty($params['format'])) {
71 if (empty($params['assign'])) {
72 return $smarty_math_result;
73 } else {
74 $template->assign($params['assign'],$smarty_math_result);
75 }
76 } else {
77 if (empty($params['assign'])){
78 printf($params['format'],$smarty_math_result);
79 } else {
80 $template->assign($params['assign'],sprintf($params['format'],$smarty_math_result));
81 }
82 }
83 }
84 ?>