preparing ubuntu packages and prepping links
[openemr.git] / library / plugins / function.math.php
blobc080d4dfe68242a05e7c1f1b26311f41b13b85f7
1 <?php
2 /**
3 * Smarty plugin
4 * @package Smarty
5 * @subpackage plugins
6 */
9 /**
10 * Smarty {math} function plugin
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
21 function smarty_function_math($params, &$smarty)
23 // be sure equation parameter is present
24 if (empty($params['equation'])) {
25 $smarty->trigger_error("math: missing equation parameter");
26 return;
29 $equation = $params['equation'];
31 // make sure parenthesis are balanced
32 if (substr_count($equation,"(") != substr_count($equation,")")) {
33 $smarty->trigger_error("math: unbalanced parenthesis");
34 return;
37 // match all vars in equation, make sure all are passed
38 preg_match_all("!\!(0x)([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 foreach($match[2] as $curr_var) {
42 if (!in_array($curr_var,array_keys($params)) && !in_array($curr_var, $allowed_funcs)) {
43 $smarty->trigger_error("math: parameter $curr_var not passed as argument");
44 return;
48 foreach($params as $key => $val) {
49 if ($key != "equation" && $key != "format" && $key != "assign") {
50 // make sure value is not empty
51 if (strlen($val)==0) {
52 $smarty->trigger_error("math: parameter $key is empty");
53 return;
55 if (!is_numeric($val)) {
56 $smarty->trigger_error("math: parameter $key: is not numeric");
57 return;
59 $equation = preg_replace("/\b$key\b/",$val, $equation);
63 eval("\$smarty_math_result = ".$equation.";");
65 if (empty($params['format'])) {
66 if (empty($params['assign'])) {
67 return $smarty_math_result;
68 } else {
69 $smarty->assign($params['assign'],$smarty_math_result);
71 } else {
72 if (empty($params['assign'])){
73 printf($params['format'],$smarty_math_result);
74 } else {
75 $smarty->assign($params['assign'],sprintf($params['format'],$smarty_math_result));
80 /* vim: set expandtab: */