Automatically exported from code.google.com/p/planningalerts
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

function.math.php 2.5 KiB

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