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