Location: PHPKode > projects > MyPhpMoney > myphpmoney_2.0/public_html/inc/sql.inc
<?php
/**
 * $Id: sql.inc 423 2007-05-27 12:01:28Z 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/
 */

# --------------------------------*- $_MPM['table'][0] -*-------------------------------

// Insert the part
// @param $the_id   = value of the part
// @param $cat      = name of categorie
function SQL_InsertCat($the_id,$cat) {
  Global $sess,$sess_pid,$_MPM,$db; $_MPM['Serial'][] = "SQL_InsertCat($the_id,$cat)";

    $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
    if ($sess_pid != '' && $the_id != '' && $cat != '') {
       $db->query (
            "INSERT INTO ".$_MPM['table'][0]."
            (
                 CATID,
                 USERID,
                 CAT
            )
       VALUES ('$the_id','$sess_pid','$cat')"
       );
     }
} ## end of SQL_InsertCat

// Recherche l'id de la categorie
// @param $cat     = le nom de la categorie
function SQL_IdCat($cat) {
  Global $sess,$sess_pid,$_MPM,$db; $_MPM['Serial'][] = "SQL_IdCat($cat)";

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '' && $cat != '') {

        $db->query (
            "SELECT CATID
            FROM ".$_MPM['table'][0]."
            WHERE CAT REGEXP '^\\\\$cat$'
            AND USERID='$sess_pid'"
        );
        $db->next_record();
      return $db->f('CATID');
     }
} ## end of SQL_IdCat

// Recherche le nom de la categorie
// @param $the_id = valeur de la Catégorie
function SQL_SearchCat($the_id) {
  Global $sess,$sess_pid,$_MPM,$other_db; $_MPM['Serial'][] = "SQL_SearchCat($the_id)";

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '' && $the_id != '') {
           $other_db->query (
                "SELECT CAT
                FROM ".$_MPM['table'][0]."
                WHERE CATID='$the_id'
                AND USERID='$sess_pid'"
           );
           $other_db->next_record();
      return $other_db->f('CAT');
     }
} ## end of SQL_SearchCat

// Update the part
// @param $cat      = name of categorie
// @param $the_id   = value of the part
function SQL_UpdateCat($cat,$the_id) {
  Global $sess,$sess_pid,$_MPM,$db; $_MPM['Serial'][] = "SQL_UpdateCat($cat,$the_id)";

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '' && $cat != '' && $the_id != '') {
         $db->query (
              "UPDATE ".$_MPM['table'][0]."
              SET CAT='$cat'
              WHERE CATID='$the_id'
              AND USERID='$sess_pid'"
         );
     }
} ## end of SQL_UpdateCat

// Delete the part
// @param $the_id = value of the part
function SQL_DeleteCat($the_id) {
  Global $sess,$sess_pid,$_MPM,$db; $_MPM['Serial'][] = "SQL_DeleteCat($the_id)";

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '' && $the_id != '') {
          $db->query (
               "DELETE
               FROM ".$_MPM['table'][0]."
               WHERE CATID='$the_id'
               AND USERID='$sess_pid'"
          );
     }
} ## end of SQL_DeleteCat

# --------------------------------*- $_MPM['table'][1] -*-------------------------------

// Verifie les entree en POST Account
// @param   $t      = actif ou temporaire (pour la table)
// @param   $i      = id
// @param   $c      = la correlation
// @param   $v      = valide opration
// @param   $n      = numero id
// @param   $d      = The date
// @param   $pt     = The Part
// @param   $td     = The Thrid
// @param   $ct     = The commentaire
// @param   $de     = The depense
// @param   $re     = The recette
// @param   $a      = The id of account
// @param   $p      = The period
// @param   $choice = The choix des requetes
function SQL_VerifPostAcct($t,$i,$c,$v,$n,$d,$pt,$td,$ct,$de,$re,$a,$p,$choice) {
  Global $sess,$sess_pid,$_MPM,$db; $_MPM['Serial'][] = "SQL_VerifPostAcct($t,$i,$c,$v,$n,$d,$pt,$td,$ct,$de,$re,$a,$p,$choice)";

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '') {
     	   // Clean args
	   $func_item = func_get_args();
	   $func_ind = array('t','i','c','v','n','d','pt',
	   'td','ct','de','re','a','p','choice');
	   $r = array_combine($func_ind,$func_item);
	   foreach($r as $index => $value) {
	   	${$index} = SQL_Clean($value);
	   }

           $period = '';
           if (isset($p) && $p != 'NULL') $period = "AND PERIOD='$p'";

           if (isset($choice) && $choice == 1) {
           $Id       = "AND (OPID='".bcsub($i,1)."' OR OPID='".bcsub($i,2)."')";
           $Corel    = "AND (COREL='".bcsub($c,1)."' OR COREL='".bcsub($c,2)."')";
           } else {
           $Id       = "AND OPID='$i'";
           $Corel    = "AND COREL='$c'";
           }

           $db->query (
               "SELECT OPID
               FROM ".$_MPM['table'][1]."
               WHERE TEMPID='$t'
               $Id
               $Corel
               AND VALID_OP='$v'
               AND NUMID='$n'
               AND USERID='$sess_pid'
               AND DATES= '$d'
               AND CAT='$pt'
               AND THIRD='$td'
               AND COMMENTS='$ct'
               AND SOUTT='$de'
               AND IMP='$re'
               AND ACCOUNT='$a'
               $period"
            );
            $db->next_record();
      return $db->f('OPID');
     }
} ## end of SQL_VerifPostAcct

// Recherche les valeurs superieurs a xx jours
// (entre la date du jour et la date mysql)
// @param $nbre_jour = nombre de jour pour la recherche
function SQL_SearchListOp($nbre_jour) {
  Global $sess,$sess_pid,$_MPM,$db; $_MPM['Serial'][] = "SQL_SearchListOp($nbre_jour)";

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '') {

            $Listz = array();

            $db->query (
                  "SELECT OPID
                  FROM ".$_MPM['table'][1]."
                  WHERE TEMPID=2
                  AND (TO_DAYS(now()) - TO_DAYS(DATES)) > -5
                  AND USERID='$sess_pid'
                  AND (COREL=OPID-1 OR COREL='0')
                  ORDER BY DATES ASC"
            );

            while ($db->next_record()) {
            $Listz[] .= $db->f('OPID');
            }
     return $Listz;
     }
} ## end of SQL_SearchListOp

// Fonction pour le js en mode modifier (le onload)
// @param $obj  = le tableau ou l'on cherche
// @param $id   = le numero du compte
function SQL_JsTiers($obj,$id) {
   Global $sess,$sess_pid,$_MPM,$db; $_MPM['Serial'][] = "SQL_JsTiers($obj,$id)";

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '') {

        if (is_array($obj)) {

          while(list($kmod) = each($obj)) $id_obj = $kmod;
            $db->query (
                   "SELECT THIRD
                   FROM ".$_MPM['table'][1]."
                   WHERE TEMPID=1
                   AND OPID='$id_obj'
                   AND USERID='$sess_pid'
                   AND ACCOUNT='$id' "
            );

            $db->next_record();
        return $db->f('THIRD');
        }
     }
} ## end of SQL_JsTiers

// Recherche le solde du compte de l'user
// @param $cpte      = Numero de compte
// @param $default   = choix de la requete
// @param $val_op    = les opérations non valider encore
function SQL_SearchSolde($cpte,$default=0,$val_op=0) {
  Global $sess,$sess_pid,$_MPM,$other_db; $_MPM['Serial'][] = "SQL_SearchSolde($cpte,$default,$val_op)";

    $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
    if ($sess_pid != '') {

         $_sql  = "SELECT SUM(IMP - SOUTT) as t2 FROM ".$_MPM['table'][1]." WHERE TEMPID=1 ";
         if ($default == 0) {
         $_sql .= "AND TO_DAYS(NOW()) >= TO_DAYS(DATES) ";
         }
         $_sql .= "AND USERID='$sess_pid' AND ACCOUNT='$cpte' ";
         $_sql .= $val_op == 1 ? 'AND VALID_OP=1' : '';

      $other_db->query($_sql);
      $other_db->next_record();
      $ST2=$other_db->f('t2');
    return $ST2 == '' ? 0 : $ST2;
    }
} ## end of SQL_SearchSolde

// Recupere l'id du compte pour le virement , le compte ,
// le nombre de fois que l'operation doit etre valider et
// la somme a affecter aux differents comptes
// retourne dans l'autre suivant : compte | somme | quantite | id compte temp
// @param $tab = la liste complete des valeurs
// @param $type_array = la liste des valeurs a verifier
function SQL_FilterCalendar($tab,$type_array) {
    Global $sess,$sess_pid,$_MPM,$other_db; $_MPM['Serial'][] = "SQL_FilterCalendar($tab,$type_array)";

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '') {

            $other_db->query (
                "SELECT ACCOUNT, COREL, OPID, (IMP - SOUTT) as t2
                FROM ".$_MPM['table'][1]."
                WHERE TEMPID=2
                AND USERID='$sess_pid'
                AND OPID IN ($type_array) ORDER BY ACCOUNT"
            );

         ## For notice initialise the tab
         $compteur_value = array();
         $find_array     = array();
         $compteur_value = array_count_values($tab);

         while ($other_db->next_record()) {

                ## ACCOUNT
                if (in_array($other_db->f('OPID'),$tab)) {

                   ## For notice initialise the tab (find the number for multiplication)
                   if (isset($compteur_value[$other_db->f('OPID')])) {
                     $cle_array[($other_db->f('OPID'))] = $compteur_value[$other_db->f('OPID')];
                   } else {
                     $cle_array[($other_db->f('OPID'))] = 1;
                   }

                    $cle = $other_db->f('t2') * $cle_array[($other_db->f('OPID'))];

                    if (isset($find_array[($other_db->f('ACCOUNT'))])) {
                     $find_array[($other_db->f('ACCOUNT'))] += $cle;
                    } else {
                     $find_array[($other_db->f('ACCOUNT'))] = $cle;
                    }
                }
                ## COREL
                else if (in_array($other_db->f('COREL'),$tab) && $other_db->f('COREL') != 0) {

                   ## For notice initialise the tab (find the number for multiplication)
                   if (isset($compteur_value[$other_db->f('COREL')])) {
                     $cle_corel[($other_db->f('OPID'))] = $compteur_value[$other_db->f('COREL')];
                   } else {
                     $cle_corel[($other_db->f('OPID'))] = 1;
                   }

                    $cle = $other_db->f('t2') * $cle_corel[($other_db->f('OPID'))];

                    if (isset($find_array[($other_db->f('ACCOUNT'))])) {
                     $find_array[($other_db->f('ACCOUNT'))] += $cle;
                    } else {
                     $find_array[($other_db->f('ACCOUNT'))] = $cle;
                    }
                } ## end of in_array()
         } ## end of while ($other_db->next_record())
     return $find_array;
     }
} ## end of SQL_FilterCalendar

// Recherche le numero de correlation
// @param $tmp = actif ou temporaire (pour la table)
// @param $id = id du compte
function SQL_SearchIdCorel($tmp,$id) {
  Global $sess,$sess_pid,$_MPM,$db; $_MPM['Serial'][] = "SQL_SearchIdCorel($tmp,$id)";

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '') {

         $db->query (
              "SELECT COREL
              FROM ".$_MPM['table'][1]."
              WHERE TEMPID='$tmp'
              AND USERID='$sess_pid'
              AND OPID='$id'"
         );
         $db->next_record();
    return $db->f('COREL');
    }
} ## end of SQL_SearchIdCorel

// Recherche tous les numeros de correlations
// @param $tab = le tableau des valeurs
function SQL_SearchAllCorel($tab) {
  Global $sess,$sess_pid,$_MPM,$db; $_MPM['Serial'][] = "SQL_SearchAllCorel($tab)";

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '') {

           $liste_id = array();
           $db->query (
                "SELECT COREL AS NEW_ID_COREL
                FROM ".$_MPM['table'][1]."
                WHERE TEMPID=2
                AND USERID='$sess_pid'
                AND OPID IN ($tab)
                AND COREL<>'0'"
           );
         while ($db->next_record()) {
                      $liste_id[] .= $db->f('NEW_ID_COREL');
         }
      return $liste_id;
     }
} ## end of SQL_SearchAllCorel

// Retourne la premiere date des comptes
function SQL_FirstDate() {
   Global $sess,$sess_pid,$_MPM,$db; $_MPM['Serial'][] = 'SQL_FirstDate';

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '') {
           $db->query (
               "SELECT DATES FROM ".$_MPM['table'][1]."
               WHERE USERID='$sess_pid' ORDER BY DATES ASC LIMIT 1"
           );
           if ($db->num_rows() > 0) {
               $db->next_record();
               $firstday = $db->f('DATES');
           } else {
               $firstday = date('Y-m-d',time());
           }
     return $firstday;
     }
} ## end of SQL_FirstDate

// Retourne la derniere date des comptes
function SQL_LastDate() {
   Global $sess,$sess_pid,$_MPM,$db; $_MPM['Serial'][] = 'SQL_LastDate';

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '') {
         $db->query (
              "SELECT DATE_FORMAT(DATES,'%w-%d-%m-%Y') as THE_DATES
              FROM ".$_MPM['table'][1]."
              WHERE TEMPID=1
              AND USERID='$sess_pid'
              AND NOW() < DATES
              ORDER BY DATES DESC LIMIT 1"
         );
     while ($db->next_record()) { return MPM_FormatDates($db->f('THE_DATES')); }
     }
} ## end of SQL_LastDate

// Retourne les dates trouver
// @param $id    = numero de compte
function SQL_SeachDay($id) {
  Global $sess,$sess_pid,$_MPM,$db,$_VAR; $_MPM['Serial'][] = "SQL_SeachDay($id)";

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '') {
           $db->query (
                "SELECT DISTINCT DATE_FORMAT(DATES,'%m|%Y') AS NEWS_DATES
                FROM ".$_MPM['table'][1]."
                WHERE TEMPID=1
                AND USERID='$sess_pid'
                AND ACCOUNT='$id'
                ORDER BY DATES DESC"
           );

           $NbDay = array();
           while ($db->next_record()) {
              $NbDay[] = $db->f('NEWS_DATES');
           }
     return $NbDay;
     }
} ## end of SQL_SeachDay

// Recherche la periodicite de l'operation
// @param $id = id du compte temporaire
function SQL_SearchPeriod($id) {
  Global $sess,$sess_pid,$_MPM,$db; $_MPM['Serial'][] = "SQL_SearchPeriod($id)";

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '') {
             $db->query (
                "SELECT PERIOD
                FROM ".$_MPM['table'][1]."
                WHERE TEMPID=2
                AND USERID='$sess_pid'
                AND OPID='$id'"
             );
             $db->next_record();
     return $db->f('PERIOD');
     }
} ## end of SQL_SearchPeriod

// Cherche tous les soldes à mettre à jour
// @param $cpte  = Numero de compte
function SQL_RecupSolde($cpte) {
   Global $sess,$sess_pid,$_MPM,$other_db; $_MPM['Serial'][] = "SQL_RecupSolde($cpte)";

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '') {
         $other_db->query (
              "SELECT DATE_FORMAT(DATES,'%m-%Y') AS NEWS_DATES, OPID,
              SUM(IMP - SOUTT) AS NEWS_SOLDES
              FROM ".$_MPM['table'][1]."
              WHERE TEMPID=1
              AND USERID='$sess_pid'
              AND ACCOUNT='$cpte'
              GROUP BY OPID
              ORDER BY DATES ASC, OPID ASC"
         );

       $news = '';
       while ($other_db->next_record()) {
          $This_compte=$other_db->f('OPID');
          $This_news_soldes=$other_db->f('NEWS_SOLDES');
          $news += $This_news_soldes;
          // 28-May-2005 :: bug fix by Sebastien Lienard
          $news_result = number_format($news,2,'.','');
       SQL_UpdateAccount(1,'',$news_result,'',1,$This_compte);
       }
     }
} ## end of SQL_RecupSolde

// Recherche les valeurs des annees et mois existant
// @param $search    = la mois ('m') ou l'annee ('Y')
// @param $order     = DESC OR ASC
function SQL_SearchYearMonth($search,$order) {
   Global $sess,$sess_pid,$_MPM,$db; $_MPM['Serial'][] = "SQL_SearchYearMonth($search,$order)";

    $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
    if ($sess_pid != '') {
      $db->query (
         "SELECT DISTINCT DATE_FORMAT(DATES,'%$search') as SEARCH
         FROM ".$_MPM['table'][1]."
         WHERE TEMPID=1 AND USERID='$sess_pid'
         ORDER BY SEARCH $order"
      );
      $_search = array();
      while ($db->next_record()) {
         $_search[] .= $db->f('SEARCH');
      }
   }
return $_search;
} ## end of SQL_SearchYearMonth

// Recherche les valeurs des annees pour les operations
// @param $cat    = la categorie
// @param $tiers  = le tiers
// @param $debut  = le nombre de page
function SQL_SearchYearOperate($cat,$tiers) {
   Global $sess,$sess_pid,$_MPM,$db; $_MPM['Serial'][] = "SQL_SearchYearOperate($cat,$tiers)";

    $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
    if ($sess_pid != '') {

    ## For choice of the year
    $preselect  = "SELECT DISTINCT DATE_FORMAT(DATES,'%Y') as SEARCH ";
    $preselect .= "FROM ".$_MPM['table'][1]." WHERE TEMPID=1 AND USERID='$sess_pid' AND CAT='$cat' ";
    $preselect .= (($tiers != "" && $tiers != __ANOTHER_ACCOUNT__) ? 'AND ': 'OR ' );
    $preselect .= "THIRD='$tiers' ORDER BY DATES DESC";

    $db->query($preselect);

      $_search = array();
      while ($db->next_record()) {
        $_search[] .= $db->f('SEARCH');
      }
   }
return $_search;
} ## end of SQL_SearchYearOperate

// Recherche le Compte de correlation
// @param $tmp      = actif ou temporaire (pour la table)
// @param $cpt      = numero du compte en correlation
// @param $corel    = Recherche les correlation ou pas
function SQL_Search_AcctCorel($tmp,$cpt,$corel) {
   Global $sess,$sess_pid,$_MPM,$other_db; $_MPM['Serial'][] = "SQL_Search_AcctCorel($tmp,$cpt,$corel)";

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '') {
             $corel = '';
             if (isset($corel) && $corel == 1) $corel = "AND COREL <> '0'";
             $other_db->query
             (
                     "SELECT ACCOUNT
                     FROM ".$_MPM['table'][1]."
                     WHERE TEMPID='$tmp'
                     AND USERID='$sess_pid'
                     AND OPID='$cpt'
                     $corel"
             );
             $other_db->next_record();
      return $other_db->f('ACCOUNT');
     }
} ## end of SQL_Search_AcctCorel

// Met a jour tous les comptes rattache a un tiers ou une categorie
// @param $tiers = Tiers
// @param $cat = Catégorie
// @param $choice = choix de la recherche cat ou les deux
function SQL_UpdateSolde($cat,$tiers,$choice) {
  Global $sess,$sess_pid,$_MPM,$db; $_MPM['Serial'][] = "SQL_UpdateSolde($cat,$tiers,$choice)";

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '') {
          ## THIRD AND PART
          if ($choice == 1) {
                  $db->query (
                       "SELECT DISTINCT ACCOUNT
                       FROM ".$_MPM['table'][1]."
                       WHERE TEMPID=1
                       AND CAT='$cat'
                       AND THIRD='$tiers'
                       AND USERID='$sess_pid'
                       ORDER BY ACCOUNT"
                  );
                  SQL_DeleteAccount(1,$cat,$tiers,4);
          }
          ## THIRD
          else if ($choice == 2) {
                  $db->query (
                       "SELECT DISTINCT ACCOUNT
                       FROM ".$_MPM['table'][1]."
                       WHERE TEMPID=1
                       AND CAT='$cat'
                       AND USERID='$sess_pid'
                       ORDER BY ACCOUNT"
                  );
            SQL_DeleteAccount(1,$cat,'',3);
          }

          while ($db->next_record()) {
               $This_compte=$db->f('ACCOUNT');
           SQL_RecupSolde($This_compte);
          }
     }
} ## end of SQL_UpdateSolde

// Delete the Account
// @param   $t      = actif ou temporaire (pour la table)
// @param   $i      = id
// @param   $a      = The id of account
// @param   $choice = The choix des requetes
function SQL_DeleteAccount($t,$i,$a,$choice) {
  Global $sess,$sess_pid,$_MPM,$valid_db; $_MPM['Serial'][] = "SQL_DeleteAccount($t,$i,$a,$choice)";

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '') {
          if (isset($choice) && $choice == 1)      $tmp = "AND ACCOUNT='$a'";
          else if (isset($choice) && $choice == 2) $tmp = "AND OPID IN ($i)";
          else if (isset($choice) && $choice == 3) $tmp = "AND CAT='$i'";
          else if (isset($choice) && $choice == 4) $tmp = "AND CAT='$i' AND THIRD='$a'";
          else $tmp = "AND OPID='$i'";

            $valid_db->query (
                 "DELETE FROM ".$_MPM['table'][1]."
                 WHERE TEMPID='$t'
                 $tmp
                 AND USERID='$sess_pid'"
            );
     }
} ## end of SQL_DeleteAccount

// Update the ID Account
// @param   $set    = Option for the SET
// @param   $tab    = list for id
// @param   $tset   = la valeur du set
// @param   $a      = The id of account
// @param   $t      = actif ou temporaire (pour la table)
// @param   $i      = id
function SQL_UpdateAccount($set,$tab,$tset,$a,$t,$i) {
   Global $sess,$sess_pid,$_MPM,$valid_db; $_MPM['Serial'][] = "SQL_UpdateAccount($set,$tab,$tset,$a,$t,$i)";

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '') {
         $EndSet = '';
         if (isset($set) && $set == 1) {
             $Set      = "SET BALANCE='$tset'";
         } else if (isset($set) && $set == 2) {
             $Set      = "SET $tab, OPID='$tset'";
         } else if (isset($set) && $set == 3) {
             $Set      = "SET $tab, PERIOD='$tset'";
         } else if (isset($set) && $set == 4) {
             $Set      = "SET $tab, OPID='$a', PERIOD='$tset'";
         } else if (isset($set) && $set == 5) {
             $Set      = "SET DATES=DATES + INTERVAL ".$tset." MONTH";
         } else if (isset($set) && $set == 6) {
             $Set      = "SET $tab";
             $EndSet   = "AND ACCOUNT='$a'";
         } else if (isset($set) && $set == 7) {
             $Set      = "SET $tab, OPID='$tset'";
             $EndSet   = "AND ACCOUNT='$a'";
         } else if (isset($set) && $set == 8) {
             $Set      = "SET $tab";
         } else {
             $Set      = "SET VALID_OP='$tset'";
         }

            $valid_db->query (
                 "UPDATE ".$_MPM['table'][1]."
                  $Set
                  WHERE TEMPID='$t'
                  AND OPID='$i'
                  AND USERID='$sess_pid'
                  $EndSet"
            );
     }
} ## end of SQL_UpdateAccount

// Update all the table for ID Account
// @param   $o      = valid for op
// @param   $n      = numero id
// @param   $da     = the date
// @param   $th     = The third
// @param   $r      = recette
// @param   $d      = depense
// @param   $a      = account id
// @param   $c      = the comment
// @param   $p      = period
// @param   $t      = temp id
// @param   $i      = id compte
function SQL_UpdateAllAccount($o,$n,$da,$th,$r,$d,$a,$c,$p,$t,$i) {
   Global $sess,$sess_pid,$_MPM,$valid_db; $_MPM['Serial'][] = "SQL_UpdateAllAccount($o,$n,$da,$th,$r,$d,$a,$c,$p,$t,$i)";

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '') {
          // Clean
	  $func_item = func_get_args();
	  $func_ind = array('o','n','da','th','r','d','a',
	  'c','p','t','i');
	  $r = array_combine($func_ind,$func_item);
	  foreach($r as $index => $value) {
	  	${$index} = SQL_Clean($value);
	  }

	  $Set = '';
          if (isset($p) && isset($t) && $t == 2) $Set = ",PERIOD='$p'";
             $valid_db->query (
                       "UPDATE ".$_MPM['table'][1]."
                       SET VALID_OP='$o',
                       NUMID='$n',
                       DATES='$da',
                       THIRD='$th',
                       IMP='$r',
                       SOUTT='$d',
                       ACCOUNT='$a',
                       COMMENTS='$c'
                       $Set
                       WHERE TEMPID='$t'
                       AND OPID='$i'
                       AND USERID='$sess_pid'"
             );
     }
} ## end of SQL_UpdateAllAccount

// Update the comment for Opening of account
function SQL_UpdateComment() {
   Global $sess,$sess_pid,$_MPM,$_VAR,$db; $_MPM['Serial'][] = "SQL_UpdateAllAccount()";
     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '') {
       $c = $_VAR['OPEN_ACCOUNT_BEGIN_COMMENT'];
       $db->query("UPDATE ".$_MPM['table'][1]." SET COMMENTS='$c' WHERE USERID='$sess_pid' AND CAT=2");
     }
} ## end of SQL_UpdateComment

// Insert the News Account
// @param   $a      = OPID
// @param   $b      = NUMID
// @param   $c      = TEMPID
// @param   $d      = VALID_OP
// @param   $f      = DATES
// @param   $g      = CAT
// @param   $h      = THIRD
// @param   $i      = COREL
// @param   $j      = COMMENTS
// @param   $k      = OUTPUT
// @param   $l      = IMPUT
// @param   $m      = ACCOUNT
// @param   $n      = BALANCE
// @param   $o      = PERIOD
function SQL_InsertAccount($a,$b,$c,$d,$f,$g,$h,$i,$j,$k,$l,$m,$n,$o) {
   Global $sess,$sess_pid,$_MPM,$valid_db; $_MPM['Serial'][] = "SQL_InsertAccount($a,$b,$c,$d,$f,$g,$h,$i,$j,$k,$l,$m,$n,$o)";

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '') {
     	// Clean
	$func_item = func_get_args();
	$func_ind = array('a','b','c','d','f','g','h',
	'i','j','k','l','m','n','o');
	$r = array_combine($func_ind,$func_item);
	foreach($r as $index => $value) {
		${$index} = SQL_Clean($value);
	}

       $valid_db->query
       (
        "INSERT INTO ".$_MPM['table'][1]." (
               OPID,
               NUMID,
               TEMPID,
               VALID_OP,
               USERID,
               DATES,
               CAT,
               THIRD,
               COREL,
               COMMENTS,
               SOUTT,
               IMP,
               ACCOUNT,
               BALANCE,
               PERIOD
         )
         VALUES('$a','$b','$c','$d','$sess_pid','$f','$g','$h','$i','$j','$k','$l','$m','$n','$o')"
        );
     }
} ## end of SQL_InsertAccount

# --------------------------------*- $_MPM['table'][2] -*-------------------------------

// Recherche id d'un compte
// @param $nom_cpt  = Nom du compte
function SQL_IdAccount($nom_cpt) {
  Global $sess,$sess_pid,$_MPM,$db; $_MPM['Serial'][] = "SQL_IdAccount($nom_cpt)";

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '') {
        $tmp = '';
        if (isset($nom_cpt) && $nom_cpt != '') {
           $tmp = "AND ACCOUNT='$nom_cpt'";
        }

         $db->query (
                 "SELECT ACCOUNTID
                 FROM ".$_MPM['table'][2]."
                 WHERE USERID='$sess_pid'
                 $tmp
                 ORDER BY ACCOUNT ASC"
         );
         $db->next_record();
     return $db->f('ACCOUNTID');
     }
} ## end of SQL_IdAccount

// Verfie l'ajout d'un nouveau compte
// @param $nom_cpt  = Nom du compte
function SQL_AddAccount($nom_cpt) {
  Global $sess,$sess_pid,$_MPM,$db; $_MPM['Serial'][] = "SQL_AddAccount($nom_cpt)";

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '') {
             $db->query (
                  "SELECT ACCOUNTID
                  FROM ".$_MPM['table'][2]."
                  WHERE ACCOUNT='$nom_cpt'
                  AND USERID='$sess_pid'"
             );
             $db->next_record();
     return $db->f('ACCOUNTID');
     }
} ## end of SQL_AddAccount

// Recherche Nom d'un compte
// @param $cpte = Numero de compte
function SQL_NameAccount($cpte) {
   Global $sess,$sess_pid,$_MPM,$other_db; $_MPM['Serial'][] = "SQL_NameAccount($cpte)";

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '') {
           $other_db->query (
              "SELECT ACCOUNT
              FROM ".$_MPM['table'][2]."
              WHERE USERID='$sess_pid'
              AND ACCOUNTID='$cpte'"
           );
           $other_db->next_record();
    return $other_db->f('ACCOUNT');
    }
} ## end of SQL_NameAccount

// Affichage du menu deroulant pour le choix du compte
// @param $id       = numero de compte
// @param $choice   = le choix du menu deroulant
//                          1    =>  choix du compte
//                          2    =>  choix du compte simple
//                          3    =>  choix du compte pour le bilan
function SQL_ChoiceAccount($id,$choice) {
  Global $sess,$sess_pid,$_MPM,$tpl,$tools,$db,$_VAR; $_MPM['Serial'][] = "SQL_ChoiceAccount($id,$choice)";

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '') {
         if (isset($choice) && $choice == 1) {
           $a   = 'Account';
           $b   = 'ID';
           $c   = ' onchange="return Verif_MOUV_ACCOUNT(this.form);"';
           $d   = '';
           $e   = $_VAR['LANG_ACCOUNT_22'];
         }
         else if (isset($choice) && $choice == 2) {
           $a   = 'Medium';
           $b   = 'S_compte';
           $c   = '';
           $d   = '';
           $e   = $_VAR['LANG_CALEND_DIS_9'];
         }
         else if (isset($choice) && $choice == 3) {
           $a   = 'iewidth';
           $b   = 'A_Account';
           $c   = '';
           $d   = '';
           $e   = $_VAR['BILAN_ACCOUNT'];
         }

           $_MPM['BeginMixed'] = array
           (
                'CLASS_CSS'    => $a,
                'NAME_SELECT'  => $b,
                'OPTION_JS'    => $c,
                'ANOTHER_VALUE'=> $d,
                'ANOTHER_NAME' => $e
           );
           XHTML_SetFile('form_select_all.tpl',$_MPM['BeginMixed'],0);

        $db->query (
              "SELECT ACCOUNTID,ACCOUNT
              FROM ".$_MPM['table'][2]."
              WHERE USERID='$sess_pid'
              ORDER BY ACCOUNT ASC"
        );

        $tpl->set_block('FILE_form_select_all.tpl', 'BOUCLE_SELECT_ALL', 'BLOCK_form_select_all.tpl');
        while ($db->next_record()) {

               if (isset($choice) && $choice == 1) {
                  $_COMPTES = $tools->Reduit_chaine($db->f('ACCOUNT'),__LENGTH_ACCOUNT__,0);
                  $_sold  = '('.$_VAR['LANG_OPTION_SELECT_1'].': '.$tools->formatage(SQL_SearchSolde($db->f('ACCOUNTID'),0,0));
                  $_sold .= ' ; '.$_VAR['LANG_OPTION_SELECT_2'].': '.$tools->formatage(SQL_SearchSolde($db->f('ACCOUNTID'),1,0));
                  $_sold .= ' ; '.$_VAR['LANG_OPTION_SELECT_3'].': '.$tools->formatage(SQL_SearchSolde($db->f('ACCOUNTID'),1,1)).')';
               }
               else if (isset($choice) && ($choice == 2 || $choice == 3)) {
                  $_COMPTES = $tools->Reduit_chaine($db->f('ACCOUNT'),__LENGTH_ACCOUNT__,0);
                  $_sold = '';
               }
         $tpl->set_var(array(
               'VALUE_COMPTE'   => $db->f('ACCOUNTID'),
               'NAME_COMPTE'    => $_VAR['LANG_ACCOUNT_4']." : $_COMPTES ".$_sold,
               'SELECTED'       => $id == $db->f('ACCOUNTID') ? ' selected="selected"' : ''
         ));
         $tpl->parse('BLOCK_form_select_all.tpl','BOUCLE_SELECT_ALL',true);
         }
     return XHTML_SetFile('form_select_all.tpl','',3);
     }
} ## end of SQL_ChoiceAccount

// Recherche l'id du compte pour le virement au cas ou
// Recherche l'id du tiers pour le virement
// @param $choice       = Choix de la recherche
// @param $cpte         = le tiers
function SQL_SearchInThird($choice,$cpte) {
  Global $sess,$sess_pid,$_MPM; $_MPM['Serial'][] = "SQL_SearchInThird($choice,$cpte)";

     $modul_db = new MPM_DB;
     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '') {
         if (isset($choice) && $choice == 1) {
             $Begin     = "SELECT ".$_MPM['table'][2].".ACCOUNTID";
             $End       = "AND ".$_MPM['table'][4].".THIRDID ='$cpte'";
         } else {
             $Begin     = "SELECT ".$_MPM['table'][4].".THIRDID";
             $End       = "AND ".$_MPM['table'][2].".ACCOUNTID='$cpte'";
         }

         if ($cpte != "") {
           $modul_db->query (
               "$Begin
               FROM ".$_MPM['table'][4].", ".$_MPM['table'][2]."
               WHERE ".$_MPM['table'][4].".USERID='$sess_pid'
               AND ".$_MPM['table'][4].".THIRD=".$_MPM['table'][2].".ACCOUNT
               AND ".$_MPM['table'][2].".USERID=".$_MPM['table'][4].".USERID
               AND ".$_MPM['table'][4].".CATID='".__PART_ID__."'
               $End"
           );
           $modul_db->next_record();
        return isset($choice) && $choice == 1 ? $modul_db->f('ACCOUNTID') : $modul_db->f('THIRDID');
        }
     }
} ## end of SQL_SearchInThird

// Insert the new detail of account
// @param $a = ACCOUNTID
// @param $c = ACCOUNT
function SQL_InsAccount($a,$c) {
  Global $sess,$sess_pid,$_MPM,$db; $_MPM['Serial'][] = "SQL_InsAccount($a,$c)";

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '') {
          $db->query (
               "INSERT INTO ".$_MPM['table'][2]."
               (
                    ACCOUNTID,
                    USERID,
                    ACCOUNT
               )
          VALUES ('$a','$sess_pid','$c')"
          );
     }
} ## end of SQL_InsAccount

// efface le compte selectionner
// @param $val = compte
function SQL_DelAccount($val) {
  Global $sess,$sess_pid,$_MPM,$db; $_MPM['Serial'][] = "SQL_DelAccount($val)";

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '') {
          $db->query (
               "DELETE FROM ".$_MPM['table'][2]."
               WHERE ACCOUNTID='$val'
               AND USERID='$sess_pid'"
          );
     }
} ## end of SQL_DelAccount

// update le compte selectionner
// @param $val        = l'id du compte
// @param $cpt        = compte
function SQL_UpAccount($val,$cpt) {
   Global $sess,$sess_pid,$_MPM,$tools,$db; $_MPM['Serial'][] = "SQL_UpAccount($val,$cpt)";

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '') {
         $db->query (
            "UPDATE ".$_MPM['table'][2]." SET ACCOUNT='$cpt'
            WHERE ACCOUNTID='$val'
            AND USERID='$sess_pid'"
         );
     }
} ## end of SQL_UpAccount

# --------------------------------*- $_MPM['table'][3] -*-------------------------------

// Return just password
// @param $name = the name of user
function SQL_ReturnPassword($name) {
 Global $_MPM,$db; $_MPM['Serial'][] = 'SQL_ReturnPassword';
   $db->query (
         "SELECT PWD FROM ".$_MPM['table'][3]."
         WHERE LOGIN_NAME='$name'"
    );
    $db->next_record();
  $pwd = $db->f('PWD');
return isset($pwd) ? $pwd : '';
} ## end of SQL_NumberAccount

// Verifie le nombre de compte
function SQL_NumberAccount() {
   Global $_MPM,$db; $_MPM['Serial'][] = 'SQL_NumberAccount';
   $db->query("SELECT * FROM ".$_MPM['table'][3]);
return $db->num_rows();
} ## end of SQL_NumberAccount

// Verifie le nom d'utilisateur
// @param $name = the name of user
function SQL_VerifUser($name) {
   Global $_MPM,$db,$_VAR; $_MPM['Serial'][] = "SQL_VerifUser($name)";
       $db->query (
            "SELECT LOGIN_NAME
            FROM ".$_MPM['table'][3]."
            WHERE LOGIN_NAME='$name'"
       );
       $db->next_record();
return $db->f('LOGIN_NAME');
} ## end of SQL_VerifUser

// Verifie l'existence de la session
function SQL_VerifSession() {
  Global $sess,$sess_pid,$sess_user,$sess_pwd,$sess_time;
   Global $_MPM,$db,$_VAR; $_MPM['Serial'][] = 'SQL_VerifSession';

    $sess_pid  = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
    $sess_user = isset($sess_user) && is_object($sess) && $sess->is_registered('sess_user') ? $sess_user : '';
    $sess_pwd  = isset($sess_pwd) && is_object($sess) && $sess->is_registered('sess_pwd') ? $sess_pwd  : '';

    if (($sess_pid == '' || $sess_user == '' || $sess_pwd == '') ||
         (isset($GLOBALS['_GET']['op']) && $GLOBALS['_GET']['op'] == 'Signup')) {
         return (int) 0;
     } else {
         $db->query (
              "SELECT * FROM ".$_MPM['table'][3]."
              WHERE LOGIN_NAME='$sess_user'
              AND USERID='$sess_pid'
              AND PWD = '$sess_pwd'"
         );

        if (!$db->num_rows() > 0) {
         return (int) 0;
        }
        else {
          SQL_CreateVirement();
          SQL_CreateOpenCat();
          SQL_CreateOpenThird();
          $sess_time = $_MPM['date_unix'] + $_MPM['sess_expire'];
          $sess->register('sess_time');
        return (int) 1;
        }
     }
return;
} ## end of SQL_VerifSession

// Verifie l'ancien mot de passe et
// insere le nouveau mot de passe
// @param $Oldpass = l'ancien passe
// @param $Newpass = le nouveau pass
function SQL_VerifPass($Oldpass,$Newpass) {
   Global $sess,$sess_pid,$_MPM,$db,$_VAR; $_MPM['Serial'][] = "SQL_VerifPass($Oldpass,$Newpass)";

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '') {
       $db->query (
            "SELECT PWD FROM ".$_MPM['table'][3]."
            WHERE PWD='$Oldpass'
            AND USERID='$sess_pid'"
       );
       if ($db->num_rows() == 1) SQL_UpdateUser(5,$Newpass,'',$sess_pid);
       else XHTML_DisplayJs($_VAR['MESSAGE_HT_ACCESS'][5]);
     }
} ## end of SQL_VerifPass

// Update the user
// @param $set      = Option for the SET
// @param $tset1    = la valeur du set1
// @param $tset2    = la valeur du set2
// @param $pid      = the userid
function SQL_UpdateUser($set,$tset1,$tset2,$pid) {
  Global $sess,$sess_pwd,$_MPM,$db; $_MPM['Serial'][] = "SQL_UpdateUser($set,$tset1,$tset2,$pid)";

     if ($pid != '') {
        if (isset($set) && $set == 1)        $Set = "SET GRAPH='$tset1'";
        else if (isset($set) && $set == 2)   $Set = "SET COUNTRY_VAL='$tset1', LANG_VAL='$tset2'";
        else if (isset($set) && $set == 3)   $Set = "SET LASTVISIT2='$tset1', LASTVISIT='$tset2'";
        else if (isset($set) && $set == 4)   $Set = "SET LANG_VAL='$tset1'";
        else if (isset($set) && $set == 5)   $Set = "SET PWD='$tset1'";

         if (isset($Set)) {
            $db->query("UPDATE ".$_MPM['table'][3]." $Set WHERE USERID='$pid'");

            ## Only if update is OK
            if ($db->affected_rows() && isset($set) && $set == 5) {
               $sess_pwd = $tset1;
            $sess->register('sess_pwd');
            }
         }
     }
} ## end of SQL_UpdateUser

// Affiche les graphiques
// @param $this_graph = le choix du graphique
function SQL_ConstrucGraph($this_graph) {
  Global $sess,$sess_pid,$_MPM,$db,$_VAR; $_MPM['Serial'][] = "SQL_ConstrucGraph($this_graph)";

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '') {
          $g = '';
          if ($this_graph == 'default') {
              $db->query (
                 "SELECT
                     DATE_FORMAT(
                           LASTVISIT2, '<p class=\"center\"><br />
                           ".$_VAR['LANG_HOME_GRAPH_2']." :<br /><span class=\"menubold\">
                           ".$_VAR['LANG_HOME_GRAPH_4']." %d {%m} %Y
                           ".$_VAR['LANG_HOME_GRAPH_5']." %H:%i:%s</span></p>'
                     ) AS A1,
                     DATE_FORMAT(
                           VISIT, '<p class=\"center\">
                           ".sprintf($_VAR['LANG_HOME_GRAPH_3'],$_MPM['name'])."<br /><span class=\"menubold\">
                           ".$_VAR['LANG_HOME_GRAPH_4']."  %d {%m} %Y
                           ".$_VAR['LANG_HOME_GRAPH_5']."  %H:%i:%s</span></p>'
                     ) AS A2
                     FROM ".$_MPM['table'][3]."
                     WHERE USERID='$sess_pid'"
              );
              $db->next_record();
                $g .= MPM_ReplacePatterns($db->f('A1'));
                $g .= XHTML_DisplayGraph($this_graph);
                $g .= MPM_ReplacePatterns($db->f('A2'));
           } else {
                $g .= XHTML_DisplayGraph($this_graph);
           }
     return $g;
     }
} ## end of SQL_ConstrucGraph

// Insert the News user
// @param   $a      = USERID
// @param   $b      = LOGIN_NAME
// @param   $c      = PWD
// @param   $d      = COUNTRY_VAL
// @param   $e      = LANG_VAL
// @param   $f      = VISIT
// @param   $g      = LASTVISIT2
// @param   $h      = LASTVISIT
// @param   $i      = EMAIL
// @param   $j      = FIRSTNAME
// @param   $k      = LASTNAME
function SQL_InsertUser($a,$b,$c,$d,$e,$f,$g,$h,$i,$j,$k) {
  Global $_MPM,$db; $_MPM['Serial'][] = "SQL_InsertUser($a,$b,$c,$d,$e,$f,$g,$h,$i,$j,$k)";

	// Clean args
	 $func_item = func_get_args();
	 $func_ind = array('a','b','c','d','e','f','g','h','i','j','k');
	 $r = array_combine($func_ind,$func_item);
	 foreach($r as $index => $value) {
	 	${$index} = SQL_Clean($value);
	 }

        $db->query (
            "INSERT INTO ".$_MPM['table'][3]."
            (
                 USERID,
                 LOGIN_NAME,
                 PWD,
                 COUNTRY_VAL,
                 LANG_VAL,
                 GRAPH,
                 VISIT,
                 LASTVISIT2,
                 LASTVISIT,
                 EMAIL,
                 FIRSTNAME,
                 LASTNAME
            )
            VALUES ('$a','$b','$c','$d','$e','default','$f','$g','$h','$i','$j','$k')"
         );
} ## end of SQL_InsertUser

# --------------------------------*- $_MPM['table'][4] -*-------------------------------

// Recherche l'id du Tiers
// @param $choice    = For choice the sql request
// @param $tcat      = l'id de la categorie
// @param $newstiers = le nouveau tiers
function SQL_SearchIdThird($choice,$tcat,$newstiers) {
   Global $sess,$sess_pid,$_MPM,$valid_db; $_MPM['Serial'][] = "SQL_SearchIdThird($choice,$tcat,$newstiers)";

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '') {
          $valid  = "SELECT THIRDID FROM ".$_MPM['table'][4]." ";
          if (isset($choice) && $choice == 2) {
          $valid .= "WHERE CATID='$tcat' ";
          } else {
          $valid .= "WHERE THIRD REGEXP '^\\\\$newstiers$' ";
          }
          if (isset($choice) && $choice == 1) {
          $valid .= "AND CATID='$tcat' ";
          }
          $valid .= "AND USERID='$sess_pid'";

         $valid_db->query($valid);
         $valid_db->next_record();
      return $valid_db->f('THIRDID');
     }
} ## end of SQL_SearchIdThird

// Verifier l'existence du nouveau Tiers et le creer
// @param $newstiers = le nouveau tiers
// @param $tcat      = l'id de la categorie
// @param $idtiers   = l'id du nouveau tiers
function SQL_BuildTiers($newstiers,$tcat,$idtiers) {
   Global $_MPM,$db; $_MPM['Serial'][] = "SQL_BuildTiers($newstiers,$tcat,$idtiers)";

       $_tiers = SQL_SearchIdThird(1,$tcat,$newstiers);

           if (!$_tiers) {
               if ($tcat != __PART_ID__)
                    SQL_InsertThird($idtiers,$tcat,$newstiers);
               $id_tiers = $idtiers;
         } else {
               $id_tiers = $_tiers;
         }
   return $id_tiers;
} ## end of SQL_BuildTiers

// Listing des cat et tiers
// @param $S_cat = valeur de la Catégorie existante methode post
// @param $js    = le javascript a afficher
// @param $css   = la feuille de style à afficher
function SQL_ListRecursive($S_cat,$js=0,$css) {
  Global $sess,$sess_pid,$_MPM; $_MPM['Serial'][] = "SQL_ListRecursive($S_cat,$js)";
  Global $db,$tools,$other_db,$tpl,$_VAR;

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '') {
          if ($js == 0) {
              $opt_js = ' onchange="return Verif_Cat();"';
              $no_include = '';
          }
          if ($js == 1) {
              $opt_js = ' onchange="Add_objet(\'parent\',\'here\',this.form.S_cat.options[this.form.S_cat.selectedIndex].value);"';
              $no_include = 'AND CATID <> '.__OPEN_PART__;
          }

               $_MPM['BeginMixed'] = array
               (
                    'ACCOUNT_ANOTHER'        => $_VAR['ACCOUNT_ANOTHER'],
                    'MESS_THIRD_PART_MENU'   => $_VAR['MESS_THIRD_PART_MENU'],
                    'CLASS_CSS'              => "iewidth$css",
                    'NAME_SELECT'            => 'S_cat',
                    'OPTION_JS'              => $opt_js,
                    'MESS_THIRD_PART_MENU'   => $_VAR['MESS_THIRD_PART_MENU']
                );
                XHTML_SetFile('form_select_third.tpl',$_MPM['BeginMixed'],0);

           $tpl->set_block('FILE_form_select_third.tpl', 'BOUCLE_JS_SUB_CATEGORIE', 'BLOCK_form_select_third.tpl_GO_1'); ## BLOCK INTERNE
           $tpl->set_block('FILE_form_select_third.tpl', 'BOUCLE_JS_CATEGORIE', 'BLOCK_form_select_third.tpl_GO_2');     ## BLOCK EXTERNE

              $db->query (
                     "SELECT DISTINCT CATID,CAT
                     FROM ".$_MPM['table'][0]."
                     WHERE USERID='$sess_pid'
                     AND CATID <> '' $no_include
                     AND CAT <> ''
                     ORDER BY CAT ASC"
              );

              while ($db->next_record()) {

             $tpl->set_var(array(
                 'VALUE_COMPTE' => $db->f('CATID'),
                 'NAME_COMPTE'  => $tools->Reduit_chaine($db->f('CAT'),__LENGTH_ACCOUNT__,0),
                 'SELECTED_1'   => $S_cat == $db->f('CATID') ? ' selected="selected"' : ''
             ));
             $tpl->set_var('BLOCK_form_select_third.tpl_GO_1',''); ## EMPTY THE VALUES FOR SECOND BOUCLE

             $other_db->query (
                  "SELECT CATID,THIRDID,THIRD
                  FROM ".$_MPM['table'][4]."
                  WHERE CATID='".$db->f('CATID')."'
                  AND USERID='$sess_pid'
                  ORDER BY THIRD ASC"
              );

          $Correl = '';
          while ($other_db->next_record()) {

           $this_cat   = $other_db->f('CATID');
           $this_third = $other_db->f('THIRDID');

           if ($db->f('CATID') == __PART_ID__) $Correl = '|'.SQL_SearchInThird(1,$this_third);

           if ($S_cat == $db->f('CATID').'|'.$this_third) $select2 = ' selected="selected"';
           else if ($S_cat == $db->f('CATID')."|".$this_third."$Correl") $select2 = ' selected="selected"';
           else $select2 = '';

          $tpl->set_var(array(
             'VALUE_COMPTES' => $db->f('CATID')."|".$this_third."$Correl",
             'NAME_COMPTES'  => $tools->Reduit_chaine($other_db->f('THIRD'),__LENGTH_ACCOUNT__,0),
             'SELECTED_2'    => $select2
          ));
          $tpl->parse('BLOCK_form_select_third.tpl_GO_1','BOUCLE_JS_SUB_CATEGORIE',true);

              if ($S_cat == $this_cat.'|'.__ANOTHER_ACCOUNT__) $select3 = ' selected="selected"';
              else $select3 = '';

                $tpl->set_var(array(
                  'LAST_NUMBER_IN'   => $this_cat != __PART_ID__ && $this_cat != __OPEN_PART__ ? $this_cat : '',
                  'SEPARATOR'        => $this_cat != __PART_ID__ && $this_cat != __OPEN_PART__ ? '|' : '',
                  'LAST_NUMBER_OUT'  => $this_cat != __PART_ID__ && $this_cat != __OPEN_PART__ ? __ANOTHER_ACCOUNT__ : '',
                  'LAST_ACCOUNT'     => $this_cat != __PART_ID__ && $this_cat != __OPEN_PART__
                                            ? '&nbsp;&nbsp; +--- '.$_VAR['ACCOUNT_ANOTHER'].' '.$_VAR['LANG_ACCOUNT_6'] : '',
                  'SELECTED_3'       => $this_cat != __PART_ID__ && $this_cat != __OPEN_PART__ ? $select3 : $select3
                ));
                } ## end of while $other_db

                $tpl->parse('BLOCK_form_select_third.tpl_GO_2','BOUCLE_JS_CATEGORIE',true);
         } ## end of while $db

    $_MPM['BeginMixed'] = array
    (
       'SELECTED_4' => $S_cat == __ANOTHER_ACCOUNT__.'|'.__ANOTHER_ACCOUNT__ ? ' selected="selected"' : ''
    );
    return XHTML_SetFile('form_select_third.tpl',$_MPM["BeginMixed"],3);
    }
} ## end of SQL_ListRecursive

// Recherche le nom du tiers
// @param $the_id = valeur de l'id tiers
function SQL_SearchThird($the_tiers) {
  Global $sess,$sess_pid,$_MPM,$other_db; $_MPM['Serial'][] = "SQL_SearchThird($the_tiers)";

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '') {
       $other_db->query (
               "SELECT THIRD FROM ".$_MPM['table'][4]."
               WHERE THIRDID='$the_tiers'
               AND USERID='$sess_pid'"
       );
       $other_db->next_record();
      return $other_db->f('THIRD');
     }
} ## end of SQL_SearchThird

// Recherche le nombre de tiers existant rattaché une categorie
// @param $third = le tiers recherche
function SQL_CountThird($third) {
   Global $sess,$sess_pid,$_MPM,$db; $_MPM['Serial'][] = "SQL_CountThird($third)";

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '') {
           $db->query (
                "SELECT COUNT(CATID) AS NUMBER_T FROM ".$_MPM['table'][4]."
                WHERE CATID='$third'
                AND USERID='$sess_pid'"
           );
           $db->next_record();
     return $db->f('NUMBER_T');
     }
} ## end of SQL_CountThird

// Creer le nouveau tiers
// @param $idtiers   = l'id du nouveau tiers
// @param $tcat      = l'id de la categorie
// @param $newstiers = le nouveau tiers
function SQL_InsertThird($idtiers,$tcat,$newstiers) {
   Global $sess,$sess_pid,$_MPM,$db; $_MPM['Serial'][] = "SQL_InsertThird($idtiers,$tcat,$newstiers)";

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '') {
          $db->query (
                 "INSERT INTO ".$_MPM['table'][4]."
                 (
                       THIRDID,
                       CATID,
                       USERID,
                       THIRD
                 )
                 VALUES ('$idtiers','$tcat','$sess_pid','$newstiers')"
           );
     }
} ## end of SQL_InsertThird

// Update le nouveau tiers
// @param $idtiers   = l'id du tiers
// @param $newstiers = le nom du tiers
function SQL_UpdateThird($idtiers,$newstiers) {
   Global $sess,$sess_pid,$_MPM,$db; $_MPM['Serial'][] = "SQL_UpdateThird($idtiers,$newstiers)";

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '') {
         $db->query (
             "UPDATE ".$_MPM['table'][4]."
             SET THIRD='$newstiers'
             WHERE USERID='$sess_pid'
             AND THIRDID='$idtiers'"
         );
     }
} ## end of SQL_UpdateThird

// Delete the third
// @param $set       = Option for the SET
// @param $w         = la valeur du WHERE
// @param $tset      = la valeur du set
function SQL_DeleteThird($set,$w,$tset) {
   Global $sess,$sess_pid,$_MPM,$db; $_MPM['Serial'][] = "SQL_DeleteThird($set,$w,$tset)";

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '') {
         if (isset($set) && $set == 1) {
           $Where      = "WHERE CATID='$w'";
           $Set        = "AND THIRDID='$tset'";
         }
         else if (isset($set) && $set == 2) {
           $Where      = "WHERE CATID='$w'";
           $Set        = '';
         }
         else if (isset($set) && $set == 3) {
           $Where      = "WHERE THIRDID='$w'";
           $Set        = "AND CATID='$tset'";
         }

          $db->query (
               "DELETE FROM ".$_MPM['table'][4]."
               $Where
               AND USERID='$sess_pid'
               $Set"
          );
     }
} ## end of SQL_DeleteThird

# --------------------------------*- $_MPM['table'][6] -*-------------------------------

// Retourne la ligne contenant toutes les preferences d'ordre des requetes sql
// Mais aussi le choix pour une page precise
// @param $page      = la page a rechercher
// @param $multiple  = si besoin de differencier plusieurs box sur la meme page
function SQL_Orderby($page='',$multiple) {
  Global $sess,$sess_pid,$_MPM,$other_db; $_MPM['Serial'][] = "SQL_Orderby($page,$multiple)";

   $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
   if ($sess_pid != '') {
    $other_db->query("SELECT ORDERBY FROM ".$_MPM['table'][6]." WHERE USERID='$sess_pid'");
      if ($other_db->num_rows() > 0) {
        $other_db->next_record();
           $things = explode(';',$other_db->f('ORDERBY'));
               while (list(,$thing) = each($things)) {
                 $t = explode('=',$thing);

                 $p = isset($t[0]) && $t[0] != '' ? $t[0] : '';
                 $k = isset($t[1]) && $t[1] != '' ? $t[1] : '';

            if ($p == $page) $this_list = $k;
            }
        $order_page = isset($this_list) && $this_list != '' ? $this_list : '';
        $order_list = $other_db->f('ORDERBY');
        }

      if (isset($GLOBALS['_POST']['orderby'.$multiple.'']) && is_array($GLOBALS['_POST']['orderby'.$multiple.''])) {
         while(list($cle,) = each($GLOBALS['_POST']['orderby'.$multiple.''])) {
            $result = explode('=',$cle);
            if ($result[0] == $page) {
               $GLOBALS['_POST']['order'.$multiple.''][$page] = $result[1];
            }
         }
      } ## end of is_isset && is_array()

      if (isset($order_page) && $order_page != '' && strpos($order_page, "_") !== false) {
           ## post exist
           if (isset($GLOBALS['_POST']['order'.$multiple.''][$page]) && $GLOBALS['_POST']['order'.$multiple.''][$page] != $order_page) {
             $GLOBALS['_POST']['order'.$multiple.''][$page] = $GLOBALS['_POST']['order'.$multiple.''][$page];
           }
           ## post not exist
           else {
              $GLOBALS['_POST']['order'.$multiple.''][$page] = $order_page;
          }
      } ## end of isset($order_page) ...

      if (isset($GLOBALS['_POST']['order'.$multiple.''][$page]) && strpos($GLOBALS['_POST']['order'.$multiple.''][$page], "_") !== false) {
      $actuel_page = $page."=".$GLOBALS['_POST']['order'.$multiple.''][$page].";";

         ## Une liste existe deja
         if (isset($order_list) && $order_list != '') {
            ## update en ajoutant
            if (isset($order_page) && $order_page == '') {
                SQL_InsertOrderby($order_list."".$actuel_page,1);
            }
            ## update en modifiant
            else if (isset($order_page) && $order_page != $GLOBALS['_POST']['order'.$multiple.''][$page]) {
             $old_page = $page."=".$order_page.";";
             $new_page = str_replace($old_page,$actuel_page,$order_list);
                SQL_InsertOrderby($new_page,1);
            } else {
            ## aucune action identique
            }
         }
         ## user existe deja !
         else if ($other_db->num_rows() > 0) {
            SQL_InsertOrderby($actuel_page,1);
         }
         ## Aucune liste existe
         else {
             SQL_InsertOrderby($actuel_page,2);
         }
      } ## end of if (isset($GLOBALS['_POST']['order'.$multiple.''][$page]) ....

   } ## end  of $sess_pid != ''
} ## end of SQL_Orderby

// Insere le choix de l'user dans la base
// Mais aussi le choix pour une page precise
// @param $np     = la page a ajouter
// @param $choice = update (1) ou insert (2)
function SQL_InsertOrderby($np='',$choice=0) {
  Global $sess,$sess_pid,$_MPM,$db; $_MPM['Serial'][] = "SQL_InsertOrderby($np,$choice)";

  $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
  if ($sess_pid != '') {
    if ($choice == 1) {
     $db->query("UPDATE ".$_MPM['table'][6]." SET ORDERBY ='$np' WHERE USERID='$sess_pid'");
    } ## end $choice 1
    if ($choice == 2) {
     $db->query("INSERT INTO ".$_MPM['table'][6]." (USERID,ORDERBY) VALUES ('$sess_pid','$np')");
    } ## end $choice 2
  }
} ## end of SQL_InsertOrderby

# --------------------------------*- ALL $_MPM['table'] -*------------------------------

// Verifie et creer la categorie virement
// si elle est modifier dans le fichier de lang
// alors on update la base pour mettre a jour son nom
function SQL_CreateVirement() {
 Global $sess,$sess_pid,$_MPM,$_VAR; $_MPM['Serial'][] = 'SQL_CreateVirement';

  $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
  if ($sess_pid != '') {
       $t = SQL_SearchCat(__PART_ID__);
       if (!$t && $_VAR['ACCOUNT_TRANSFERT'] != '') {
             SQL_InsertCat(__PART_ID__,$_VAR['ACCOUNT_TRANSFERT']);
       }
       else if ($_VAR['ACCOUNT_TRANSFERT'] != '' && $_VAR['ACCOUNT_TRANSFERT'] != $t) {
             SQL_UpdateCat($_VAR['ACCOUNT_TRANSFERT'],__PART_ID__);
       }
  }
} ## end of SQL_CreateVirement

// Verifie et creer la categorie ouverture de compte
// si elle est modifier dans le fichier de lang
// alors on update la base pour mettre a jour son nom
function SQL_CreateOpenCat() {
 Global $sess,$sess_pid,$_MPM,$_VAR; $_MPM['Serial'][] = 'SQL_CreateOpenCat';
  $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
  if ($sess_pid != '') {
       $t = SQL_SearchCat(__OPEN_PART__);
       if (!$t && $_VAR['OPEN_ACCOUNT_BEGIN_CAT'] != '') {
          SQL_InsertCat(__OPEN_PART__,$_VAR['OPEN_ACCOUNT_BEGIN_CAT']);
       }
       else if ($_VAR['OPEN_ACCOUNT_BEGIN_CAT'] != '' && $_VAR['OPEN_ACCOUNT_BEGIN_CAT'] != $t) {
          SQL_UpdateCat($_VAR['OPEN_ACCOUNT_BEGIN_CAT'],__OPEN_PART__);
       }
  }
} ## end of SQL_CreateOpenCat

// Verifie et creer le tiers solde de compte
// si elle est modifier dans le fichier de lang
// alors on update la base pour mettre a jour son nom
function SQL_CreateOpenThird() {
 Global $sess,$sess_pid,$_MPM,$_VAR; $_MPM['Serial'][] = 'SQL_CreateOpenThird';

  $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
  if ($sess_pid != '') {
       $t  = SQL_SearchIdThird(2,__OPEN_PART__,'');
       $td = SQL_SearchThird($t);
       if (!$t && $_VAR['LANG_BOOK_8'] != '') {
         $idtiers = SQL_RecupId(4);
         SQL_InsertThird($idtiers,__OPEN_PART__,$_VAR['LANG_BOOK_8']);
       }
       else if ($_VAR['LANG_BOOK_8'] != '' && $_VAR['LANG_BOOK_8'] != $td) {
          SQL_UpdateThird($t,$_VAR['LANG_BOOK_8']);
          SQL_UpdateComment();
       }
  }
} ## end of SQL_CreateOpenThird

// Retourne l'id du tiers solde de compte
function SQL_ReturnOpenThird() {
 Global $sess,$sess_pid,$_MPM,$_VAR; $_MPM['Serial'][] = 'SQL_ReturnOpenThird';

  $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
  if ($sess_pid != '') {
     $h = SQL_SearchIdThird(2,__OPEN_PART__,'');   ## Third
     if (!$h) {
          SQL_CreateOpenThird();
     $h = SQL_SearchIdThird(2,__OPEN_PART__,'');
     }
  return $h;
  }
} ## end of SQL_ReturnOpenThird

// construit l'ensemble des menu select et graphique de la home
// @param $id_pays    = l'id pays selectionner
// @param $this_graph = le choix du graphique
function SQL_HomeGraph($id_pays,$this_graph) {
  Global $sess,$sess_pid,$_MPM; $_MPM['Serial'][] = "SQL_HomeGraph($id_pays,$this_graph)";

  $a='';$b='';$c='';
  $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
  if ($sess_pid != '') {
     if (SQL_CountThird(__PART_ID__) > 0) {
          $a = XHTML_ConstrucGraph($id_pays,$this_graph);
     } else {
          $this_graph = 'default';
     }
     $c = SQL_ConstrucGraph($this_graph);
     $b = XHTML_Select(1,$id_pays,XML_TabRate());
   return $a.$b.$c;
   } ## end of if ($sess_pid != '')
} ## end of SQL_HomeGraph

// Insert le fichier backup
// @param $files    = nom du fichier
function SQL_InsertBackup($files) {
  Global $sess,$sess_pid,$_MPM,$tools,$db,$_VAR; $_MPM['Serial'][] = "SQL_InsertBackup($files)";

     $error     = 0;
     $SqlDump   = '';
     $SqlString = '';
     $NewSql    = array();
     $SqlSplit  = array();
     $SqlTable  = array();
     $SqlCount  = 0;

  $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
  if ($sess_pid != '') {
     if (isset($files)) {
     $SqlDump = fread(fopen($files, 'r'), filesize($files));

          if (get_magic_quotes_runtime() == 1) $SqlDump = stripslashes($SqlDump);

          $SqlDump       = trim($tools->Remove_Remarks($SqlDump));
          $SqlSplit      = $tools->Split_Sql_File($SqlDump, ';');
          $SqlCount      = count($SqlSplit);

          ## Ajout courou du 21/10/2002 afin de renforcer
          ## la verification de ce qui est envoyer
          $SqlTable  = explode('_',$_MPM['table'][0]);
          $SqlString = count($SqlTable) > 1 ? $SqlTable[0]  : '';

            for ($zz = 0; $zz < $SqlCount; $zz++) {
            $NewSql = trim($SqlSplit[$zz]);
               if (!empty($NewSql) && $NewSql[0] != '#') {

                   ## ERROR IN THE FILE SQL
                   if (!preg_match('/^(INSERT INTO '.$SqlString.')+/i',$NewSql)) {
                      $err = '<span class="menurouge">Error in : '.$NewSql.'</span>';
                      MPM_DisplayHandler($err);
                  $error = 2;
                  }
               }
            }

           if ($error != 2) {

                ## DELETE THE OLD DATA IT'S OK
                SQL_Record(0);

                for ($z = 0; $z < $SqlCount; $z++) {
                   $NewSql = trim($SqlSplit[$z]);
                   if (!empty($NewSql) && $NewSql[0] != '#') {
                          $db->query($NewSql);
                   }
                }
           $error = 1;
           }
     } else {
        $error = 0;
     } ## end of if (isset($files))

   $JsMess = '';
   if ($error == 0) $JsMess .= sprintf($_VAR['JS_DYNAMIQUE_55'],$files);
   if ($error == 1) $JsMess .= $_VAR['JS_DYNAMIQUE_56'];
   if ($error == 2) $JsMess .= sprintf($_VAR['JS_DYNAMIQUE_55'],$files);

  XHTML_DisplayJs($JsMess);
  return $error;
  } ## end if ($sess_pid != '')
} ## end of SQL_InsertBackup

// Récupère l'id suivant de la table selectionné
// @param $data = number of the database
function SQL_RecupId($data) {
 Global $sess,$sess_pid,$_MPM,$db; $_MPM['Serial'][] = "SQL_RecupId($data)";

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '' && isset($data) && is_int($data)) {
          switch($data) {
                  case 0 : $sqlmax = 'CATID';      break;
                  case 1 : $sqlmax = 'OPID';       break;
                  case 2 : $sqlmax = 'ACCOUNTID';  break;
                  case 4 : $sqlmax = 'THIRDID';    break;
          }
          $db->query (
                 "SELECT (MAX($sqlmax) +1) as ID_C
                 FROM ".$_MPM['table'][$data]."
                 WHERE USERID='$sess_pid'"
          );
          $db->next_record();

       $ids = $db->f('ID_C');
      return $ids == '' || !strstr($ids,$sess_pid) ? $sess_pid.'000'.$ids : $ids;
    } ## end if ($sess_pid != '')
} ## end of SQL_RecupId

// Verifier l'existence de la nouvelle categorie et la creer
// @param $newscat = la nouvelle categorie
// @param $idcat   = l'id de la nouvelle categorie
function SQL_BuildCat($newscat,$idcat) {
   Global $sess,$sess_pid,$_MPM; $_MPM['Serial'][] = "SQL_BuildCat($newscat,$idcat)";

   $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
   if ($sess_pid != '') {
          $_cat=SQL_IdCat($newscat);
          if ($_cat == '') {
               SQL_InsertCat($idcat,$newscat);
               $id_cat = $idcat;
          } else {
               $id_cat = $_cat;
          }
   return $id_cat;
   } ## end if ($sess_pid != '')
} ## end of SQL_BuildCat

// efface le compte selectionner et met a jour
// les comptes qui pourrait en dependre
// @param $val = compte
function SQL_DeleteUpdateAccount($val) {
  Global $sess,$sess_pid,$_MPM; $_MPM['Serial'][] = "SQL_DeleteUpdateAccount($val)";

   $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
   if ($sess_pid != '') {
       $this_tiers = SQL_SearchInThird(0,$val);
       SQL_DelAccount($val);
       SQL_DeleteThird(3,$this_tiers,__PART_ID__);
       SQL_DeleteAccount(1,'',$val,1);
       SQL_UpdateSolde(1,$this_tiers,1);
   } ## end if ($sess_pid != '')
} ## end of SQL_DeleteUpdateAccount

// Recherche la listes des colonnes et des donnees de l'user
// @param $the_table = Nom de la table
function SQL_SearchColums($the_table) {
  Global $sess,$sess_pid,$_MPM,$db,$tools; $_MPM['Serial'][] = "SQL_SearchColums($the_table)";

     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '') {
      $l_colonne = array();   $liste_colonne = '';
      $colonne   = array();   $liste_champs  = '';
      $l_champs  = array();   $liste         = '';

      $db->query("SELECT * FROM $the_table WHERE USERID='$sess_pid'");
      $db->num_rows();
      $l_colonne = $db->metadata($the_table,false);

            while ($db->next_record()) {
                for ($k=0; $k < count($l_colonne); $k++) {
                    $colonne[$k]  = $l_colonne[$k]['name'];
                    $l_champs[$k] = $db->f("$colonne[$k]");
                    $l_champs[$k] = $tools->add_slashes($l_champs[$k]);
                    $liste_colonne = "(`".join($colonne,"`, `")."`)";
                    $liste_champs = "('".join($l_champs,"', '")."');";
                 }
            $liste .= "INSERT INTO $the_table $liste_colonne VALUES $liste_champs\n";
            }
     return $liste;
     } ## end if ($sess_pid != '')
} ## end of SQL_SearchColums

// Création du dump pour la sauvegarde
function SQL_DumpDays() {
  Global $sess,$sess_user,$_MPM,$_VAR,$tpl,$db; $_MPM['Serial'][] = 'SQL_DumpDays';

     $sess_user = isset($sess_user) && is_object($sess) && $sess->is_registered('sess_user') ? $sess_user : '';
     if ($sess_user != '') {

              $_MPM['BeginMixed'] = array
              (
                   'PHP_VERSION'           => phpversion(),
                   'SERVER'                => $GLOBALS['_SERVER']['HTTP_HOST'],
                   'DUMP_WEB'              => $_MPM['header_DUMP_WEB'],
                   'DUMP_DEVELOPER'        => $_VAR['DUMP_DEVELOPER'],
                   'DUMP_SERVER'           => $_VAR['DUMP_SERVER'],
                   'DUMP_MADE'             => $_VAR['DUMP_MADE'],
                   'DUMP_VERSION_SERVER'   => $_VAR['DUMP_VERSION_SERVER'],
                   'DUMP_VERSION_PHP'      => $_VAR['DUMP_VERSION_PHP'],
                   'DUMP_NAME'             => $_VAR['DUMP_NAME'],
                   'DUMP_SEPARATOR'        => $_VAR['DUMP_SEPARATOR'],
                   'DATE'                  => $_MPM['date_dump'],
                   'USERNAME'              => $sess_user,
                   'MAIL'                  => $_MPM['header_MAIL'],
                   'DUMP_MESSAGE'          => sprintf($_VAR['DUMP_MESSAGE'],$_MPM['name'])
              );
              XHTML_SetFile('mysql_save.tpl','',0);

           $db->query("SELECT VERSION() AS VERSION_DB");
           $db->next_record();
           if ($db->num_rows() > 0) {
             $_MPM['BoucleMixed'] = array('CHECK_VERSION' => $db->f('VERSION_DB'));
           }

           $tpl->set_block('FILE_mysql_save.tpl','BOUCLE_DUMP','BOUCLE_mysql_save.tpl');
           ## no dump table $_MPM['table'][7] = 'MPM_quotes';
           for ($i=0; $i < 7; $i++) {
               $tpl->set_var(array(
                        'TABLE'            => $_MPM['table'][$i],
                         'REQUETE_LIST'    => SQL_SearchColums($_MPM['table'][$i])
               ));
           $tpl->parse('BOUCLE_mysql_save.tpl','BOUCLE_DUMP',true);
           }
           $_MPM['BeginMixed'] = array_merge($_MPM['BeginMixed'],$_MPM['BoucleMixed']);
     return XHTML_SetFile('mysql_save.tpl',$_MPM['BeginMixed'],3);
     } ## end if ($sess_pid != '')
} ## end of SQL_DumpDays

// Optimise toutes les tables
// ou supprimer tout les enregistrements d'un user
// @param $choice   = choix de l'action
function SQL_Record($choice) {
  Global $sess,$sess_pid,$_MPM,$db; $_MPM['Serial'][] = "SQL_Record($choice)";
     $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
     if ($sess_pid != '') {
       if (isset($choice) && $choice == 1) {
         $table_liste = join($_MPM['table'], " , ")." , ".$_MPM['table_phplib'];
         $db->query("OPTIMIZE TABLE $table_liste");
       } else {
         ## no delete table $_MPM['table'][7] = 'MPM_quotes';
         for ($i=0; $i<7; $i++) {
            $db->query(sprintf("DELETE FROM %s WHERE USERID='$sess_pid'",$_MPM['table'][$i]));
         }
       } ## end if (isset($choice) && $choice == 1)
     } ## end if ($sess_pid != '')
} ## end of SQL_Record

// Permet de modifier la table MPM_acct
// afin de supprimer le champs BALANCE
function SQL_AlterOpen() {
 Global $sess,$sess_pid,$db,$other_db,$_MPM,$_VAR; $_MPM['Serial'][] = 'SQL_AlterOpen';

   $sess_pid = isset($sess_pid) && is_object($sess) && $sess->is_registered('sess_pid') ? $sess_pid : '';
   if ($sess_pid != '') {
      ## Verif the number of account
      if (SQL_CountThird(__PART_ID__) > 0) {

         ## Check the table MPM_acct
         $field = $db->metadata($_MPM['table'][2],true);

         ## The field BALANCE exist table MPM_acct
         if ($field['num_fields'] == 4 && $field[3]['name'] == 'BALANCE') {

           ## Check the first day for table MPM_op
           $f = SQL_FirstDate();

           $a = bcsub(SQL_RecupId(1),1);                 ## Id for new account
           $g = __OPEN_PART__;                           ## Part
           $h = SQL_ReturnOpenThird();                   ## Third
           $j = $_VAR['OPEN_ACCOUNT_BEGIN_COMMENT'];     ## Comment

           ## Check the value for BALANCE table MPM_acct
           $db->query (
               "SELECT ACCOUNTID, BALANCE FROM ".$_MPM['table'][2]."
               WHERE USERID='$sess_pid' ORDER BY ACCOUNTID asc"
           );
              while ($db->next_record()) {
              $a = bcadd($a,1);
                     $m  = $db->f('ACCOUNTID');
                     $balance  = $db->f('BALANCE');

                     if (strpos($balance,'-')) {
                        $k = str_replace('-','',$balance);
                        $l = 0;
                     } else {
                        $k = 0;
                        $l = $balance;
                     }
                  ## Create the new operation for stockage the value
                  if ($balance != '') {
                     SQL_InsertAccount($a,'',1,1,$f,$g,$h,0,$j,$k,$l,$m,0,0);
                     $other_db->query("UPDATE ".$_MPM['table'][2]." SET BALANCE='' WHERE ACCOUNTID='$m' AND USERID='$sess_pid'");
                  SQL_RecupSolde($m);
                  }
               } ## end while

           ## Ok for alter table MPM_acct
           $true = false;
           $db->query("SELECT BALANCE FROM ".$_MPM['table'][2]);
               while ($db->next_record()) {
                  if ($db->f('BALANCE') != '') $true = true;
               }
           if (!$true) $db->query("ALTER TABLE ".$_MPM['table'][2]." DROP BALANCE");

         } ## end of $field['num_fields'] == 4 && $field[3]['name'] == 'BALANCE'
      } ## end of SQL_CountThird
   } ## end of if($sess_pid != "")
} ## end of SQL_AlterOpen()

# ------------------------------------*- Clean Query -*---------------------------------

function SQL_Clean ($parm) {
    
    if ( is_array($parm) || is_numeric($parm) ) {
    	return $parm;
    }

/*    $parm = strtolower($parm);
    $parm = preg_replace(
    sql_regcase(
    "/(from|select|insert|delete|where|drop table|show tables|#|\*|--|\\\\)/"),
    "",
    $parm);*/
    $parm = trim($parm);
    $parm = strip_tags($parm);
    $parm = get_magic_quotes_gpc() == 0 ? addslashes($parm) : $parm;
    $parm = preg_replace("/(--|\*|;|\#|\\\\)/", "", $parm);

    return $parm;

}
Return current item: MyPhpMoney