PageRenderTime 41ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/code/ryzom/tools/server/admin/smarty/plugins/function.math.php

https://bitbucket.org/mattraykowski/ryzomcore_demoshard
PHP | 83 lines | 50 code | 11 blank | 22 comment | 20 complexity | f7a46fbbe8541e8506954dbe18d24198 MD5 | raw file
Possible License(s): AGPL-3.0, GPL-3.0, LGPL-2.1
  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. * @param array
  16. * @param Smarty
  17. * @return string
  18. */
  19. function smarty_function_math($params, &$smarty)
  20. {
  21. // be sure equation parameter is present
  22. if (empty($params['equation'])) {
  23. $smarty->trigger_error("math: missing equation parameter");
  24. return;
  25. }
  26. $equation = $params['equation'];
  27. // make sure parenthesis are balanced
  28. if (substr_count($equation,"(") != substr_count($equation,")")) {
  29. $smarty->trigger_error("math: unbalanced parenthesis");
  30. return;
  31. }
  32. // match all vars in equation, make sure all are passed
  33. preg_match_all("!(?:0x[a-fA-F0-9]+)|([a-zA-Z][a-zA-Z0-9_]+)!",$equation, $match);
  34. $allowed_funcs = array('int','abs','ceil','cos','exp','floor','log','log10',
  35. 'max','min','pi','pow','rand','round','sin','sqrt','srand','tan');
  36. foreach($match[1] as $curr_var) {
  37. if ($curr_var && !in_array($curr_var, array_keys($params)) && !in_array($curr_var, $allowed_funcs)) {
  38. $smarty->trigger_error("math: function call $curr_var not allowed");
  39. return;
  40. }
  41. }
  42. foreach($params as $key => $val) {
  43. if ($key != "equation" && $key != "format" && $key != "assign") {
  44. // make sure value is not empty
  45. if (strlen($val)==0) {
  46. $smarty->trigger_error("math: parameter $key is empty");
  47. return;
  48. }
  49. if (!is_numeric($val)) {
  50. $smarty->trigger_error("math: parameter $key: is not numeric");
  51. return;
  52. }
  53. $equation = preg_replace("/\b$key\b/",$val, $equation);
  54. }
  55. }
  56. eval("\$smarty_math_result = ".$equation.";");
  57. if (empty($params['format'])) {
  58. if (empty($params['assign'])) {
  59. return $smarty_math_result;
  60. } else {
  61. $smarty->assign($params['assign'],$smarty_math_result);
  62. }
  63. } else {
  64. if (empty($params['assign'])){
  65. printf($params['format'],$smarty_math_result);
  66. } else {
  67. $smarty->assign($params['assign'],sprintf($params['format'],$smarty_math_result));
  68. }
  69. }
  70. }
  71. /* vim: set expandtab: */
  72. ?>