]> git.sur5r.net Git - bacula/bacula/blob - gui/bacula-web/external_packages/smarty/plugins/function.math.php
commit changes
[bacula/bacula] / gui / bacula-web / external_packages / smarty / plugins / function.math.php
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-fA-F0-9]+)|([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     
42     foreach($match[1] as $curr_var) {
43         if ($curr_var && !in_array($curr_var, array_keys($params)) && !in_array($curr_var, $allowed_funcs)) {
44             $smarty->trigger_error("math: function call $curr_var not allowed");
45             return;
46         }
47     }
48
49     foreach($params as $key => $val) {
50         if ($key != "equation" && $key != "format" && $key != "assign") {
51             // make sure value is not empty
52             if (strlen($val)==0) {
53                 $smarty->trigger_error("math: parameter $key is empty");
54                 return;
55             }
56             if (!is_numeric($val)) {
57                 $smarty->trigger_error("math: parameter $key: is not numeric");
58                 return;
59             }
60             $equation = preg_replace("/\b$key\b/",$val, $equation);
61         }
62     }
63
64     eval("\$smarty_math_result = ".$equation.";");
65
66     if (empty($params['format'])) {
67         if (empty($params['assign'])) {
68             return $smarty_math_result;
69         } else {
70             $smarty->assign($params['assign'],$smarty_math_result);
71         }
72     } else {
73         if (empty($params['assign'])){
74             printf($params['format'],$smarty_math_result);
75         } else {
76             $smarty->assign($params['assign'],sprintf($params['format'],$smarty_math_result));
77         }
78     }
79 }
80
81 /* vim: set expandtab: */
82
83 ?>