PageRenderTime 42ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/bblog/smarty_plugins/function.math.php

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