Gyvr a écrit:Bonjour,
J'ai des erreurs avec le calulateur qui génère l'erreur suivante ((en utilisant la fonction "tester" du script:
internal error 2<br />
<b>Warning</b>: Cannot modify header information - headers already sent by (output started at /mnt/flash/puch/www/script/user/20164/calculator.php:430) in <b>/mnt/flash/puch/www/script/script_include.php</b> on line <b>74</b><br />
<result></result>
Après divers tests et simplification de la formule de calcul, je constate qu'avec la formule suivante dans VAR1 "15*(1-1)" j'ai l'erreur
internal error 2<result></result>
Par contre avec la formule "15*(2-1)" j'obtiens le bon résultat.
Il semble que si la valeur calculée entre parenthèses est égale à zéro ca plante, et si c'est non nul le résultat du calcul est bon.
Merci de votre aide.
Gérard
==null
===null
<?php
// Create an object to compute the formula
$evaleedomus = new sdk_EvalMath;
// Get formula from VAR1
$formula = getArg("formula");
if (!isset($formula)) $formula = "0";
// basic evaluation:
$result = $evaleedomus->sdk_evaluate($formula);
sdk_header('text/xml');
echo "<result>".$result."</result>";
/*
Script développé par :
Mickael VIALAT - http://www.planete-domotique.com
Basé sur l'excellent travail de Miles Kaufmann : EvalMath Class
Merci de partager toute modification ou amélioration de ce script avec la communauté eedomus
sur le forum : http://forum.eedomus.com
================================================================================
EvalMath - PHP Class to safely evaluate math expressions
Copyright (C) 2005 Miles Kaufmann <http://www.twmagic.com/>
================================================================================
LICENSE
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1 Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
class sdk_EvalMath {
var $suppress_errors = false;
var $last_error = null;
var $v = array('e'=>2.71,'pi'=>3.14); // variables (and constants)
var $f = array(); // user-defined functions
var $vb = array('e', 'pi'); // constants
var $fb = array( // built-in functions
'device', 'abs', 'acos', 'asin', 'atan', 'cos', 'deg2rad', 'exp', 'floor', 'log', 'pow', 'rad2deg', 'rand', 'round', 'sin', 'sqrt');
var $devicetab = array(); // user-defined functions
function sdk_EvalMath()
{
// make the variables a little more accurate
$this->v['pi'] = pi();
$this->v['e'] = exp(1);
}
function sdk_evaluate($expr)
{
$this->last_error = null;
$expr = trim($expr);
if (substr($expr, -1, 1) == ';') $expr = substr($expr, 0, strlen($expr)-1); // strip semicolons at the end
$arr = $this->sdk_nfx($expr);
return $this->sdk_pfx($arr); // straight up evaluation, woo
}
//===================== HERE BE INTERNAL METHODS ====================\\
// Convert infix to postfix notation
function sdk_nfx($expr)
{
$index = 0;
$stack = new sdk_EvalMathStack;
$output = array(); // postfix form of expression, to be passed to pfx()
$expr = trim(strtolower($expr));
$ops = array('+', '-', '*', '/', '^', '_');
$ops_r = array('+'=>0,'-'=>0,'*'=>0,'/'=>0,'^'=>1); // right-associative operator?
$ops_p = array('+'=>0,'-'=>0,'*'=>1,'/'=>1,'_'=>1,'^'=>2); // operator precedence
$expecting_op = false; // we use this in syntax-checking the expression
// and determining when a - is a negation
if (preg_match("/[^\w\s+*^\/()\.,-]/", $expr, $matches))
{ // make sure the characters are all good
return $this->sdk_trigger("illegal character '{$matches[0]}'");
}
while(1)
{ // 1 Infinite Loop ;)
$op = substr($expr, $index, 1); // get the first character at the current index
// find out if we're currently at the beginning of a number/variable/function/parenthesis/operand
$ex = preg_match('/^([a-z]\w*\(?|\d+(?:\.\d*)?|\.\d+|\()/', substr($expr, $index), $match);
//===============
if ($op == '-' && !$expecting_op)
{ // is it a negation instead of a minus?
$stack->sdk_push('_'); // put a negation on the stack
$index++;
}
else
if ($op == '_')
{ // we have to explicitly deny this, because it's legal on the stack
return $this->sdk_trigger("illegal character '_'"); // but not in the input expression
}
else
if ((in_array($op, $ops) || $ex) && $expecting_op)
{ // are we putting an operator on the stack?
if ($ex) { // are we expecting an operator but have a number/variable/function/opening parethesis?
$op = '*'; $index--; // it's an implicit multiplication
}
// heart of the algorithm:
while($stack->count > 0 && ($o2 = $stack->sdk_last()) && in_array($o2, $ops) && ($ops_r[$op] ? $ops_p[$op] < $ops_p[$o2] : $ops_p[$op] <= $ops_p[$o2]))
{
$output[] = $stack->sdk_pop(); // pop stuff off the stack into the output
}
// many thanks: http://en.wikipedia.org/wiki/Reverse_Polish_notation#The_algorithm_in_detail
$stack->sdk_push($op); // finally put OUR operator onto the stack
$index++;
$expecting_op = false;
//===============
}
else
if ($op == ')' && $expecting_op)
{ // ready to close a parenthesis?
while (($o2 = $stack->sdk_pop()) != '(')
{ // pop off the stack back to the last (
if ($o2===null) return $this->sdk_trigger("unexpected ')'");
else $output[] = $o2;
}
if (preg_match("/^([a-z]\w*)\($/", $stack->sdk_last(2), $matches))
{ // did we just close a function?
$fnn = $matches[1]; // get the function name
$arg_count = $stack->sdk_pop(); // see how many arguments there were (cleverly stored on the stack, thank you)
$output[] = $stack->sdk_pop(); // pop the function and push onto the output
if (in_array($fnn, $this->fb))
{ // check the argument count
if($arg_count > 1)
return $this->sdk_trigger("too many arguments ($arg_count given, 1 expected)");
}
else
{ // did we somehow push a non-function on the stack? this should never happen
return $this->sdk_trigger("internal error 1");
}
}
$index++;
//===============
}
else
if ($op == ',' && $expecting_op)
{ // did we just finish a function argument?
while (($o2 = $stack->sdk_pop()) != '(')
{
if ($o2===null) return $this->sdk_trigger("unexpected ','"); // oops, never had a (
else $output[] = $o2; // pop the argument expression stuff and push onto the output
}
// make sure there was a function
if (!preg_match("/^([a-z]\w*)\($/", $stack->sdk_last(2), $matches))
return $this->sdk_trigger("unexpected ','");
$stack->sdk_push($stack->sdk_pop()+1); // increment the argument count
$stack->sdk_push('('); // put the ( back on, we'll need to pop back to it again
$index++;
$expecting_op = false;
//===============
}
else
if ($op == '(' && !$expecting_op)
{
$stack->sdk_push('('); // that was easy
$index++;
$allow_neg = true;
//===============
}
else
if ($ex && !$expecting_op)
{ // do we now have a function/variable/number?
$expecting_op = true;
$val = $match[1];
if (preg_match("/^([a-z]\w*)\($/", $val, $matches))
{ // may be func, or variable w/ implicit multiplication against parentheses...
if (in_array($matches[1], $this->fb) or array_key_exists($matches[1], $this->f))
{ // it's a func
$stack->sdk_push($val);
$stack->sdk_push(1);
$stack->sdk_push('(');
$expecting_op = false;
}
else
{ // it's a var w/ implicit multiplication
$val = $matches[1];
$output[] = $val;
}
}
else
{ // it's a plain old var or num
$output[] = $val;
}
$index += strlen($val);
//===============
}
else
if ($op == ')')
{ // miscellaneous error checking
return $this->sdk_trigger("unexpected ')'");
}
else
if (in_array($op, $ops) && !$expecting_op)
{
return $this->sdk_trigger("unexpected operator '$op'");
}
else
{ // I don't even want to know what you did to get here
return $this->sdk_trigger("an unexpected error occured");
}
if ($index == strlen($expr))
{
if (in_array($op, $ops))
{ // did we end with an operator? bad.
return $this->sdk_trigger("operator '$op' lacks operand");
}
else
break;
}
while (substr($expr, $index, 1) == ' ')
{ // step the index past whitespace (pretty much turns whitespace
$index++; // into implicit multiplication if no operator is there)
}
}
while (($op = $stack->sdk_pop())!=null)
{ // pop everything off the stack and push onto output
if ($op == '(') return $this->sdk_trigger("expecting ')'"); // if there are (s on the stack, ()s were unbalanced
$output[] = $op;
}
return $output;
}
function sdk_device($val)
{
$valtab = getValue($val);
if (isset($valtab['value']))
return $valtab['value'];
else
return 0;
}
// evaluate postfix notation
function sdk_pfx($tokens, $vars = array())
{
if ($tokens == false) return false;
$stack = new sdk_EvalMathStack;
foreach ($tokens as $token)
{ // nice and easy
// if the token is a binary operator, pop two values off the stack, do the operation, and push the result back on
if (in_array($token, array('+', '-', '*', '/', '^')))
{
if (($op2 = $stack->sdk_pop())===null) return $this->sdk_trigger("internal error 2");
if (($op1 = $stack->sdk_pop())===null) return $this->sdk_trigger("internal error 3");
switch ($token) {
case '+':
$stack->sdk_push($op1+$op2); break;
case '-':
$stack->sdk_push($op1-$op2); break;
case '*':
$stack->sdk_push($op1*$op2); break;
case '/':
if ($op2 == 0) return $this->sdk_trigger("division by zero");
$stack->sdk_push($op1/$op2); break;
case '^':
$stack->sdk_push(pow($op1, $op2)); break;
}
// if the token is a unary operator, pop one value off the stack, do the operation, and push it back on
}
else
if ($token == "_")
{
$stack->sdk_push(-1*$stack->sdk_pop());
// if the token is a function, pop arguments off the stack, hand them to the function, and push the result back on
}
else
if (preg_match("/^([a-z]\w*)\($/", $token, $matches))
{ // it's a function!
$fnn = $matches[1];
if (in_array($fnn, $this->fb)) { // built-in function:
if (($op1 = $stack->sdk_pop())===null) return $this->sdk_trigger("internal error 4");
$fnn = preg_replace("/^arc/", "a", $fnn); // for the 'arc' trig synonyms
switch ($fnn)
{
case "device" :
$stack->sdk_push($this->sdk_device($op1));
break;
case "abs":
$stack->sdk_push(abs($op1));
break;
case "acos":
$stack->sdk_push(acos($op1));
break;
case "asin":
$stack->sdk_push(asin($op1));
break;
case "atan":
$stack->sdk_push(atan($op1));
break;
case "cos":
$stack->sdk_push(cos($op1));
break;
case "deg2rad":
$stack->sdk_push(deg2rad($op1));
break;
case "exp":
$stack->sdk_push(exp($op1));
break;
case "floor":
$stack->sdk_push(floor($op1));
break;
case "log":
$stack->sdk_push(log($op1));
break;
case "pow":
$stack->sdk_push(pow($op1));
break;
case "rad2deg":
$stack->sdk_push(rad2deg($op1));
break;
case "rand":
$stack->sdk_push(rand($op1));
break;
case "round":
$stack->sdk_push(round($op1));
break;
case "sin":
$stack->sdk_push(sin($op1));
break;
case "sqrt":
$stack->sdk_push(sqrt($op1));
break;
}
}
else
if (array_key_exists($fnn, $this->f))
{ // user function
// get args
$args = array();
for ($i = count($this->f[$fnn]['args'])-1; $i >= 0; $i--)
{
if (($args[$this->f[$fnn]['args'][$i]] = $stack->sdk_pop())===null) return $this->sdk_trigger("internal error 5");
}
$stack->sdk_push($this->sdk_pfx($this->f[$fnn]['func'], $args)); // yay... recursion!!!!
}
// if the token is a number or variable, push it on the stack
}
else
{
if (is_numeric($token))
{
$stack->sdk_push($token);
}
else
if (array_key_exists($token, $this->v))
{
$stack->sdk_push($this->v[$token]);
}
else
if (array_key_exists($token, $vars))
{
$stack->sdk_push($vars[$token]);
}
else
{
return $this->sdk_trigger("undefined variable '$token'");
}
}
}
// when we're out of tokens, the stack should have a single element, the final result
if ($stack->count != 1) return $this->sdk_trigger("internal error 6");
return $stack->sdk_pop();
}
// trigger an error, but nicely, if need be
function sdk_trigger($msg)
{
$this->last_error = $msg;
if (!$this->suppress_errors) echo $msg;
return false;
}
}
class sdk_EvalMathStack
{
var $stack = array();
var $count = 0;
function sdk_push($val)
{
$this->stack[$this->count] = $val;
$this->count++;
}
function sdk_pop()
{
if ($this->count > 0)
{
$this->count--;
return $this->stack[$this->count];
}
return null;
}
function sdk_last($n=1)
{
if (isset($this->stack[$this->count-$n]))
{
return $this->stack[$this->count-$n];
}
return;
}
}
?>
//sdk_header('text/xml');
opa95 a écrit:Bonjour
Pour moi, la version mise en ligne plus haut devrait fonctionner, mais elle doit être validée par les divers utilisateurs.
Ensuite, il faudrait que l'auteur du script (Mickael) (ou la Team) dont je n'ai pas les coordonnées exactes mette sur le store la version correcte.
La nuance entre le == et le === n'est pas toujours bien utilisée, mais à part cela c'est un très beau script qui est bien pratique et avec lequel je n'avais pas rencontré de problème : merci Mickael
Kepasub a écrit:J'ai eu le même problème d'erreur due à un zéro dans le calcul et il a été résolu avec la version proposée ici. Je le commente, au cas où cela aiderait à contribuer à la validation de la proposition. Merci opa95 pour vos collaborations. Et à l'auteur du script (Mickael), pour la calculatrice, que je trouve phénoménale.
leraystep95 a écrit:Bonjour,
J'aimerais utiliser la fonction arrondit dans mon calcul.
Mais dès que j’intègre (, -1) pour avoir un arrondit à la dizaine près.
round(abs(device(3175494))+(device(3175698)), -1)
J'ai le message "too many arguments (2 given, 1 expected)" et l'ERREUR: Valeur lue vide
Alors qu'avec : round(abs(device(3175494))+(device(3175698))) le résultat est correct !
Comment je peux faire ?
"too many arguments (2 given, 1 expected)"
'+', '-', '*', '/', '^', '_','<','>','=',',','§'
'device', 'change','unit','valuetext', 'devunit',
'year', 'month','week','dayweek','day', 'hour', 'minute','weekdec','daydec', 'hourdec', 'minutedec','year_', 'month_', 'day_', 'hour_', 'minute_', 'nbsemaine','nbjour','nbheure','nbminute','hms','hms_','ymd','ymd_','ymdhms','ymdhms_','hm','hm_','gmt','today','datestr','timestr','date','time',
'if','case','text',
'add','and','abs', 'acos', 'asin', 'atan','ceil','concat', 'cos', 'deg2rad', 'deg2degmin','degmin2deg','div','exp','ext','equ', 'floor','frac','ge','gt','in','inv','le','lt','neg','neq', 'log', 'logdec', 'min','max','mod','moyenne','not','or', 'pow', 'prod', 'rad2deg', 'rand', 'round','seuils', 'sin', 'somme', 'sqrt', 'tan','xor';
<?php
// Create an object to compute the formula
$evaleedomus = new sdk_EvalMath;
// Get formula from VAR1
$formula = getArg("formula");
if (!isset($formula)) $formula = "0";
/*
echo $formula.PHP_EOL
// Get variables x from VAR2
$varx_ = getArg("varx",false);
if (!isset($varx)) $varx = "";
else {
$varx = explode('@',$varx_);
foreach ($varx as $cle => $elem){
$search = '$x'.$cle.'$';
$formula = str_replace($search,$elem,$formula);
}
}
// Get variables y from VAR3
$vary_ = getArg("vary",false);
if (!isset($vary)) $vary = "";
else {
$vary = explode('@',$vary);
foreach ($vary as $cle => $elem){
$search = '$y'.$cle.'$';
$formula = str_replace($search,$elem,$formula);
}
}
// Get debug
$debug = getArg("debug",false,0);
*/
// basic evaluation:
$result = $evaleedomus->sdk_evaluate($formula);
@sdk_header('text/xml');
/*
$xml = '<?xml version="1.0" encoding="UTF-8"?>'.PHP_EOL;
$xml .= "<result>".$result;
if ($debug) $xml .= PHP_EOL.'<formule>'.$formula.'</formule>'.PHP_EOL;
$xml .= "</result>";
*/
echo "<result>".$result.'</result>';
/*
Script développé par :
Mickael VIALAT - http://www.planete-domotique.com
Basé sur l'excellent travail de Miles Kaufmann : EvalMath Class
Merci de partager toute modification ou amélioration de ce script avec la communauté eedomus
sur le forum : http://forum.eedomus.com
opérateurs ':' '+' '-' '*' '/' '^'
fonctions : 'abs', 'acos', 'asin', 'atan', 'cos', 'deg2rad', 'exp', 'floor', 'log', 'rad2deg', 'rand', 'round', 'sin', 'sqrt'
eedomus : 'device'
Ajoût d'opérateurs, fonctions e traitement de date et heure // 2022/11 Opa95
opérateurs ':' '+' '-' '*' '/' '^' ',' '<' '=' '>' '§'(remplacement de %) (l'opérateur ',' sert à concaténer les valeurs pour les fonctions)
fonctions complémentaires 'ceil', 'equ'[equal], 'ext', 'frac', 'ge'[greater or equal], 'gt'[greater], 'in', 'le'[lower or equal], 'lt'[lower], 'neq'[not equal], 'not', 'and', 'or', 'min', 'max', 'moyenne', 'pow', 'round', 'seuils', 'tan','somme'
eedomus : 'device', 'change'
Fonctions de date et heure
now -> date actuelle en secondes
year(),month(),week(),day(), hour(),minute() -> Nombre correspondant
year_(),month_(),day_(), hour_(),minute_() -> Nombre formaté (00..)
nbsemaine(),nbjour(),nbheure(),nbminute() -> nombre de secondes correspondantes
today(x) -> heure du jour pour x secondes après 0h
date(yyyymmjjhhmmss) -> date en seconde
time(hhmmss) -> heure aujourdhui
gmt() conversion en gmt
Si les paramètre à passer à une fonction à parametres multiples sont complexes, il vaut mieux les encadrer avec des parentheses.
Exemple : pow((2^2),(2+3))
tester les valeurs complexes quand on utilise la virgule (désolé)
================================================================================
EvalMath - PHP Class to safely evaluate math expressions
Copyright (C) 2005 Miles Kaufmann <http://www.twmagic.com/>
================================================================================
LICENSE
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1 Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
class sdk_EvalMath {
var $suppress_errors = false;
var $last_error = null;
var $v = array('e'=>2.71,'pi'=>3.14,'now'=>0, 'tzoffset'=>3600); // variables (and constants)
var $f = array(); // user-defined functions
var $vb = array('e', 'pi','now','tzoffset'); // constants
var $fb = array( // built-in functions
'device', 'change','unit','valuetext', 'devunit', 'year', 'month','week','dayweek','day', 'hour', 'minute','weekdec','daydec', 'hourdec', 'minutedec','year_', 'month_', 'day_', 'hour_', 'minute_',
'nbsemaine','nbjour','nbheure','nbminute','hms','hms_','ymd','ymd_','ymdhms','ymdhms_','hm','hm_','gmt','today','datestr','timestr','date','time',
'if','case','text',
'add','and','abs', 'acos', 'asin', 'atan','ceil','concat', 'cos', 'deg2rad', 'deg2degmin','degmin2deg','div','exp','ext','equ', 'floor','frac','ge','gt','in','inv','le','lt','neg','neq', 'log', 'logdec', 'min','max','mod','moyenne','not','or', 'pow', 'prod', 'rad2deg', 'rand', 'round','seuils', 'sin', 'somme', 'sqrt', 'tan','xor');
var $devicetab = array(); // user-defined functions
function sdk_EvalMath()
{
// make the variables a little more accurate
$this->v['pi'] = pi();
$this->v['e'] = exp(1);
$this->v['now'] = time();
$this->v['tzoffset'] = date('Z',$v['now']);
}
function sdk_evaluate($expr)
{
$this->last_error = null;
$expr = trim($expr);
if (substr($expr, -1, 1) == ';') $expr = substr($expr, 0, strlen($expr)-1); // strip semicolons at the end
$arr = $this->sdk_nfx($expr);
return $this->sdk_pfx($arr); // straight up evaluation, woo
}
//===================== HERE BE INTERNAL METHODS ====================\\
// Convert infix to postfix notation
function sdk_nfx($expr)
{
$index = 0;
$stack = new sdk_EvalMathStack;
$output = array(); // postfix form of expression, to be passed to pfx()
$expr = trim(strtolower($expr));
$ops = array('+', '-', '*', '/', '^', '_','<','>','=',',','§');
$ops_r = array('+'=>0,'-'=>0,'*'=>0,'/'=>0,'^'=>1,'<'=>0,'>'=>0,'='=>0,','=>0,'§'=>0); // right-associative operator?
$ops_p = array('+'=>0,'-'=>0,'*'=>1,'/'=>1,'_'=>1,'^'=>2,'<'=>0,'>'=>0,'='=>0,','=>0,'&'=>0); // operator precedence
// $ops_p = array('+'=>1,'-'=>1,'*'=>2,'/'=>2,'_'=>2,'^'=>3,'<'=>2,'>'=>2,'='=>2,','=>4,'§'=>2); // operator precedence
$expecting_op = false; // we use this in syntax-checking the expression
// and determining when a - is a negation
if (preg_match("/[^\w\s+*^<>=\/():$\.,-]/,%/", $expr, $matches))
{ // make sure the characters are all good
return $this->sdk_trigger("illegal character '{$matches[0]}'");
}
while(1)
{ // 1 Infinite Loop ;)
$op = substr($expr, $index, 1); // get the first character at the current index
// find out if we're currently at the beginning of a number/variable/function/parenthesis/operand
$ex = preg_match('/^([a-z]\w*\(?|\d+(?:\.\d*)?|\.\d+|\()/', substr($expr, $index), $match);
//===============
if ($op == '-' && !$expecting_op)
{ // is it a negation instead of a minus?
$stack->sdk_push('_'); // put a negation on the stack
$index++;
}
else
if ($op == '_')
{ // we have to explicitly deny this, because it's legal on the stack
return $this->sdk_trigger("illegal character '_'"); // but not in the input expression
}
else
if ((in_array($op, $ops) || $ex) && $expecting_op)
{ // are we putting an operator on the stack?
if ($ex) { // are we expecting an operator but have a number/variable/function/opening parethesis?
$op = '*'; $index--; // it's an implicit multiplication
}
// heart of the algorithm:
while($stack->count > 0 && ($o2 = $stack->sdk_last()) && in_array($o2, $ops) && ($ops_r[$op] ? $ops_p[$op] < $ops_p[$o2] : $ops_p[$op] <= $ops_p[$o2]))
{
$output[] = $stack->sdk_pop(); // pop stuff off the stack into the output
}
// many thanks: http://en.wikipedia.org/wiki/Reverse_Polish_notation#The_algorithm_in_detail
$stack->sdk_push($op); // finally put OUR operator onto the stack
$index++;
$expecting_op = false;
//===============
}
else
if ($op == ')' && $expecting_op)
{ // ready to close a parenthesis?
while (($o2 = $stack->sdk_pop()) != '(')
{ // pop off the stack back to the last (
if ($o2===null) return $this->sdk_trigger("unexpected ')'");
else $output[] = $o2;
}
if (preg_match("/^([a-z]\w*)\($/", $stack->sdk_last(2), $matches))
{ // did we just close a function?
$fnn = $matches[1]; // get the function name
$arg_count = $stack->sdk_pop(); // see how many arguments there were (cleverly stored on the stack, thank you)
$output[] = $stack->sdk_pop(); // pop the function and push onto the output
if (in_array($fnn, $this->fb))
{ // check the argument count
if($arg_count > 1)
return $this->sdk_trigger("too many arguments ($arg_count given, 1 expected)");
}
else
{ // did we somehow push a non-function on the stack? this should never happen
return $this->sdk_trigger("internal error 1");
}
}
$index++;
//===============
}
else
if ($op == ',' && $expecting_op)
{ // did we just finish a function argument?
while (($o2 = $stack->sdk_pop()) != '(')
{
if ($o2===null) return $this->sdk_trigger("unexpected ','"); // oops, never had a (
else $output[] = $o2; // pop the argument expression stuff and push onto the output
}
// make sure there was a function
if (!preg_match("/^([a-z]\w*)\(/", $stack->sdk_last(2), $matches))
return $this->sdk_trigger("unexpected ','");
$stack->sdk_push($stack->sdk_pop()+1); // increment the argument count
$stack->sdk_push('('); // put the ( back on, we'll need to pop back to it again
$index++;
$expecting_op = false;
//===============
}
else
if ($op == '(' && !$expecting_op)
{
$stack->sdk_push('('); // that was easy
$index++;
$allow_neg = true;
//===============
}
else
if ($ex && !$expecting_op)
{ // do we now have a function/variable/number?
$expecting_op = true;
$val = $match[1];
if (preg_match("/^([a-z]\w*)\($/", $val, $matches))
{ // may be func, or variable w/ implicit multiplication against parentheses...
if (in_array($matches[1], $this->fb) or array_key_exists($matches[1], $this->f))
{ // it's a func
$stack->sdk_push($val);
$stack->sdk_push(1);
$stack->sdk_push('(');
$expecting_op = false;
}
else
{ // it's a var w/ implicit multiplication
$val = $matches[1];
$output[] = $val;
}
}
else
{ // it's a plain old var or num
$output[] = $val;
}
$index += strlen($val);
//===============
}
else
if ($op == ')')
{ // miscellaneous error checking
return $this->sdk_trigger("unexpected ')'");
}
else
if (in_array($op, $ops) && !$expecting_op)
{
return $this->sdk_trigger("unexpected operator '$op'");
}
else
{ // I don't even want to know what you did to get here
return $this->sdk_trigger("an unexpected error occured");
}
if ($index == strlen($expr))
{
if (in_array($op, $ops))
{ // did we end with an operator? bad.
return $this->sdk_trigger("operator '$op' lacks operand");
}
else
break;
}
while (substr($expr, $index, 1) == ' ')
{ // step the index past whitespace (pretty much turns whitespace
$index++; // into implicit multiplication if no operator is there)
}
}
while (($op = $stack->sdk_pop())!=null)
{ // pop everything off the stack and push onto output
if ($op == '(') return $this->sdk_trigger("expecting ')'"); // if there are (s on the stack, ()s were unbalanced
$output[] = $op;
}
return $output;
}
function sdk_device($val)
{
$valtab = getValue($val);
if (isset($valtab['value']))
return $valtab['value'];
else
return 0;
}
function sdk_devunit($val)
{
$valtab = getValue($val);
if (isset($valtab['value']))
return $valtab['value'].' '.$valtab['unit'];
else
return 0;
}
function sdk_change($val)
{
$valtab = getValue($val);
if (isset($valtab['change'])){
$time = strtotime($valtab['change']);
return $time;}
else
return time();
}
function sdk_unit($val)
{
$valtab = getValue($val);
if (isset($valtab['unit']))
return $valtab['unit'];
else
return '';
}
function sdk_valuetext($val)
{
$valtab = getValue($val,$value_text=true);
if (isset($valtab['value_text'])) {
$valtab['value_text'] = strtolower(str_replace(' ','',$valtab['value_text']));
return $valtab['value_text']; }
else
return $valtab['value'];
}
function sdk_year($val)
{
return date('Y',$val);
}
function sdk_month($val)
{
return date('n',$val);
}
function sdk_week($val)
{
return date('W',$val);
}
function sdk_dayweek($val)
{
return date('N',$val);
}
function sdk_day($val)
{
return date('j',$val);
}
function sdk_hour($val)
{
return date('G',$val);
}
function sdk_minute($val)
{
$valtab = date('i',$val);
if (strpos($valtab.'0','0') == 1) $valtab = substr($valtab,1);
return $valtab;
}
function sdk_weekdec($val)
{
return date('W',$val)+($val%604800)/604800;
}
function sdk_daydec($val)
{
return date('j',$val)+($val%86400)/86400;
}
function sdk_hourdec($val)
{
return date('G',$val)+($val%3600)/3600;
}
function sdk_minutedec($val)
{
$valtab = date('i',$val);
if (strpos($valtab.'0','0') == 1) $valtab = substr($valtab,1);
return $valtab+($val%60)/60;
}
function sdk_ymd($val)
{
return date('Ymd',$val);
}
function sdk_ymd_($val)
{
return date('Y-m-d',$val);
}
function sdk_ymdhms($val)
{
return date('YmdHis',$val);
}
function sdk_ymdhms_($val)
{
return date('Y-m-d H:i:s',$val);
}
function sdk_hms($val)
{
if ($val>0) return date('His',$val);
else return '-'.date('His',$val);
}
function sdk_hms_($val)
{
if ($val>0) return date('H:i:s',$val);
else return '-'.date('H:i:s',$val);
}
function sdk_hm($val)
{
if ($val>0) return date('Hi',$val);
else return '-'.date('Hi',$val);
}
function sdk_hm_($val)
{
if ($val>0) return date('H:i',$val);
else return '-'.date('H:i',$val);
}
function sdk_month_($val)
{
return date('m',$val);
}
function sdk_day_($val)
{
return date('d',$val);
}
function sdk_hour_($val)
{
return date('h',$val);
}
function sdk_minute_($val)
{
return date('i',$val);
}
function sdk_nbminute($val)
{
return round($val*60);
}
function sdk_nbheure($val)
{
return round($val*3600);
}
function sdk_nbjour($val)
{
return round($val*86400);
}
function sdk_nbsemaine($val)
{
return round($val*604800);
}
function sdk_gmt($val)
{
return $val-date('Z');
}
function sdk_today($val)
{
$valtab = time()-3600;
$valtab = $valtab-$valtab%86400+$val-date('Z');
return $valtab;
}
function sdk_datestr($val)
{
echo ($val);
return strtotime($val);
}
function sdk_timestr($val)
{
$valtab = time()-3600;
$valtab = $valtab-$valtab%86400-date('Z');
$valtab = date('Ymd',$valtab);
return strtotime($valtab.$val);
}
function sdk_date($val)
{
$arr_val = explode('$$$',$val);
$valstr = sprintf("%'.04d",$arr_val[0]);
foreach ($arr_val as $cle => $value) {
if ($cle == 0 ) continue;
$valstr .= sprintf("%'.02d",$value);
}
return strtotime($valstr);
}
function sdk_time($val)
{
$arr_val = explode('$$$',$val);
$valstr = '';
foreach ($arr_val as $cle => $value) {
$valstr .= sprintf("%'.02d",$value);
}
$valtab = time()-3600;
$valtab = $valtab-$valtab%86400-date('Z');
$valtab = date('Ymd',$valtab);
return strtotime($valtab.$valstr);
}
// evaluate postfix notation
function sdk_pfx($tokens, $vars = array())
{
if ($tokens == false) return false;
$stack = new sdk_EvalMathStack;
foreach ($tokens as $token)
{ // nice and easy
// if the token is a binary operator, pop two values off the stack, do the operation, and push the result back on
if (in_array($token, array('+', '-', '*', '/', '^','<','>','=',',','§')))
{
if (($op2 = $stack->sdk_pop())===null) return $this->sdk_trigger("internal error 2");
if (($op1 = $stack->sdk_pop())===null) return $this->sdk_trigger("internal error 3");
switch ($token) {
case '+':
$stack->sdk_push($op1+$op2); break;
case '-':
$stack->sdk_push($op1-$op2); break;
case '*':
$stack->sdk_push($op1*$op2); break;
case '/':
if ($op2 == 0) return $this->sdk_trigger("division by zero");
$stack->sdk_push($op1/$op2); break;
case '^':
$stack->sdk_push(pow($op1, $op2)); break;
case '<':
$val = ($op1<$op2)? 1 : 0;
$stack->sdk_push($val); break;
case '>':
$val = ($op1>$op2)? 1 : 0;
$stack->sdk_push($val); break;
case '=':
$val = ($op1==$op2)? 1 : 0;
$stack->sdk_push($val); break;
case '§':
$stack->sdk_push($op1%$op2); break;
case ',':
$stack->sdk_push($op1.'$$$'.$op2); break;
}
// if the token is a unary operator, pop one value off the stack, do the operation, and push it back on
}
else
if ($token == "_")
{
$stack->sdk_push(-1*$stack->sdk_pop());
// if the token is a function, pop arguments off the stack, hand them to the function, and push the result back on
}
else
if (preg_match("/^([a-z]\w*)\($/", $token, $matches))
{ // it's a function!
$fnn = $matches[1];
if (in_array($fnn, $this->fb)) { // built-in function:
if (($op1 = $stack->sdk_pop())===null) return $this->sdk_trigger("internal error 4");
$fnn = preg_replace("/^arc/", "a", $fnn); // for the 'arc' trig synonyms
switch ($fnn)
{
case "device" :
$stack->sdk_push($this->sdk_device($op1));
break;
case "devunit" :
$stack->sdk_push($this->sdk_devunit($op1));
break;
case "change" :
$stack->sdk_push($this->sdk_change($op1));
break;
case "unit" :
$stack->sdk_push($this->sdk_unit($op1));
break;
case "valuetext" :
$stack->sdk_push($this->sdk_valuetext($op1));
break;
case "year" :
case "year_" :
$stack->sdk_push($this->sdk_year(round($op1)));
break;
case "month" :
$stack->sdk_push($this->sdk_month(round($op1)));
break;
case "week" :
$stack->sdk_push($this->sdk_week(round($op1)));
break;
case "dayweek" :
$stack->sdk_push($this->sdk_dayweek(round($op1)));
break;
case "day" :
$stack->sdk_push($this->sdk_day(round($op1)));
break;
case "hour" :
$stack->sdk_push($this->sdk_hour(round($op1)));
break;
case "minute" :
$stack->sdk_push($this->sdk_minute(round($op1)));
break;
case "weekdec" :
$stack->sdk_push($this->sdk_weekdec(round($op1)));
break;
case "daydec" :
$stack->sdk_push($this->sdk_daydec(round($op1)));
break;
case "hourdec" :
$stack->sdk_push($this->sdk_hourdec(round($op1)));
break;
case "minutedec" :
$stack->sdk_push($this->sdk_minutedec(round($op1)));
break;
case "month_" :
$stack->sdk_push($this->sdk_month_(round($op1)));
break;
case "day_" :
$stack->sdk_push($this->sdk_day_(round($op1)));
break;
case "hour_" :
$stack->sdk_push($this->sdk_hour_(round($op1)));
break;
case "minute_" :
$stack->sdk_push($this->sdk_minute_(round($op1)));
break;
case "nbsemaine" :
$stack->sdk_push($this->sdk_nbsemaine($op1));
break;
case "nbjour" :
$stack->sdk_push($this->sdk_nbjour($op1));
break;
case "nbheure" :
$stack->sdk_push($this->sdk_nbheure($op1));
break;
case "nbminute" :
$stack->sdk_push($this->sdk_nbminute($op1));
break;
case "ymd" :
$stack->sdk_push($this->sdk_ymd(round($op1)));
break;
case "ymd_" :
$stack->sdk_push($this->sdk_ymd_(round($op1)));
break;
case "hms" :
$stack->sdk_push($this->sdk_hms(round($op1)));
break;
case "hms_" :
$stack->sdk_push($this->sdk_hms_(round($op1)));
break;
case "hm" :
$stack->sdk_push($this->sdk_hm(round($op1)));
break;
case "hm_" :
$stack->sdk_push($this->sdk_hm_(round($op1)));
break;
case "ymdhms" :
$stack->sdk_push($this->sdk_ymdhms(round($op1)));
break;
case "ymdhms_" :
$stack->sdk_push($this->sdk_ymdhms_(round($op1)));
break;
case "gmt" :
$stack->sdk_push($this->sdk_gmt(round($op1)));
break;
case "today" :
$stack->sdk_push($this->sdk_today(round($op1)));
break;
case "datestr" :
$stack->sdk_push($this->sdk_datestr($op1));
break;
case "timestr" :
$stack->sdk_push($this->sdk_timestr($op1));
break;
case "date" :
$stack->sdk_push($this->sdk_date($op1));
break;
case "time" :
$stack->sdk_push($this->sdk_time($op1));
break;
case "if":
$arr_val = explode('$$$',$op1);
if ($arr_val[0]) $op1=$arr_val[1]; else $op1=$arr_val[2];
$stack->sdk_push($op1);
break;
case "case":
$arr_val = explode('$$$',$op1);
$arr_val[0] =max(0,min(count($arr_val)-2,round($arr_val[0])))+1;
$stack->sdk_push($arr_val[$arr_val[0]]);
break;
case "abs":
$stack->sdk_push(abs($op1));
break;
case "and":
$arr_val = explode('$$$',$op1);
$op1 = 1;
foreach ($arr_val as $value) {
$op1 = $op1&&$value;
if ($op1==0) break;
}
if ($op1) $op1=1; else $op1=0;
$stack->sdk_push($op1);
break;
case "acos":
$stack->sdk_push(acos($op1));
break;
case "asin":
$stack->sdk_push(asin($op1));
break;
case "atan":
$stack->sdk_push(atan($op1));
break;
case "ceil":
$stack->sdk_push(ceil($op1));
break;
case "concat":
$arr_val = explode('$$$',$op1);
$op1='';
foreach ($arr_val as $value){$op1 .=$value;}
$op1=str_replace('__',' ',$op1);
$stack->sdk_push($op1);
break;
case "cos":
$stack->sdk_push(cos($op1));
break;
case "deg2rad":
$stack->sdk_push(deg2rad($op1));
break;
case "deg2degmin":
$val1 = round((abs($op1)-floor(abs($op1)))*100,9);
$val2 = ($val1-floor($val1))*100;
if ($op1<0) $val1 = ceil($op1)-floor($val1)*6/1000-$val2*6/100000;
else $val1 = floor($op1)+floor($val1)*6/1000+$val2*6/100000;
$stack->sdk_push(round($val1,9));
break;
case "degmin2deg":
$val1 = round((abs($op1)-floor(abs($op1)))*100,9);
$val2 = ($val1-floor($val1))*100;
if ($op1<0) $val1 = ceil($op1)-floor($val1)/60-$val2/6000;
else $val1 = floor($op1)+floor($val1)/60+$val2/6000;
$stack->sdk_push($val1);
break;
case "div":
$arr_val = explode('$$$',$op1);
$op1 = $arr_val[0];
foreach ($arr_val as $cle => $value) {
if ($cle==0) continue;
if ($value==0) {$op1=0;break;}
$op1/=$value;
}
$stack->sdk_push($op1);
break;
case "neq":
case "xor":
case "equ":
$arr_val = explode('$$$',$op1);
$op1 = 1;
foreach ($arr_val as $value) {
if ($value!=$arr_val[0]) {$op1=0; break;}
}
if ($fnn != 'equ') $op1= ($op1)? 0:1;
$stack->sdk_push($op1);
break;
case "exp":
$stack->sdk_push(exp($op1));
break;
case "floor":
$stack->sdk_push(floor($op1));
break;
case "frac":
$stack->sdk_push($op1-floor($op1));
break;
case "lt":
case "ge":
list($val1,$val2) = explode('$$$',$op1);
if ($val1 < $val2) $op1=0; else $op1=1;
if ($fnn == 'lt') $op1= ($op1)? 0:1;
$stack->sdk_push($op1);
break;
case "gt":
case "le":
list($val1,$val2) = explode('$$$',$op1);
if ($val1 > $val2) $op1=0; else $op1=1;
if ($fnn == 'gt') $op1= ($op1)? 0:1;
$stack->sdk_push($op1);
break;
case "ext":
case "in":
list($val1,$val2,$val3) = explode('$$$',$op1);
$op1 = (($val1>=$val2)&&($val1<=$val3))? 1:0;
if ($fnn == 'ext') $op1= ($op1)? 0:1;
$stack->sdk_push($op1);
break;
case "inv":
if ($op1==0) $stack->sdk_push(-$op1);
$stack->sdk_push(1/$op1);
break;
case "log":
$stack->sdk_push(log($op1));
break;
case "logdec":
$stack->sdk_push(log($op1,10));
break;
case "not":
$op1= ($op1)? 0:1;
$stack->sdk_push($op1);
break;
case "max":
$arr_val = explode('$$$',$op1);
$op1 = $arr_val[0];
foreach ($arr_val as $value) {if ($value>$op1) $op1=$value;}
$stack->sdk_push($op1);
break;
case "min":
$arr_val = explode('$$$',$op1);
$op1 = $arr_val[0];
foreach ($arr_val as $value) {if ($value<$op1) $op1=$value;}
$stack->sdk_push($op1);
break;
case "mod":
list($val1,$val2) = explode('$$$',$op1);
$stack->sdk_push($val1%$val2);
break;
case "neg":
$stack->sdk_push(-$op1);
break;
case "add":
case "somme":
case "moyenne":
$arr_val = explode('$$$',$op1);
$op1 = 0;
foreach ($arr_val as $value) {$op1+=$value;}
if ($fnn=='moyenne') $op1 = $op1/count($arr_val);
$stack->sdk_push($op1);
break;
case "or":
$arr_val = explode('$$$',$op1);
$op1 = 0;
foreach ($arr_val as $value) {
$op1 = $op1||$value;
if ($op1) break;
}
if ($op1) $op1=1; else $op1=0;
$stack->sdk_push($op1);
break;
case "pow":
list($val1,$val2) = explode('$$$',$op1);
$stack->sdk_push(pow($val1,$val2));
break;
case "prod":
$arr_val = explode('$$$',$op1);
$op1 = 1;
foreach ($arr_val as $value) {
$op1*=$value;
if ($op1==0) break;
}
$stack->sdk_push($op1);
break;
case "rad2deg":
$stack->sdk_push(rad2deg($op1));
break;
case "rand":
$arr_val = explode('$$$','0$$$'.$op1);
if (count($arr_val)<3) {
$stack->sdk_push(rand($arr_val[0],round($arr_val[1])));
}
else
$stack->sdk_push(rand(round($arr_val[1]),round($arr_val[2])));
break;
case "round":
list($val1,$val2) = explode('$$$',$op1);
$stack->sdk_push(round($val1,round($val2)));
break;
case "seuils":
$arr_val = explode('$$$',$op1);
$ok = 0;
$op1 = 0;
foreach ($arr_val as $cle => $value){
if ($cle==0) continue;
if ($arr_val[0] <= $value) {$op1=$cle;$ok=1;break;}
}
if (!$ok) $op1 = count($arr_val);
$stack->sdk_push($op1-1);
break;
case "sin":
$stack->sdk_push(sin($op1));
break;
case "sqrt":
$stack->sdk_push(sqrt($op1));
break;
case "tan":
$stack->sdk_push(tan($op1));
break;
}
}
else
if (array_key_exists($fnn, $this->f))
{ // user function
// get args
$args = array();
for ($i = count($this->f[$fnn]['args'])-1; $i >= 0; $i--)
{
if (($args[$this->f[$fnn]['args'][$i]] = $stack->sdk_pop())===null) return $this->sdk_trigger("internal error 5");
}
$stack->sdk_push($this->sdk_pfx($this->f[$fnn]['func'], $args)); // yay... recursion!!!!
}
// if the token is a number or variable, push it on the stack
}
else
{
if (is_numeric($token))
{
$stack->sdk_push($token);
}
else
if (array_key_exists($token, $this->v))
{
$stack->sdk_push($this->v[$token]);
}
else
if (array_key_exists($token, $vars))
{
$stack->sdk_push($vars[$token]);
}
else
{
$stack->sdk_push($token);
// return $this->sdk_trigger("undefined variable '$token'");
}
}
}
// when we're out of tokens, the stack should have a single element, the final result
if ($stack->count != 1) return $this->sdk_trigger("internal error 6");
return $stack->sdk_pop();
}
// trigger an error, but nicely, if need be
function sdk_trigger($msg)
{
$this->last_error = $msg;
if (!$this->suppress_errors) echo $msg;
return false;
}
}
class sdk_EvalMathStack
{
var $stack = array();
var $count = 0;
function sdk_push($val)
{
$this->stack[$this->count] = $val;
$this->count++;
}
function sdk_pop()
{
if ($this->count > 0)
{
$this->count--;
return $this->stack[$this->count];
}
return null;
}
function sdk_last($n=1)
{
if (isset($this->stack[$this->count-$n]))
{
return $this->stack[$this->count-$n];
}
return;
}
}
?>
Retour vers Scripts & Périphériques du store
Utilisateurs parcourant ce forum : Aucun utilisateur inscrit et 10 invité(s)