Location: PHPKode > projects > MyPhpMoney > myphpmoney_2.0/public_html/inc/function.inc
<?php
/**
 * $Id: function.inc 417 2007-05-08 17:55:39Z hpfn $
 *
 * Author     : courou&#64;users.sourceforge.net
 * Website    : http://allreponse.ath.cx
 *
 * Support    : http://sourceforge.net/projects/myphpmoney/
 * CVS        : http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/myphpmoney/
 */

# ------------------------------ Gestion of Error ----------------------------
// Fonction qui recupere les erreurs
// Qui les affichent ou Qui les enregistrent dans un fichier de log
// Existe depuis la version php 4.0.1
//
// Becareful don't put the &amp; for 5 arguments (no implemented here)
//
// @param $errno    = number of error
// @param $errstr   = this error
// @param $errfile  = file with error
// @param $errline  = lile with error
function ErrorHandler(&$errno,&$errstr,&$errfile,&$errline) {
  Global $_MPM; $_MPM['Serial'][] = "ErrorHandler($errno,$errfile,$errline)";

    $inconnu     = false;    ## silence Mysql warnings
    $halt_script = false;    ## halt the script

    $input = '';
    switch ($errno) {
           default:
               $input .= 'Unkown error type';
               break;
           case E_USER_NOTICE:
               $input .= 'USER_NOTICE';
               break;
           case E_NOTICE:
               $input .= 'NOTICE';
               break;
           case E_USER_WARNING:
               $input .= 'USER_WARNING';
               break;
           case E_COMPILE_WARNING:
               $input .= 'COMPILE_WARNING';
               break;
           case E_CORE_WARNING:
               $input .= 'CORE_WARNING';
               break;
           case E_WARNING:
               ## no display the error because phplib to do already
               ## Modif : 01/12/2002 courou
               if (stripos($errstr, 'Using password:') !== false) $inconnu = true; ## for phplib
               if (stripos($errfile, 'db_mysql.inc') !== false)   $inconnu = true; ## for phplib
               if (stripos($errstr, 'mysql') !== false)           $inconnu = true; ## for IIS if no good permissions (wwwroot)
               if (stripos($errstr, 'mkdir') !== false)           $inconnu = true; ## for IIS if no good permissions (wwwroot)
               if (stripos($errstr, 'fopen') !== false)           $inconnu = true; ## if perms conflict with error_log function
               if (stripos($errstr, 'error_log') !== false)       $inconnu = true; ## for phplib
               $input .= 'WARNING';
               break;
           case E_USER_ERROR:
               $input .= 'USER_ERROR';
               break;
           case E_COMPILE_ERROR:
               $input .= 'COMPILE_ERROR';
               break;
           case E_CORE_ERROR:
               $input .= 'CORE_ERROR';
               break;
           case E_ERROR:
               $input .= 'ERROR';
               $input .= "Aborting...<br />\n";
               $halt_script = true;
               break;
           case E_PARSE:
               $input .= 'PARSE';
               $input .= "Aborting...<br />\n";
               $halt_script = true;
               break;
     }

     if (!$inconnu) {
          $err  = "<div class=\"line\"></span>%s</span> $errstr <span class=\"menurouge\">line: <span class=\"menubold\">$errline</span></span>";
          $err .= " file : ".basename($errfile)." - ";
          $err .= "<span class=\"menurouge\"><span class=\"menubold\">PHP ".PHP_VERSION."</span></span>(".PHP_OS.")</div>\n";
     MPM_DisplayHandler(sprintf($err,$input));
     }

if ($halt_script) exit; // STOP SCRIPT
} ## end of ErrorHandler

// Fonction qui execute les actions
//   DEFINE  LOG = inscrire les infos de debug dans un fichier
//   DEFINE  OUT = inscrire les infos de debug dans le brouseur
//   DEFINE  VAR = inscrire les infos sur toutes les variables utiliser
//                       (dans un fichier log si erreur detecter)
//   DEFINE  SQL = inscrire les infos de debug dans la base (non implementer)
function MPM_DisplayHandler($err) {
  Global $_MPM,$debugs; $_MPM['Serial'][] = "MPM_DisplayHandler($err)";

 $_err = '';
 if (stripos(__DEBUG__,'OFF') === false || __DEBUG_CHMOD__ >= 2) {

     if (stripos(__DEBUG__,'OUT') !== false && $_MPM['NbBug'] <= 0) {
       $_err .= $_MPM['external_mess'];
     }
     $_err .= '<span class="menubleu"> '.$_MPM['date_dump'].' </span>'.$err.'<br />';

   ## if (stristr(__DEBUG__,'SQL')) echo 'Data send in the SQL database (no implemented)';
   if (stripos(__DEBUG__,'OUT') !== false) echo $_err;
   if (stripos(__DEBUG__,'LOG') !== false) MPM_TestHandler($_err,'Error');
   if (stripos(__DEBUG__,'VAR') !== false) MPM_TestHandler($debugs->Debug_Globals('',''),'Vars');

  $_MPM['NbBug']++;
  } ## end of if (!stristr(__DEBUG__,'OFF'))
} ## end of MPM_DisplayHandler

// Fonction qui cree le log
// @param $err     = l'erreur
// @param $name    = le nom du fichier
function MPM_TestHandler($err,$name) {
  Global $_MPM,$_VAR; $_MPM['Serial'][] = "MPM_TestHandler($err,$name)";

    $bolean = false;
    $_err   = '';

    $_MPM['dir_function'] =  basename($_MPM['dir_function']);
    $directory = preg_replace('/'.$_MPM['dir_function'].'(.*)/i','',__FILE__);
    $path      = $directory.''.$name.'_'.$_MPM['name'].'.log';

    if (stripos($name,'Vars') !== false && file_exists($path)) {
      ## No re - create the file Vars
    } else {
      $bolean = @error_log(strip_tags($err),3,$path);
    }

    if ($_MPM['NbBug'] <= 0 && !is_writeable($path)) {
      $_err  = $_VAR['LOG_ERROR']."<br />Can't create log file TO log <span class=\"menubold\">this error</span><br />";
      $_err .= '<span class="menurouge">Unable to write : '.$directory.' <br /></span>';
      $_err .= 'Solution : Create and chmod 777 the file '.$name.'_'.$_MPM['name'].'.log <br />';
      $_err .= '<span class="menurouge">'.$path.'</span>';
    }
    if ((!file_exists($path) || (!$bolean && $_MPM['NbBug'] <= 0)) && isset($_err) && $_err != '')
    printf ("<h2 class=\"center\">%s</h2>\n",$_err);
} ## end of MPM_TestHandler

# --------------------------- Php Function > 4.0.0 ---------------------------
if (!function_exists('array_key_exists')) {
// Recherche dans un tableau si la clé existe
// Existe depuis la version php 4.1
// @param $key   = la cle a cherche
// @param $search = le tableau ou l'on cherche
   function array_key_exists($key,$search) {
      if (in_array($key,array_keys($search))) {
          return true;
      } else {
          return false;
      }
   }
} ## end if !function_exists

if (!function_exists('array_search')) {
// Recherche dans un tableau la clé associée à une valeur
// Existe depuis la version php 4.0.5
// @param $str   = la cle a cherche
// @param $vars  = le tableau ou l'on cherche
function array_search($str, $vars) {
  Global $_MPM; $_MPM['Serial'][] = "array_search($str, $vars)";
      foreach ($vars as $key => $val) {
         if ($val == $str) { return $key; }
      }
   }
} ## end if !function_exists

if (!function_exists('array_unique')) {
// Affiche le tableau dedoublonné
// remplace la fonction php  array_unique()
// Existe depuis la version php 4.0.1
// @param $old  = Tableau des donnees à verifier
  function array_unique(&$old) {
    Global $_MPM; $_MPM['Serial'][] = "array_unique($old)";

     $New_Array = array();
     foreach($old as $key => $value) {
         if(!in_array($value, $New_Array)) $New_Array[$key] = $value;
     }
   return $this->New_Array;
  } ## end of array_unique
} ## end if !function_exists

if (!function_exists('version_compare')) {
// Comparer deux version de php
// Existe depuis la version php 4.1.0
// @param $version1      = la version installer
// @param $version2      = la version minimal
  function version_compare($version1,$version2) {
    Global $_MPM; $_MPM['Serial'][] = "version_compare($version1,$version2)";

     ## idem str_replace('.','',$version1) mais plus rapider (retire les . et rapproche)
     $version1= (int) preg_replace('/[^\d]*/', '', $version1);
     $version2= (int) preg_replace('/[^\d]*/', '', $version2);

    if ($version1 < $version2)         return -1;
    else if ($version1 === $version2)  return  0;
    else if ($version1 > $version2)    return  1;
   } ## end version_compare
} ## end if !function_exists

if (!function_exists("bcadd")) {
// la function php bcadd mais sans l'utilisation de la librairie bcmath
// function adds number 1 and number 2
// @param $zahl1     = number 1
// @param $zahl2     = number 2
  function bcadd($zahl1,$zahl2) {
    Global $_MPM; $_MPM['Serial'][] = "bcadd($zahl1,$zahl2)";

    if ($zahl1===false or $zahl2===false) {return false;}

    # detect sign
    $vorzeichen1=1;$vorzeichen2=1;
    if (substr($zahl1,0,1)=="-") {$vorzeichen1=-1;$zahl1=substr($zahl1,1);}
    if (substr($zahl1,0,1)=="+") {$vorzeichen1=1;$zahl1=substr($zahl1,1);}
    if (substr($zahl2,0,1)=="-") {$vorzeichen2=-1;$zahl2=substr($zahl2,1);}
    if (substr($zahl2,0,1)=="+") {$vorzeichen2=1;$zahl2=substr($zahl2,1);}

    if ($vorzeichen1==1 and $vorzeichen2==-1) {return bcsub("$zahl1","$zahl2");}
    if ($vorzeichen1==-1 and $vorzeichen2==-1)
      {
      if ($zahl1==0 and $zahl2==0) {return 0;}
      return "-".bcadd ("$zahl1","$zahl2");
      }
    if ($vorzeichen1==-1 and $vorzeichen2==1) {return bcsub("$zahl2","$zahl1");}

    if ($zahl1==0 and $zahl2==0) {return 0;}
    if ($zahl1==0) {return $zahl2;}
    if ($zahl2==0) {return $zahl1;}

    # delete leading zeros
    while (substr($zahl1,0,1) == "0") {$zahl1=substr($zahl1,1,strlen($zahl1)+1);}
    while (substr($zahl2,0,1) == "0") {$zahl2=substr($zahl2,1,strlen($zahl2)+1);}

    # delete positive sign
    while (substr($zahl1,0,1) == "+") {$zahl1=substr($zahl1,1,strlen($zahl1)+1);}
    while (substr($zahl2,0,1) == "+") {$zahl2=substr($zahl2,1,strlen($zahl2)+1);}

    # detect positon of decimal place
    $position1=strpos($zahl1,".");
    $position2=strpos($zahl2,".");


    # delete trailing zeros in $zahl1 (only if there is a decimal point) and delete unnecessary decimal point
    if (!$position1===false)  {
      # delete trailing zeros
      while (substr($zahl1,strlen($zahl1)-1,strlen($zahl1)) == "0") {
        $zahl1=substr($zahl1,0,strlen($zahl1)-1);
        }
      # delete decimal point if it is the last character
      if (substr($zahl1,strlen($zahl1)-1,strlen($zahl1)) == ".") {
        $zahl1=substr($zahl1,0,strlen($zahl1)-1);
        $position1=false; # set position of decimal point false (= there is no point anymore)
        }
      }

    # delete trailing zeros in $zahl2 (only if there is a decimal point) and delete unnecessary decimal point
    if (!$position2===false) {
      # delete trailing zeros
      while (substr($zahl2,strlen($zahl2)-1,strlen($zahl2)) == "0") {
        $zahl2=substr($zahl2,0,strlen($zahl2)-1);
        }
      # delete decimal point if it is the last character
      if (substr($zahl2,strlen($zahl2)-1,strlen($zahl2)) == ".") {
        $zahl2=substr($zahl2,0,strlen($zahl2)-1);
        $position2=false; # set position of decimal point false (= there is no point anymore)
        }
      }

    # number of digits after the point
    $pos1 = ($position1===false) ? false : strlen($zahl1)-($position1+1);
    $pos2 = ($position2===false) ? false : strlen($zahl2)-($position2+1);

    # numeric characters BEFORE point
    $teil_vor_komma1 = ($pos1===false) ? $zahl1 : substr($zahl1,0,strlen($zahl1)-$pos1-1);
    $teil_vor_komma2 = ($pos2===false) ? $zahl2 : substr($zahl2,0,strlen($zahl2)-$pos2-1);

    # numeric characters AFTER point
    $teil_hinter_komma1 = ($pos1===false) ? "" : substr($zahl1,-$pos1);
    $teil_hinter_komma2 = ($pos2===false) ? "" : substr($zahl2,-$pos2);

    # add trailing zeros
    if (substr_count($zahl1,".")==1) {
      $pos=strpos($zahl1,".");
      if (strlen($teil_hinter_komma1)<strlen($teil_hinter_komma2)) {
        $zahl1=$zahl1.str_repeat("0",strlen($teil_hinter_komma2)-strlen($teil_hinter_komma1));
        }
      }
    else {
      # there is no decimal point: add one
      if (strlen($teil_hinter_komma1)<strlen($teil_hinter_komma2)) {
        $zahl1=$zahl1.".".str_repeat("0",strlen($teil_hinter_komma2)-strlen($teil_hinter_komma1));
        }
      }
    if (substr_count($zahl2,".")==1) {
      $pos=strpos($zahl2,".");
      if (strlen($teil_hinter_komma2)<strlen($teil_hinter_komma1)) {
        $zahl2=$zahl2.str_repeat("0",strlen($teil_hinter_komma1)-strlen($teil_hinter_komma2));
        }
      }
    else {
      # there is no decimal point: add one
      if (strlen($teil_hinter_komma2)<strlen($teil_hinter_komma1)) {
        $zahl2=$zahl2.".".str_repeat("0",strlen($teil_hinter_komma1)-strlen($teil_hinter_komma2));
        }
      }

    # add leading zeros
    if (strlen($teil_vor_komma1)<strlen($teil_vor_komma2)) {$zahl1=str_repeat("0",strlen($teil_vor_komma2)-strlen($teil_vor_komma1)).$zahl1;}
    if (strlen($teil_vor_komma1)>strlen($teil_vor_komma2)) {$zahl2=str_repeat("0",strlen($teil_vor_komma1)-strlen($teil_vor_komma2)).$zahl2;}

    # detect positon of decimal place of future result
    $pos = (($pos=strpos($zahl1,"."))===false) ? 0 : strlen($zahl1)-($pos+1);

    # delete point
    $zahl1=str_replace(".","",$zahl1);
    $zahl2=str_replace(".","",$zahl2);

    $ueberlauf =0;
    $fg = '';
    for ($i=strlen($zahl1)-1;$i>=0;$i--){
      $a=substr($zahl1,$i,1);
      $b=substr($zahl2,$i,1)+$ueberlauf;
      $er=$a+$b;
      if ($er>9 and $i!=0) {$ueberlauf=substr($er,0,strlen($er)-1);$er=substr($er,-1);} else {$ueberlauf=0;}
      $fg=$er.$fg;
      }

    if ($fg==0) {return 0;}

    # set decimal point
    if ($pos) {
      #echo "fg: $fg<br />",
      $rechts=substr($fg,-$pos);

      $links=substr($fg,0,strlen($fg)-$pos); #echo "pos: $pos ** l: $links ** r: $rechts<hr>";

      $fg="${links}.${rechts}";
      $position=strpos($zahl1,".");
      # delete trailing zeros
      while (substr($fg,strlen($fg)-1,strlen($fg)) == "0") {$fg=substr($fg,0,strlen($fg)-1);}
      # delete trailing decimal point if it is the last sign
      if (substr($fg,strlen($fg)-1,strlen($fg)) == ".") {$fg=substr($fg,0,strlen($fg)-1);}
      }

    # delete leading zeros
    $vorzeichen = '';
    while (substr($fg,0,1) == "0") {
      $fg=substr($fg,1,strlen($fg)+1);
      if ($fg=="0") {return 0;}
      }
    if ($fg=="0") {return 0;}
    return $vorzeichen.$fg;
    } ## end bcadd()
} ## end of !function_exists

if (!function_exists("bcsub")) {
// la function php bcsub mais sans l'utilisation de la librairie bcmath
// function subtracts number 1 and number 2
// @param $zahl1     = number 1
// @param $zahl2     = number 2
  function bcsub($zahl1,$zahl2) {
    Global $_MPM; $_MPM['Serial'][] = "bcsub($zahl1,$zahl2)";

    if ($zahl1===false or $zahl2===false) {return false;}

    # detect sign
    $vorzeichen1=1;$vorzeichen2=1;
    if (substr($zahl1,0,1)=="-") {$vorzeichen1=-1;$zahl1=substr($zahl1,1);}
    if (substr($zahl1,0,1)=="+") {$vorzeichen1=1;$zahl1=substr($zahl1,1);}
    if (substr($zahl2,0,1)=="-") {$vorzeichen2=-1;$zahl2=substr($zahl2,1);}
    if (substr($zahl2,0,1)=="+") {$vorzeichen2=1;$zahl2=substr($zahl2,1);}

    if ($vorzeichen1==-1 and $vorzeichen2==1) {return "-".bcadd("$zahl1","$zahl2");}
    if ($vorzeichen1==1 and $vorzeichen2==-1) {return bcadd("$zahl1","$zahl2");}
    if ($vorzeichen1==-1 and $vorzeichen2==-1) {return bcadd("-$zahl1","$zahl2");}

    if ($zahl1==0 and $zahl2==0) {return 0;}
    if ($zahl1==0) {return "-$zahl2";}
    if ($zahl2==0) {return $zahl1;}

    # delete leading zeros
    while (substr($zahl1,0,1) == "0") {$zahl1=substr($zahl1,1,strlen($zahl1)+1);}
    while (substr($zahl2,0,1) == "0") {$zahl2=substr($zahl2,1,strlen($zahl2)+1);}

    # detect positon of decimal place
    $position1=strpos($zahl1,".");
    $position2=strpos($zahl2,".");

    # delete trailing zeros in $zahl1 (only if there is a decimal point) and delete unnecessary decimal point
    if (!$position1===false) {
      # delete trailing zeros
      while (substr($zahl1,strlen($zahl1)-1,strlen($zahl1)) == "0") {
        $zahl1=substr($zahl1,0,strlen($zahl1)-1);
        }
      # delete decimal point if it is the last character
      if (substr($zahl1,strlen($zahl1)-1,strlen($zahl1)) == ".") {
        $zahl1=substr($zahl1,0,strlen($zahl1)-1);
        $position1=false; # set position of decimal point false (= there is no point anymore)
        }
      }

    # delete trailing zeros in $zahl2 (only if there is a decimal point) and delete unnecessary decimal point
    if (!$position2===false) {
      # delete trailing zeros
      while (substr($zahl2,strlen($zahl2)-1,strlen($zahl2)) == "0") {
        $zahl2=substr($zahl2,0,strlen($zahl2)-1);
        }
      # delete decimal point if it is the last character
      if (substr($zahl2,strlen($zahl2)-1,strlen($zahl2)) == ".") {
        $zahl2=substr($zahl2,0,strlen($zahl2)-1);
        $position2=false; # set position of decimal point false (= there is no point anymore)
        }
      }

    # number of digits after the point
    $pos1 = ($position1===false) ? false : strlen($zahl1)-($position1+1);
    $pos2 = ($position2===false) ? false : strlen($zahl2)-($position2+1);

    # numeric characters BEFORE point
    $teil_vor_komma1 = ($pos1===false) ? $zahl1 : substr($zahl1,0,strlen($zahl1)-$pos1-1);
    $teil_vor_komma2 = ($pos2===false) ? $zahl2 : substr($zahl2,0,strlen($zahl2)-$pos2-1);

    # numeric characters AFTER point
    $teil_hinter_komma1 = ($pos1===false) ? "" : substr($zahl1,-$pos1);
    $teil_hinter_komma2 = ($pos2===false) ? "" : substr($zahl2,-$pos2);

    # add trailing zeros
    if (substr_count($zahl1,".")==1) {
      $pos=strpos($zahl1,".");
      if (strlen($teil_hinter_komma1)<strlen($teil_hinter_komma2)) {$zahl1=$zahl1.str_repeat("0",strlen($teil_hinter_komma2)-strlen($teil_hinter_komma1));}
      }
    else {
      # there is no decimal point: add one
      if (strlen($teil_hinter_komma1)<strlen($teil_hinter_komma2)) {$zahl1=$zahl1.".".str_repeat("0",strlen($teil_hinter_komma2)-strlen($teil_hinter_komma1));}
      }
    if (substr_count($zahl2,".")==1) {
      $pos=strpos($zahl2,".");
      if (strlen($teil_hinter_komma2)<strlen($teil_hinter_komma1)) {$zahl2=$zahl2.str_repeat("0",strlen($teil_hinter_komma1)-strlen($teil_hinter_komma2));}
      }
    else {
      # there is no decimal point: add one
      if (strlen($teil_hinter_komma2)<strlen($teil_hinter_komma1)) {$zahl2=$zahl2.".".str_repeat("0",strlen($teil_hinter_komma1)-strlen($teil_hinter_komma2));}
      }

    # add leading zeros
    if (strlen($teil_vor_komma1)<strlen($teil_vor_komma2)) {$zahl1=str_repeat("0",strlen($teil_vor_komma2)-strlen($teil_vor_komma1)).$zahl1;}
    if (strlen($teil_vor_komma1)>strlen($teil_vor_komma2)) {$zahl2=str_repeat("0",strlen($teil_vor_komma1)-strlen($teil_vor_komma2)).$zahl2;}

    # swap zahl1 and zahl2, if zahl2 is bigger than zahl1
    if ($teil_vor_komma1<$teil_vor_komma2) {$help=$zahl2;$zahl2=$zahl1;$zahl1=$help;$vorzeichen="-";}
    if (($teil_vor_komma1==$teil_vor_komma2) and ($teil_hinter_komma1<$teil_hinter_komma2)) {$help=$zahl2;$zahl2=$zahl1;$zahl1=$help;$vorzeichen="-";}

    # detect positon of decimal place of future result
    $pos = (($pos=strpos($zahl1,"."))===false) ? 0 : strlen($zahl1)-($pos+1);

    # delete point
    $zahl1=str_replace(".","",$zahl1);
    $zahl2=str_replace(".","",$zahl2);

    $ueberlauf=0;
    $fg = '';
    for ($i=strlen($zahl1)-1;$i>=0;$i--) {
      $a=substr($zahl1,$i,1);
      $b=substr($zahl2,$i,1)+$ueberlauf;
      if ($b>$a) {$a="1".$a;$ueberlauf=1;} else {$ueberlauf=0;}
      $er=$a-$b;
      $fg=$er.$fg;
      }

    if ($fg==0) {return 0;}

    # set decimal point
    if ($pos) {
      $rechts=substr($fg,-$pos);
      $links=substr($fg,0,strlen($fg)-$pos);
      $fg="${links}.${rechts}";
      $position=strpos($zahl1,".");
      # delete trailing zeros
      while (substr($fg,strlen($fg)-1,strlen($fg)) == "0") {$fg=substr($fg,0,strlen($fg)-1);}
      # delete trailing decimal point if it is the last sign
      if (substr($fg,strlen($fg)-1,strlen($fg)) == ".") {$fg=substr($fg,0,strlen($fg)-1);}
      }

    # delete leading zeros
    $vorzeichen = '';
    while (substr($fg,0,1) == "0") {
      $fg=substr($fg,1,strlen($fg)+1);
      if ($fg == '0') return 0;
      }
     if ($fg == '0') { exit; return 0; }

    return $vorzeichen.$fg;
    } ## end bcsub()
} ## end of function_exists

# ------------------------------- Function XML -------------------------------
// Recupere le taux de change d'un pays
// ou retourne le tableau des taux de change
// @param $file       = le fichier a scanner
// @param $id_country = valeur du pays
// @param $choice     = choice de la fonction
function XML_GetRate($file) {
   Global $_MPM; $_MPM['Serial'][] = "XML_GetRate($file)";

    $data = join('', file($file));
    $parser = xml_parser_create();

    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
    xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE,   1);
    xml_parse_into_struct($parser, $data, $XmlVal, $index);
    xml_parser_free($parser);

    ## EMPTY VALUE FOR 0
    $tab = array(0=>''); $a = array(0=>''); $b = array(0=>''); $c = array(0=>'');

    for ($i= 0; $i < count($XmlVal); $i++) {
         if ($XmlVal[$i]['type'] == 'complete' && $XmlVal[$i]['level'] == 3) {
                if ($XmlVal[$i]['tag'] == 'iso')  $a[] = $XmlVal[$i]['value'];
                if ($XmlVal[$i]['tag'] == 'id')   $b[] = $XmlVal[$i]['value'];
                if ($XmlVal[$i]['tag'] == 'taux') $c[] = $XmlVal[$i]['value'];
         }
    }
    $tab = array($a,$b,$c);
return $tab;
} ## end of XML_GetRate

// Fonction qui Retourne un tableau
//  trier de tous les pays
function XML_TabRate() {
  Global $_MPM,$_VAR; $_MPM['Serial'][] = 'XML_TabRate';
      $rate_array = array();
      $rate_array = $_MPM['LocalRate'][2];
      $rate_array = array_slice($rate_array,1,sizeof($rate_array));

      for ($ld=1; $ld <= sizeof($_VAR['THIS_COUNTRY']); $ld++) {
                        $id_array[$ld]     = $ld;
                        $county_array[$ld] = $_VAR['THIS_COUNTRY'][$ld]['COUNTRY'];
                        $money_array[$ld]  = $_VAR['THIS_COUNTRY'][$ld]['MONEY'];
      }
      array_multisort($county_array,$id_array,$rate_array,$money_array,SORT_ASC);
      for ($d=0; $d < sizeof($county_array); $d++) {
            $TAB[] = "$id_array[$d]|$county_array[$d]|$rate_array[$d]|$money_array[$d]";
      }

    if (is_array($TAB)) {
          return $TAB;
    } else {
          XHTML_DisplayJs(XML_CheckUpdateXmlFiles());
    return XML_TabRate();
    }
} ## end of XML_TabRate

// verifie deux fichiers xml et met le fichier
// local a jour en prenant le fichier distant comme source
// si il rencontre une erreur il met a jour le fichier
// avec le fichier original
function XML_CheckUpdateXmlFiles() {
 Global $_MPM,$tools,$tpl,$_VAR; $_MPM['Serial'][] = 'XML_CheckUpdateXmlFiles';

   $file1 = $_MPM['export_local'];    ## le fichier local
   $file2 = $_MPM['external_rate'];   ## le fichier distant
   $file3 = $_MPM['export_original']; ## original file for the restaure

   $nb_count_file_local = ''; $nb_count_file_distant = '';

   if (isset($file1) && isset($file2) && isset($file3)) {
        ## verif the local file
        if (!file_exists($file1)) $b = 1;

        ## The first file ( local file )
        else {
           $_MPM['LocalRate']['iso']     = $_MPM['LocalRate'][0];
           $_MPM['LocalRate']['id']      = $_MPM['LocalRate'][1];
           $_MPM['LocalRate']['taux']    = $_MPM['LocalRate'][2];

           $nb_count_file_local = sizeof($_MPM['LocalRate']['iso']) - 1;
        }
        ## verif the connection
        if (!$tools->verif_connect()) {
            if (defined('PHP_HOSTCONNECT') && PHP_HOSTCONNECT == 1) $b = 4;
            else $b = 3;
        }
        ## verif the remote file
        else if (!MPM_fopen($file2)) $b = 2;

        ## The Seconde file (distante file)
        else {
           $RemoteRate            = array();
           $RemoteRate            = XML_GetRate($_MPM['external_rate']);
           $RemoteRate['iso']     = $RemoteRate[0];
           $RemoteRate['id']      = $RemoteRate[1];
           $RemoteRate['taux']    = $RemoteRate[2];
           $nb_count_file_distant = sizeof($RemoteRate['iso']) - 1;
        }

      ## if ok Verif the data now
      if (!isset($b) || $b != 1 || $b != 2 || $b != 3) {
        if ($nb_count_file_local == $nb_count_file_distant) {

                $err = 0;
                for ($i= 1; $i <= $nb_count_file_distant; $i++) {

                  $iso_file_local    = isset($_MPM['LocalRate']['iso'][$i]) ? $_MPM['LocalRate']['iso'][$i] : null;
                  $iso_file_distant  = isset($RemoteRate['iso'][$i]) ? $RemoteRate['iso'][$i] : null;
                  $id_file_local     = isset($_MPM['LocalRate']['id'][$i]) ? $_MPM['LocalRate']['id'][$i] : null;
                  $id_file_distant   = isset($RemoteRate['id'][$i]) ? $RemoteRate['id'][$i] : null;
                  $taux_file_local   = isset($_MPM['LocalRate']['taux'][$i]) ? $_MPM['LocalRate']['taux'][$i] : null;
                  $taux_file_distant = isset($RemoteRate['taux'][$i]) ? $RemoteRate['taux'][$i] : null;

                    if ($iso_file_distant == $iso_file_local && $id_file_distant == $id_file_local
                         && $taux_file_distant == $taux_file_local) { ## nothing to do $err = 0;
                    } else {
                    $err++; ## changement detected
                    }

                } ## end of for ($i= 1; $i < $nb_count_file_distant; $i++)
          if ($err >= 1)  $a = 'false';
          } else {
          $a = 'false'; ## no idem file
         } ## end of if ($nb_count_file_local == $nb_count_file_distant)
       } ## end of if ($b != 1 || $b != 2)
    } ## end of if (isset($file1) && isset($file2))

 /**
  * UPDATE THE XML
  */
        ## THE RAPPORT
        $r = '';

        ## LOCAL FILE PROBLEME (EMPTY ??)
        if (($_MPM['LocalRate']['iso'][1] == '') || (sizeof($_VAR['THIS_COUNTRY']) != $nb_count_file_local)) {
          ## PROBLEM EMPTY FILE 3 (LOCAL)
          if (!copy($file3, $file1) )  $r .= sprintf($_VAR['JS_PARSER_XML_4'],$file3);
          ## OK COPY THE FILE
          else $r .= $_VAR['JS_PARSER_XML_8'];
        }
        else if ((isset($a) && $a == 'false') && (!isset($b))) {

           XHTML_SetFile('conver.xtpl','',0);
           $tpl->set_block('FILE_conver.xtpl', 'BOUCLE CONVERT XML', 'BLOCK_conver.xtpl');
           for ($m= 1; $m <= $nb_count_file_distant; $m++) {

           $tpl->set_var(array(
                       'CONVERT_ISO'           => $RemoteRate['iso'][$m],
                       'CONVERT_ID'            => $RemoteRate['id'][$m],
                       'CONVERT_TAUX'          => $RemoteRate['taux'][$m]
           ));
           $tpl->parse('BLOCK_conver.xtpl','BOUCLE CONVERT XML',true);
           }
            ## WRITE AND CREATE THE FILE
            if (file_exists($file1) && is_writable($file1)) {
              $scann = fopen($file1, 'w');
              $writing  = fwrite($scann,XHTML_SetFile('conver.xtpl','',3));
              $r .=  $_VAR['JS_PARSER_XML_3'];
              fclose($scann);
            }
            ## PROBLEM FOR WRITE THE DATA
            else {
              $r .= $_VAR['JS_PARSER_XML_2'];
            }
        }
        else if (isset($b)) {
         $r ='';
         ## EMPTY FILE 1 (LOCAL)
         if ($b == 1) $r .= sprintf($_VAR['JS_PARSER_XML_4'],$file1);
         ## EMPTY FILE 2 (REMOTE)
         if ($b == 2) $r .= sprintf($_VAR['JS_PARSER_XML_5'],$file2);
         ## NO CONNECTING DETECTED
         if ($b == 3) $r .= $_VAR['JS_PARSER_XML_6'];
         ## CONNECT REFUSED CODE 111
         if ($b == 4) $r .= sprintf($_VAR['JS_PHP_HOSTCONNECT'],$_MPM['name'],$_VAR['LANG_BOOK_9']);
        }
        ## GOOD NOTHING TO DO
        else {
        $r .=  $_VAR['JS_PARSER_XML_7'];
        }
   return $r;
unset($a,$b);
} ## end of XML_CheckUpdateXmlFiles

# ----------------------------- Internal Function ----------------------------
// fonction qui permet de verifier si la version de php est
// une version standart ou non
// et renvoie la chaine moins la portion
// @param $str      = la version de php a verifier
function MPM_version_test($str) {
  Global $_MPM; $_MPM['Serial'][] = "MPM_version_test($str)";

     $special_version = array('-dev', 'a1', 'b1', 'RC1', 'pl1');
     foreach ($special_version as $key => $val) {
        if (stripos($str,$val) !== false) $a = str_replace($val,'',$str);
     }
  return !isset($a) ? $str : $a;
} ## end MPM_version_test

// Verifie l'existance du repertoire
// Non utilisation de is_dir car genere une notice error
// afin de plus avoir de notice
// @param $dir  = the repertory
// @param $file = the file verified
function MPM_is_dir($dir,$file) {
  Global $_MPM; $_MPM['Serial'][] = "MPM_is_dir($dir,$file)";
   if (is_readable($dir)) {
         $Exist = false;
         $VerifDir = opendir($dir);
         while ($tmp = readdir($VerifDir)) {
             if ($tmp == $file) {
               $Exist = true;
             }
        }
      closedir($VerifDir);
      return $Exist;
   }
} ## end of MPM_is_dir

// Verifie l'existance du fichier
// evite le fopen et les warning ou autre notice
// @param $url  = le fichier distant a verifier
function MPM_fopen($url) {
  Global $_MPM; $_MPM['Serial'][] = "MPM_fopen($url)";

          $url = str_replace('http://', '', $url);
          list($domain, $file) = explode('/', $url, 2);

          $fid=fsockopen($domain,80,$errno,$errstr,30);
          if ($fid) {
            fputs($fid,"GET /$file HTTP/1.0\r\nHost: $domain\r\n\r\n");
            $gets = fgets($fid, 1024);
            fclose($fid);
          }
if (isset($gets) && strstr($gets,'HTTP/1.1 200 OK')) return true; else return false;
} ## end of MPM_fopen

// Lire un fichier et le tabuler
// @param $url = the url for open
// @param $codex = default value for read the url (1 for FAQ read xhtml)
function MPM_ReadUrl($url,$codex=0) {
  Global $_MPM; $_MPM['Serial'][] = "MPM_ReadUrl($url,$codex)";

       if (file_exists($url)) {
          $output = '';
          $ary = file($url);
          $size = count($ary);
          $string = implode('',$ary);
            for ($i = 0 ; $i < $size ; $i++) {
              $output .= $codex == 0 ? htmlspecialchars($ary[$i]) : $ary[$i];
            }
            ## nl2br because php 4.05 for xhtml compliency
            if ($codex == 0) {
               $prep = '<p>'.str_replace("\n",'<br />',$output).'</p><br />';
               echo str_replace('&amp;#64;','&#64;',$prep)."\n";
            }
            if ($codex == 1) echo $output;
       } else {
            $_MPM['NbBug'] = 1; // no display the form bug
            $err = '<span class="menurouge">No exist ? '.$url.'</span>';
            MPM_DisplayHandler($err);
       }
} ## end of MPM_ReadUrl

// Liste les fichiers Changelog
// @param $path_file = le repertoire a lister
function MPM_BrowseRep($path_file) {
 Global $_MPM; $_MPM['Serial'][] = "MPM_BrowseRep($path_file)";

       if (file_exists($path_file)) {
            $dir=opendir($path_file);
            while ($file = readdir($dir)) {
              if ($file != '.' && $file!= '..') {
                ## No repertory
                if (!is_dir($path_file.'/'.$file)) {
                    echo '<ul><li><a class="menu" href="'.__NIV__.'/'.$_MPM['http'][6].'?p=l12&amp;c='.$path_file.''.$file.'">'.$file.'</a></li></ul>';
                }
              }
            }
            closedir($dir);
       } else {
            $_MPM['NbBug'] = 1; // no display the form bug
            $err = '<span class="menurouge">No exist ? '.$path_file.'</span>';
            MPM_DisplayHandler($err);
       }
} ## end of MPM_BrowseRep

// Detruit le repertoire et les fichiers de sauvegarde
// @param $direction = chemin à detruire
function MPM_DelDump($repertory) {
  Global $sess,$sess_pid,$_MPM; $_MPM['Serial'][] = "MPM_DelDump($repertory)";

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid  : '';
     if ($sess_pid != '') {
         ## Ajout de is_writable afin d'eviter le warning
         $exist = MPM_is_dir($_MPM['dir_dump'],md5($sess_pid));
         if ($exist && is_writable($repertory)) {
           $F = array();
           $R = opendir($repertory);
           while($t = readdir($R)) $F[] = $t; closedir($R);
           sort($F); next($F); next($F);  reset($F);
            while($t = each($F)) {
                if ($t[1] != '.' && $t[1] != '..' && stripos($t[1],'.sql') !== false) {
                   if (file_exists($repertory.'/'.$t[1])) {
                     unlink($repertory.'/'.$t[1]);
                   } ## end file_exists
                }
            } ## end while
            if ($exist && !file_exists($repertory.'/'.md5($sess_pid).'.php')) {
               rmdir($repertory);
            }
        } ## end is_writable
     } ## end $sess_pid
} ## end of MPM_DelDump

// Ouvre et lit un fichier
// attend le chemin du fichier en parametre
// @param $files = chemin des fichier a lire
function MPM_ReadFile($files) {
  Global $_MPM,$_VAR; $_MPM['Serial'][] = "MPM_ReadFile($files)";

   if ($files == '') {
        echo XHTML_DisplayJs($_VAR['MESSAGE_HT_ACCESS'][10]);
   } else {
   $Zlist = '';
       if (file_exists($files)) {
         $fp = fopen($files, 'r');
       } else {
         echo XHTML_DisplayJs($_VAR['MESSAGE_HT_ACCESS'][11]);
       exit;
       }
        while (!feof($fp)) {
           $ligne = fgets($fp,4096);
           $liste = explode('\n',$ligne);
           $Zlist .= $liste[0];
          }
     fclose($fp);
   return $Zlist;
   } ## end of else
} ## end of MPM_ReadFile

// Création d'une copie de sauvegarde
// avec création du répertoire
function MPM_DumpDays() {
Global $sess,$sess_pid,$_MPM; $_MPM['Serial'][] = 'MPM_DumpDays';

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '') {
         ## Ajout de is_writable afin de verifier avant le mkdir
         ## evite le warning sur mkdir
         $exist = MPM_is_dir($_MPM['dir_dump'],md5($sess_pid));

         if (!$exist && is_writable($_MPM['dir_dump'])) {
              mkdir($_MPM['dir_dump'].''.md5($sess_pid), 0755);
         $exist = true;
         }

         if ($exist) {
            $fichier = $_MPM['dir_dump'].''.md5($sess_pid).'/'.date('Y-m-d',time()).'_'.md5($sess_pid).'.sql';
              if (!($fc = fopen($fichier, 'w'))) {
                   echo XHTML_ChmodError();
              } else {
                 $w  = fwrite($fc, SQL_DumpDays());
                 fclose($fc);
              }
         } else {
                 echo XHTML_ChmodError();
         }
     }
} ## end of MPM_DumpDays

// Suppression des sauvegardes de plus de XX Jours
// @param $jour_arriere = nombre de jour
// @param $jour_act = Jour d'aujourd'hui (actuel)
function MPM_DelDumpDays($jour_arriere,$jour_act) {
Global $sess,$sess_pid,$_MPM,$_VAR; $_MPM['Serial'][] = "MPM_DelDumpDays($jour_arriere,$jour_act)";

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '') {
          $exist = MPM_is_dir($_MPM['dir_dump'],md5($sess_pid));
          if ($exist) {
                $Limit = date('Y-m-d',mktime(0,0,0,date('m'),($jour_act-$jour_arriere),date('Y')));
                $THE_FICHIER = array();
                $THE_REPERTOIRE = opendir($_MPM['dir_dump'].''.md5($sess_pid));
                while($THE_TEMP = readdir($THE_REPERTOIRE)) $THE_FICHIER[] = $THE_TEMP;
                closedir($THE_REPERTOIRE);

                rsort($THE_FICHIER); next($THE_FICHIER); next($THE_FICHIER); reset($THE_FICHIER);
                while($THE_TEMP = each($THE_FICHIER))

              ## On choisit uniquement les fichiers .sql
              if (stripos($THE_TEMP[1],'_'.md5($sess_pid).'.sql') !== false) {

                  $Recherche_Final = '';
                  $Recherche_Final = str_replace('_'.md5($sess_pid).'.sql','',$THE_TEMP[1]);

                 if ($Limit >= $Recherche_Final) {
                    if (file_exists($_MPM['dir_dump'].''.md5($sess_pid).'/'.$THE_TEMP[1])) {
                        unlink($_MPM['dir_dump'].''.md5($sess_pid).'/'.$THE_TEMP[1]);
                    }
                 }
              }
           } ## end of if ($exist)
     }
} ## end of MPM_DelDumpDays

// remplace une portion de chaine et
// la remplacer par le mois
// @param $x = le texte dans lequel on va rechercher
function MPM_ReplacePatterns($x) {
  Global $_MPM,$_VAR; $_MPM['Serial'][] = "MPM_ReplacePatterns($x)";

     $patterns = "/{(.*)}/";
     preg_match ($patterns,$x,$word);
     if (isset($word[1])) {
     $replace = $_VAR['THIS_MONTH'][$word[1] - 1];
     $x = preg_replace ($patterns,$replace,$x);
     }
 return $x;
} ## end of MPM_ReplacePatterns

// permet de rechercher l'uri d'installation
// du programme afin de le rendre dynamique
function MPM_SearchUri() {
  Global $_MPM; $_MPM['Serial'][] = 'MPM_SearchUri';
   return (isset($GLOBALS['_SERVER']['HTTPS']) && $GLOBALS['_SERVER']['HTTPS'] == "on"
             ? 'https' : 'http').
             '://' .$GLOBALS['_SERVER']['HTTP_HOST'].
          (stripos($GLOBALS['_SERVER']['REQUEST_URI'],'/'.$_MPM['file_phpdoc'].'?') !== false
             ? $GLOBALS['_SERVER']['REQUEST_URI']
             : substr($GLOBALS['_SERVER']['REQUEST_URI'],0,strrpos($GLOBALS['_SERVER']['REQUEST_URI'], '/')+1)
          );
} ## end of MPM_SearchUri

// Format une date complete
// @param $this_date = la date a chercher
function MPM_FormatDates($this_date) {
 Global $_MPM,$_VAR; $_MPM['Serial'][] = "MPM_FormatDates($this_date)";
   $split = explode('-',$this_date);
 return $_VAR['THIS_DAYS'][$split[0]]." $split[1] ".$_VAR['THIS_MONTH'][$split[2] - 1]." $split[3]";
} ## end of MPM_FormatDates

// Search the js boby element
// @param $scriptname = page courante
function MPM_JsBody($scriptname) {
 Global $sess,$sess_pid,$_MPM,$_VAR; $_MPM['Serial'][] = "MPM_JsBody($scriptname)";

   if (__SHUFFE_MOUV__ || __HELPER_MOUV__ || __HELPER_MENU__) $layers = 1; else $layers = 0;
   if (stripos($scriptname, basename($_MPM['dir_doc'])) !== false || stripos($scriptname,$_MPM['file_account']) !== false) $forbid = 1; else $forbid = 0;

   $body = '';
   $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
   if (stripos($scriptname,$_MPM['file_calculate']) !== false) {
      $body = $_MPM['body_FOCUS'];
   } else if ($sess_pid != '' && isset($GLOBALS['_GET']['opt']) && ($GLOBALS['_GET']['opt'] == $_VAR['AMORTISSEMENT']) && (stripos($scriptname,$_MPM['file_listing']) !== false)) {
      $body = $_MPM['body_DOUBLE'];
   } else if ($sess_pid != '' && (!isset($GLOBALS['_GET']['opt']) || isset($GLOBALS['_POST']['opt'])) && (stripos($scriptname,$_MPM['http'][4]) !== false) && $layers == 1) {
      $body = sprintf($_MPM['body_SIMPLE'],$_MPM['body_js']);
   } else if ($sess_pid != '' && (!isset($GLOBALS['_GET']['opt']) || isset($GLOBALS['_POST']['opt'])) && (stripos($scriptname,$_MPM['http'][4]) !== false) && $layers == 0) {
      $body = sprintf($_MPM['body_SIMPLE'],$_MPM['body_NOTHING']);
   } else if ($sess_pid != '' && (stripos($scriptname,$_MPM['file_account']) !==false) && (isset($GLOBALS['_POST']['MODIF_ACCOUNT'])) && (isset($GLOBALS['_POST']['THIS_SCROLLING']) && $GLOBALS['_POST']['THIS_SCROLLING'] == 'YES')) {
      $body = $_MPM['body_POPULATE_B'];
   } else if ($sess_pid != '' && (stripos($scriptname,$_MPM['file_account']) !== false) && (isset($GLOBALS['_POST']['MODIF_ACCOUNT'])) && (isset($GLOBALS['_POST']['THAT_SCROLLING']) && $GLOBALS['_POST']['THAT_SCROLLING'] == 'YES')) {
      $body = $_MPM['body_POPULATE_T'];
   } else if ($sess_pid != '' && (isset($GLOBALS['_POST']['THAT_SCROLLING'])) && ($GLOBALS['_POST']['THAT_SCROLLING'] == 'YES')) {
      $body = sprintf($_MPM['body_SCROLLING_T'],$_MPM['body_NOTHING']);
   } else if ($sess_pid != '' && (isset($GLOBALS['_POST']['THIS_SCROLLING'])) && ($GLOBALS['_POST']['THIS_SCROLLING'] == 'YES') && $forbid == 1) {
      $body = sprintf($_MPM['body_SCROLLING_B'],$_MPM['body_NOTHING']);
   } else if ($sess_pid != '' && (isset($GLOBALS['_POST']['THIS_SCROLLING'])) && ($GLOBALS['_POST']['THIS_SCROLLING'] == 'YES') && $forbid == 0) {
      $body = sprintf($_MPM['body_SCROLLING_B'],$_MPM['body_js']);
   } else if ($sess_pid != '' && $forbid == 1) {
      $body = $_MPM['body_NOTHING'];
   } else if ($layers == 1) {
      $body = sprintf($_MPM['body_LAYER'],$_MPM['body_js']);
   } else {
      $body = $_MPM['body_NOTHING'];
   }
 return $body;
 } ## end of MPM_JsBody

// inclus le fichier dynamique.php (dhtml)
function MPM_DynamiqueJs() {
  Global $_MPM,$_VAR,$sess,$sess_user,$sess_pid;$_MPM['Serial'][] = 'MPM_DynamiqueJs';
    Global $tpl,$tools,$db,$other_db,$valid_db;
     Global $OPTION_CONFIG,$OPTION_SAUV_AUTO,$OPTION_NEW_APPLI;
require_once $_MPM['dir_style'].''.$_MPM['file_stylphp'];
} ## end of MPM_DynamiqueJs

// Cherche quel template doit etre appeler est inclue
// @param $gb  = for good_book only
// @param $t1  = the number of the template one
// @param $t2  = he number of the template two
function MPM_IncludeTemp($gb,$t1,$t2) {
  Global $_MPM; $_MPM['Serial'][] = "MPM_IncludeTemp($gb,$t1,$t2)";
    $Bk = ''; $Sz = '';
    if (__DISPLAY_EURO__ == 0 || __DISPLAY_EURO__ == 2) {
      $Bk = $t1; $Sz = 38;                            ## look css Contenu38
    } else if (__DISPLAY_EURO__) {
      $Bk = $t2; $Sz = 31;                            ## look css Contenu31
    }
return (isset($gb) && $gb == 1) ? $Bk.'|'.$Sz : $Bk;
} ## end of MPM_IncludeTemp

// Boucle pour les 31 jours
function MPM_listdays() {
  Global $_MPM; $_MPM['Serial'][] = 'MPM_listdays';
   $a = array();
   for ($i=1; $i<=31; $i++){
      ## Put Zero
      $a[] .= preg_replace('/^([1-9]){1}$/', '0\1', $i);
   }
return $a;
} ##  end of MPM_listdays
Return current item: MyPhpMoney