PageRenderTime 50ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/external_lib/Smarty/plugins/function.math.php

https://github.com/modulargaming/kittokittokitto
PHP | 84 lines | 50 code | 9 blank | 25 comment | 20 complexity | c082ce10e53e3a9ec729a92d1c94aeca MD5 | raw file
  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. throw new Exception ("math: missing equation parameter");
  28. return;
  29. }
  30. $equation = $params['equation'];
  31. // make sure parenthesis are balanced
  32. if (substr_count($equation,"(") != substr_count($equation,")")) {
  33. throw new Exception ("math: unbalanced parenthesis");
  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. throw new Exception ("math: function call $curr_var not allowed");
  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. throw new Exception ("math: parameter $key is empty");
  51. return;
  52. }
  53. if (!is_numeric($val)) {
  54. throw new Exception ("math: parameter $key: is not numeric");
  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. ?>