PageRenderTime 40ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/src/_includes/Smarty/plugins/function.math.php

https://bitbucket.org/dereckson/icedeck
PHP | 84 lines | 50 code | 11 blank | 23 comment | 20 complexity | 0b33b8526bcff403e3d650c3d7eb982b MD5 | raw file
Possible License(s): GPL-2.0
  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. ?>