init
[garradin.git] / include / libs / template_lite / plugins / function.math.php
1 <?php
2
3 /*
4 * Template Lite plugin
5 * -------------------------------------------------------------
6 * Type: function
7 * Name: math
8 * Purpose: handle math computations in template
9 * Taken from the original Smarty
10 * http://smarty.php.net
11 * -------------------------------------------------------------
12 */
13 function tpl_function_math($params, &$template_object)
14 {
15 // be sure equation parameter is present
16 if (empty($params['equation']))
17 {
18 throw new Template_Exception("math: missing equation parameter", $template_object);
19 return;
20 }
21
22 $equation = $params['equation'];
23
24 // make sure parenthesis are balanced
25 if (substr_count($equation,"(") != substr_count($equation,")"))
26 {
27 throw new Template_Exception("math: unbalanced parenthesis", $template_object);
28 return;
29 }
30
31 // match all vars in equation, make sure all are passed
32 preg_match_all("![a-zA-Z][a-zA-Z0-9_]*!",$equation, $match);
33 $allowed_funcs = array('int','abs','ceil','cos','exp','floor','log','log10',
34 'max','min','pi','pow','rand','round','sin','sqrt','srand','tan');
35
36 foreach($match[0] as $curr_var)
37 {
38 if (!in_array($curr_var,array_keys($params)) && !in_array($curr_var, $allowed_funcs))
39 {
40 throw new Template_Exception("math: parameter $curr_var not passed as argument", $template_object);
41 return;
42 }
43 }
44
45 foreach($params as $key => $val)
46 {
47 if ($key != "equation" && $key != "format" && $key != "assign")
48 {
49 // make sure value is not empty
50 if (strlen($val)==0)
51 {
52 throw new Template_Exception("math: parameter $key is empty", $template_object);
53 return;
54 }
55 if (!is_numeric($val))
56 {
57 throw new Template_Exception("math: parameter $key: is not numeric", $template_object);
58 return;
59 }
60 $equation = preg_replace("/\b$key\b/",$val, $equation);
61 }
62 }
63
64 eval("\$template_object_math_result = ".$equation.";");
65
66 if (empty($params['format']))
67 {
68 if (empty($params['assign']))
69 {
70 return $template_object_math_result;
71 }
72 else
73 {
74 $template_object->assign($params['assign'],$template_object_math_result);
75 }
76 }
77 else
78 {
79 if (empty($params['assign']))
80 {
81 printf($params['format'],$template_object_math_result);
82 }
83 else
84 {
85 $template_object->assign($params['assign'],sprintf($params['format'],$template_object_math_result));
86 }
87 }
88 }
89
90 ?>