1: <?php
2: 3: 4: 5: 6: 7: 8:
9:
10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24:
25: function smarty_function_math($params, $template)
26: {
27: static $_allowed_funcs =
28: array('int' => true, 'abs' => true, 'ceil' => true, 'cos' => true, 'exp' => true, 'floor' => true,
29: 'log' => true, 'log10' => true, 'max' => true, 'min' => true, 'pi' => true, 'pow' => true, 'rand' => true,
30: 'round' => true, 'sin' => true, 'sqrt' => true, 'srand' => true, 'tan' => true);
31:
32: if (empty($params[ 'equation' ])) {
33: trigger_error("math: missing equation parameter", E_USER_WARNING);
34:
35: return;
36: }
37:
38: $equation = $params[ 'equation' ];
39:
40:
41: if (substr_count($equation, "(") != substr_count($equation, ")")) {
42: trigger_error("math: unbalanced parenthesis", E_USER_WARNING);
43:
44: return;
45: }
46:
47:
48: if (strpos($equation, '`') !== false) {
49: trigger_error("math: backtick character not allowed in equation", E_USER_WARNING);
50:
51: return;
52: }
53:
54:
55: if (strpos($equation, '$') !== false) {
56: trigger_error("math: dollar signs not allowed in equation", E_USER_WARNING);
57:
58: return;
59: }
60:
61:
62: preg_match_all('!(?:0x[a-fA-F0-9]+)|([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)!', $equation, $match);
63:
64: foreach ($match[ 1 ] as $curr_var) {
65: if ($curr_var && !isset($params[ $curr_var ]) && !isset($_allowed_funcs[ $curr_var ])) {
66: trigger_error("math: function call $curr_var not allowed", E_USER_WARNING);
67:
68: return;
69: }
70: }
71:
72: foreach ($params as $key => $val) {
73: if ($key != "equation" && $key != "format" && $key != "assign") {
74:
75: if (strlen($val) == 0) {
76: trigger_error("math: parameter $key is empty", E_USER_WARNING);
77:
78: return;
79: }
80: if (!is_numeric($val)) {
81: trigger_error("math: parameter $key: is not numeric", E_USER_WARNING);
82:
83: return;
84: }
85: $equation = preg_replace("/\b$key\b/", " \$params['$key'] ", $equation);
86: }
87: }
88: $smarty_math_result = null;
89: eval("\$smarty_math_result = " . $equation . ";");
90:
91: if (empty($params[ 'format' ])) {
92: if (empty($params[ 'assign' ])) {
93: return $smarty_math_result;
94: } else {
95: $template->assign($params[ 'assign' ], $smarty_math_result);
96: }
97: } else {
98: if (empty($params[ 'assign' ])) {
99: printf($params[ 'format' ], $smarty_math_result);
100: } else {
101: $template->assign($params[ 'assign' ], sprintf($params[ 'format' ], $smarty_math_result));
102: }
103: }
104: }
105: