Automatically exported from code.google.com/p/planningalerts
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

85 linhas
2.5 KiB

  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. ?>