[ Index ]

krapohl.info

title

Body

[close]

/pnincludes/Smarty/plugins/ -> function.math.php (source)

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


Generated: Wed Feb 16 22:40:07 2005 Cross-referenced by PHPXref 0.6