function.math.php 2.7 KB

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