noalyss  Version-6.7.2
 All Data Structures Namespaces Files Functions Variables Enumerations
class_database.php
Go to the documentation of this file.
00001 <?php
00002 /*
00003  *   This file is part of NOALYSS.
00004  *
00005  *   NOALYSS is free software; you can redistribute it and/or modify
00006  *   it under the terms of the GNU General Public License as published by
00007  *   the Free Software Foundation; either version 2 of the License, or
00008  *   (at your option) any later version.
00009  *
00010  *   NOALYSS is distributed in the hope that it will be useful,
00011  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
00012  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00013  *   GNU General Public License for more details.
00014  *
00015  *   You should have received a copy of the GNU General Public License
00016  *   along with NOALYSS; if not, write to the Free Software
00017  *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
00018  */
00019 
00020 // Copyright Author Dany De Bontridder danydb@aevalys.eu
00021 
00022 /*!\file
00023  * \brief contains the class for connecting to a postgresql database
00024  */
00025 require_once('constant.php');
00026 require_once('ac_common.php');
00027 
00028 /*!\brief
00029  * This class allow you to connect to the postgresql database, execute sql, retrieve data
00030  *
00031  */
00032 class Database
00033 {
00034 
00035     private $db;                        /*!< database connection */
00036     private $ret;                       /*!< return value  */
00037     /*!\brief constructor
00038      *\param $p_database_id is the id of the dossier, or the modele following the
00039      * p_type if = 0 then connect to the repository
00040      *\param $p_type is 'DOS' (defaut) for dossier or 'MOD'
00041      */
00042     function __construct ($p_database_id=0,$p_type='dos')
00043     {
00044         if ( IsNumber($p_database_id) == false || strlen($p_database_id) > 5 )  die ("-->Dossier invalide [$p_database_id]");
00045         $noalyss_user=(defined ("noalyss_user"))?noalyss_user:phpcompta_user;
00046         $password=(defined("noalyss_password"))?noalyss_password:phpcompta_password;
00047         $port=(defined("noalyss_psql_port"))?noalyss_psql_port:phpcompta_psql_port;
00048         $host=( ! defined ("noalyss_psql_host") )?'127.0.0.1':noalyss_psql_host;
00049                 if (defined ("MULTI") && MULTI=="0") {
00050                          $noalyss_user = noalyss_user;
00051                         $password = noalyss_password;
00052                         $port = noalyss_psql_port;
00053                         $host = (!defined("noalyss_psql_host")) ? $host : noalyss_psql_host;
00054                         $l_dossier= dbname;
00055                 }
00056                 else
00057                 {
00058 
00059                         if ( $p_database_id == 0 )
00060                         { /* connect to the repository */
00061                                 $l_dossier=sprintf("%saccount_repository",strtolower(domaine));
00062                         }
00063                         else if ( $p_type == 'dos')
00064                         { /* connect to a folder (dossier) */
00065                                 $l_dossier=sprintf("%sdossier%d",strtolower(domaine),$p_database_id);
00066                         }
00067                         else if ($p_type=='mod')
00068                         {         /* connect to a template (modele) */
00069                                 $l_dossier=sprintf("%smod%d",strtolower(domaine),$p_database_id);
00070                         }
00071                         else if ($p_type=='template')
00072                         {
00073                                 $l_dossier='template1';
00074                         }
00075                         else
00076                         {
00077                                 throw new Exception ('Connection invalide');
00078                         }
00079                 }
00080 
00081         ob_start();
00082         $a=pg_connect("dbname=$l_dossier host='$host' user='$noalyss_user'
00083                       password='$password' port=$port");
00084 
00085         if ( $a == false )
00086         {
00087           if (DEBUG)
00088             {
00089               ob_end_clean();
00090               echo '<h2 class="error">Impossible de se connecter &agrave; postgreSql !</h2>';
00091               echo '<p>';
00092               echo "Vos param&egrave;tres sont incorrectes : <br>";
00093               echo "<br>";
00094               echo "base de donn&eacute;e : $l_dossier<br>";
00095               echo "Domaine : ".domaine."<br>";
00096               echo "Port $port <br>";
00097               echo "Utilisateur : $noalyss_user <br>";
00098               echo '</p>';
00099 
00100               exit ("Connection impossible : v&eacute;rifiez vos param&egrave;tres de base
00101                   de donn&eacute;es");
00102             }
00103           else
00104             {
00105               echo '<h2 class="error">Erreur de connexion !</h2>';
00106             }
00107 
00108         }
00109         $this->db=$a;
00110         if ( $this->exist_schema('comptaproc') )
00111             pg_exec($this->db,'set search_path to public,comptaproc;');
00112             pg_exec($this->db,'set DateStyle to ISO, MDY;');
00113         ob_end_clean();
00114     }
00115 
00116     public function verify()
00117     {
00118         // Verify that the elt we want to add is correct
00119     }
00120     function set_encoding($p_charset)
00121     {
00122         pg_set_client_encoding($this->db,$p_charset);
00123     }
00124     /*!
00125      * \brief send a sql string to the database
00126      * \param $p_string     sql string
00127      * \param $p_array array for the SQL string (see pg_query_params)
00128      * \return the result of the query, a resource or false if an
00129      * error occured
00130      */
00131     function exec_sql( $p_string,$p_array=null)
00132     {
00133         try
00134         {
00135 
00136             $this->sql=$p_string;
00137             $this->array=$p_array;
00138 
00139            if ( $p_array==null )
00140             {
00141               if ( ! DEBUG )
00142                 $this->ret=pg_query($this->db,$p_string);
00143               else
00144                 $this->ret=@pg_query($this->db,$p_string);
00145             }
00146             else
00147             {
00148                                 if ( !is_array($p_array))
00149                                 {
00150                                         throw new Exception("Erreur : exec_sql attend un array");
00151                                 }
00152               if ( ! DEBUG )
00153                 $this->ret=pg_query_params($this->db,$p_string,$p_array);
00154               else
00155                 $this->ret=@pg_query_params($this->db,$p_string,$p_array);
00156 
00157             }
00158             if ( ! $this->ret )
00159             {
00160                                 $str_error=pg_last_error($this->db). pg_result_error($this->ret);
00161                 throw new Exception ("  SQL ERROR $p_string ".$str_error,1 );
00162             }
00163 
00164         }
00165         catch (Exception  $a)
00166         {
00167             if (DEBUG)
00168             {
00169                 print_r ($p_string);
00170                 print_r($p_array);
00171                 echo $a->getMessage();
00172                 echo $a->getTrace();
00173                 echo $a->getTraceAsString();
00174                 echo pg_last_error($this->db);
00175             }
00176             throw ($a);
00177         }
00178 
00179         return $this->ret;
00180 
00181     }
00182     /*! \brief Count the number of row returned by a sql statement
00183      *
00184      * \param $p_sql sql string
00185      * \param $p_array if not null we use the safer pg_query_params
00186      */
00187 
00188     function count_sql($p_sql,$p_array=null)
00189     {
00190         $r_sql=$this->exec_sql($p_sql,$p_array);
00191         return pg_NumRows($r_sql);
00192     }
00193     /*!\brief get the current sequence value
00194      */
00195     function get_current_seq($p_seq)
00196     {
00197         $Res=$this->get_value("select currval('$p_seq') as seq");
00198         return $Res;
00199     }
00200 
00201 
00202     /*!\brief  get the next sequence value
00203      */
00204     function get_next_seq($p_seq)
00205     {
00206         $Res=$this->exec_sql("select nextval('$p_seq') as seq");
00207         $seq=pg_fetch_array($Res,0);
00208         return $seq['seq'];
00209     }
00210     /**
00211      * @ brief : start a transaction
00212      *
00213      */
00214 
00215     function start()
00216     {
00217         $Res=$this->exec_sql("start transaction");
00218     }
00219     /**
00220      * Commit the transaction
00221      *
00222      */
00223 
00224     function commit()
00225     {
00226         $Res=$this->exec_sql("commit");
00227     }
00228     /**
00229      * rollback the current transaction
00230      */
00231     function rollback()
00232     {
00233         $Res=$this->exec_sql("rollback");
00234     }
00235     /**
00236      * @brief alter the sequence value
00237      * @param $p_name name of the sequence
00238      * @param $min the start value of the sequence
00239      */
00240     function alter_seq($p_name,$min)
00241     {
00242         if ($min < 1) $min=1;
00243         $Res=$this->exec_sql("alter sequence $p_name restart $min");
00244     }
00245     /*!
00246      * \brief Execute a sql script
00247      * \param $script script name
00248      */
00249     function execute_script($script)
00250     {
00251 
00252         if ( ! DEBUG ) ob_start();
00253         $hf=fopen($script,'r');
00254         if ( $hf == false )
00255         {
00256             echo 'Ne peut ouvrir '.$script;
00257             exit();
00258         }
00259         $sql="";
00260         $flag_function=false;
00261         while (!feof($hf))
00262         {
00263             $buffer=fgets($hf);
00264             $buffer=str_replace ("$","\$",$buffer);
00265             print $buffer."<br>";
00266             // comment are not execute
00267             if ( substr($buffer,0,2) == "--" )
00268             {
00269                 //echo "comment $buffer";
00270                 continue;
00271             }
00272             // Blank Lines Are Skipped
00273             If ( Strlen($buffer)==0)
00274             {
00275                 //echo "Blank $buffer";
00276                 Continue;
00277             }
00278             if ( strpos(strtolower($buffer),"create function")===0 )
00279             {
00280                 echo "found a function";
00281                 $flag_function=true;
00282                 $sql=$buffer;
00283                 continue;
00284             }
00285             if ( strpos(strtolower($buffer),"create or replace function")===0 )
00286             {
00287                 echo "found a function";
00288                 $flag_function=true;
00289                 $sql=$buffer;
00290                 continue;
00291             }
00292             // No semi colon -> multiline command
00293             if ( $flag_function== false && strpos($buffer,';') == false )
00294             {
00295                 $sql.=$buffer;
00296                 continue;
00297             }
00298             if ( $flag_function )
00299             {
00300                 if ( strpos(strtolower($buffer), "language plpgsql") === false &&
00301                      strpos(strtolower($buffer), "language 'plpgsql'") === false )
00302                 {
00303                     $sql.=$buffer;
00304                     continue;
00305                 }
00306             }
00307             else
00308             {
00309                 // cut the semi colon
00310                 $buffer=str_replace (';','',$buffer);
00311             }
00312             $sql.=$buffer;
00313             if ( $this->exec_sql($sql) == false )
00314             {
00315                 $this->rollback();
00316                 if ( ! DEBUG ) ob_end_clean();
00317                 print "ERROR : $sql";
00318                 exit();
00319             }
00320             $sql="";
00321             $flag_function=false;
00322             print "<hr>";
00323         } // while (feof)
00324         fclose($hf);
00325         if ( ! DEBUG ) ob_end_clean();
00326     }
00327     /*!
00328      * \brief Get version of a database, the content of the
00329      *        table version
00330      *
00331      * \return version number
00332      *
00333      */
00334     function get_version()
00335     {
00336         $Res=$this->get_value("select val from version");
00337         return $Res;
00338     }
00339 
00340     /**
00341      *@brief fetch the $p_indice array from the last query
00342      *@param $p_indice index
00343      *
00344      */
00345     function fetch($p_indice)
00346     {
00347         if ( $this->ret == false ) throw new Exception ('this->ret is empty');
00348         return pg_fetch_array($this->ret,$p_indice ) ;
00349     }
00350     /*!@brief return the number of rows found by the last query, or the number
00351      * of rows from $p_ret
00352      * @param $p_ret is the result of a query, the default value is null, in that case
00353      * it is related to the last query
00354      * @note synomym for count()
00355      */
00356     function size($p_ret = null)
00357     {
00358         if ($p_ret == null )
00359             return pg_NumRows($this->ret);
00360         else
00361             return pg_NumRows($p_ret);
00362     }
00363     /*!@brief       synomym for size()*/
00364     function count($p_ret=null)
00365     {
00366         return $this->size($p_ret);
00367     }
00368 
00369     /*!\brief loop to apply all the path to a folder or
00370      *         a template
00371      * \param $p_name database name
00372      * \param $from_setup == 1 if called from setup.php
00373      *
00374      */
00375     function apply_patch($p_name,$from_setup=1)
00376     {
00377         $MaxVersion=DBVERSION-1;
00378                 $succeed="<span style=\"font-size:18px;color:green\">&#x2713;</span>";
00379         echo '<ul style="list-type-style:square">';
00380         $add=($from_setup==0)?'admin/':'';
00381         for ( $i = 4;$i <= $MaxVersion;$i++)
00382         {
00383             $to = $i + 1;
00384 
00385                         if ($this->get_version() <= $i)
00386                         {
00387                                 if ($this->get_version() == 97)
00388                                 {
00389                                         if ($this->exist_schema("amortissement"))
00390                                         {
00391                                                 $this->exec_sql('ALTER TABLE amortissement.amortissement_histo
00392                                                         ADD CONSTRAINT internal_fk FOREIGN KEY (jr_internal) REFERENCES jrn (jr_internal)
00393                                                         ON UPDATE CASCADE ON DELETE SET NULL');
00394                                         }
00395                                 }
00396                 echo "<li>Patching ".$p_name.
00397                 " from the version ".$this->get_version()." to $to ";
00398 
00399                 $this->execute_script($add.'sql/patch/upgrade'.$i.'.sql');
00400                 echo $succeed;
00401 
00402                 if ( ! DEBUG ) ob_start();
00403                 // specific for version 4
00404                 if ( $i == 4 )
00405                 {
00406                     $sql="select jrn_def_id from jrn_def ";
00407                     $Res=$this->exec_sql($sql);
00408                     $Max=$this->size();
00409                     for ($seq=0;$seq<$Max;$seq++)
00410                     {
00411                         $row=pg_fetch_array($Res,$seq);
00412                         $sql=sprintf ("create sequence s_jrn_%d",$row['jrn_def_id']);
00413                         $this->exec_sql($sql);
00414                     }
00415                 }
00416                 // specific to version 7
00417                 if ( $i == 7 )
00418                 {
00419                     // now we use sequence instead of computing a max
00420                     //
00421                     $Res2=$this->exec_sql('select coalesce(max(jr_grpt_id),1) as l from jrn');
00422                     $Max2= pg_NumRows($Res2) ;
00423                     if ( $Max2 == 1)
00424                     {
00425                         $Row=pg_fetch_array($Res2,0);
00426                         var_dump($Row);
00427                         $M=$Row['l'];
00428                         $this->exec_sql("select setval('s_grpt',$M,true)");
00429                     }
00430                 }
00431                 // specific to version 17
00432                 if ( $i == 17 )
00433                 {
00434                     $this->execute_script($add.'sql/patch/upgrade17.sql');
00435                     $max=$this->get_value('select last_value from s_jnt_fic_att_value');
00436                     $this->alter_seq($p_cn,'s_jnt_fic_att_value',$max+1);
00437                 } // version
00438 
00439                 // reset sequence in the modele
00440                 //--
00441                 if ( $i == 30 && $p_name=="mod" )
00442                 {
00443                     $a_seq=array('s_jrn','s_jrn_op','s_centralized',
00444                                  's_stock_goods','c_order','s_central');
00445                     foreach ($a_seq as $seq )
00446                     {
00447                         $sql=sprintf("select setval('%s',1,false)",$seq);
00448                         $Res=$this->exec_sql($sql);
00449                     }
00450                     $sql="select jrn_def_id from jrn_def ";
00451                     $Res=$this->exec_sql($sql);
00452                     $Max=pg_NumRows($Res);
00453                     for ($seq=0;$seq<$Max;$seq++)
00454                     {
00455                         $row=pg_fetch_array($Res,$seq);
00456                         $sql=sprintf ("select setval('s_jrn_%d',1,false)",$row['jrn_def_id']);
00457                         $this->exec_sql($sql);
00458                     }
00459 
00460                 }
00461                 if ( $i == 36 )
00462                 {
00463                     /* check the country and apply the path */
00464                     $res=$this->exec_sql("select pr_value from parameter where pr_id='MY_COUNTRY'");
00465                     $country=pg_fetch_result($res,0,0);
00466                     $this->execute_script($add."sql/patch/upgrade36.".$country.".sql");
00467                     $this->exec_sql('update tmp_pcmn set pcm_type=find_pcm_type(pcm_val)');
00468                 }
00469                 if ($i == 59 )
00470                 {
00471                     $res=$this->exec_sql("select pr_value from parameter where pr_id='MY_COUNTRY'");
00472                     $country=pg_fetch_result($res,0,0);
00473                     if ( $country == 'BE') $this->exec_sql("insert into parm_code values ('SUPPLIER',440,'Poste par défaut pour les fournisseurs')");
00474                     if ($country=='FR') $this->exec_sql("insert into parm_code values ('SUPPLIER',400,'Poste par défaut pour les fournisseurs')");
00475                 }
00476                 if ( $i == 61 )
00477                 {
00478                     $country=$this->get_value ("select pr_value from parameter where pr_id='MY_COUNTRY'");
00479                     $this->execute_script($add."sql/patch/upgrade61.".$country.".sql");
00480                 }
00481 
00482                 if ( ! DEBUG ) ob_end_clean();
00483             }
00484         }
00485         echo '</ul>';
00486     }
00487     /*!\brief return the value of the sql, the sql will return only one value
00488      *        with the value
00489      * \param $p_sql the sql stmt example :select s_value from
00490      document_state where s_id=2
00491      *\param $p_array if array is not null we use the ExecSqlParm (safer)
00492      *\see exec_sql
00493      *\note print a warning if several value are found, if only the first value is needed
00494      * consider using a LIMIT clause
00495      * \return only the first value or an empty string if nothing is found
00496      */
00497     function get_value($p_sql,$p_array=null)
00498     {
00499         $this->ret=$this->exec_sql($p_sql,$p_array);
00500         $r= pg_NumRows($this->ret);
00501         if ( $r == 0 ) return "";
00502         if ( $r > 1 )
00503           {
00504             $array=pg_fetch_all($this->ret);
00505             throw new Exception( "Attention $p_sql retourne ".pg_NumRows($this->ret)."  valeurs ".
00506                                var_export($p_array,true)." values=".var_export($array,true));
00507           }
00508         $r=pg_fetch_row($this->ret,0);
00509         return $r[0];
00510 
00511     }
00512     /*!\brief  purpose return the result of a sql statment
00513      * in a array
00514      * \param $p_sql sql query
00515      * \param $p_array if not null we use ExecSqlParam
00516      *\return an empty array if nothing is found
00517      */
00518     function get_array($p_sql,$p_array=null)
00519     {
00520         $r=$this->exec_sql($p_sql,$p_array);
00521 
00522         if ( ($Max=  pg_NumRows($r)) == 0 ) return array();
00523         $array=pg_fetch_all($r);
00524         return $array;
00525     }
00526 
00527     function create_sequence($p_name,$min=1)
00528     {
00529         if ($min < 1) $min=1;
00530         $sql="create sequence ".$p_name." minvalue $min";
00531         $this->exec_sql($sql);
00532     }
00533     /*!\brief test if a sequence exist */
00534     /* \return true if the seq. exist otherwise false
00535      */
00536     function exist_sequence($p_name)
00537     {
00538         $r=$this->count_sql("select relname from pg_class where relname=lower($1)",array($p_name));
00539         if ( $r==0)
00540             return false;
00541         return true;
00542     }
00543     /*!\brief test if a table exist
00544      *\param $p_name table name
00545      *\param  $schema name of the schema default public
00546      * \return true if a table exist otherwise false
00547      */
00548     function exist_table($p_name,$p_schema='public')
00549     {
00550         $r=$this->count_sql("select table_name from information_schema.tables where table_schema=$1 and table_name=lower($2)", array($p_schema,$p_name));
00551         if ( $r==0)
00552             return false;
00553         return true;
00554     }
00555     /**
00556      * Check if a column exists in a table
00557      * @param $col : column name
00558      * @param $table :table name
00559      * @param $schema :schema name, default public
00560      *@return true or false
00561      */
00562     function exist_column($col,$table,$schema)
00563     {
00564         $r=$this->get_value('select count(*) from information_schema.columns where table_name=lower($1) and column_name=lower($2) and table_schema=lower($3)',
00565                             array($col,$table,$schema));
00566         if ( $r > 0 ) return true;
00567         return false;
00568     }
00569     /**
00570      * return the name of the database with the domain name
00571      * @param $p_id of the folder WITHOUT the domain name
00572      * @param $p_type dos for folder mod for template
00573      * @return formatted name
00574      */
00575     function format_name($p_id,$p_type)
00576     {
00577         switch ($p_type)
00578         {
00579             case 'dos':
00580                 $sys_name=sprintf("%sdossier%d",strtolower(domaine),$p_id);
00581                 break;
00582             case 'mod':
00583                 $sys_name=sprintf("%smod%d",strtolower(domaine),$p_id);
00584                 break;
00585             default:
00586                 echo_error(__FILE__." format_name invalid type ".$p_type, __LINE__);
00587                 exit();
00588         }
00589         return $sys_name;
00590     }
00591     /**
00592      * Count the database name in a system view
00593      * @param $p_name string database name
00594      * @return number of database found (normally 0 or 1)
00595      */
00596     function exist_database($p_name)
00597     {
00598         $database_exist=$this->get_value('select count(*)
00599                 from pg_catalog.pg_database where datname = lower($1)',array($p_name));
00600         return $database_exist;
00601     }
00602     /**
00603      *@brief check if the large object exists
00604      *@param $p_oid of the large object
00605      *@return return true if the large obj exist or false if not
00606      */
00607     function exist_blob($p_oid)
00608     {
00609         $r=$this->get_value('select count(loid) from pg_largeobject where loid=$1'
00610                             ,array($p_oid)  );
00611         if ($r > 0) return true;
00612         else return false;
00613     }
00614     /*
00615      *!\brief test if a view exist
00616      * \return true if the view. exist otherwise false
00617      */
00618     function exist_view($p_name)
00619     {
00620         $r=$this->count_sql("select viewname from pg_views where viewname=lower($1)",array($p_name));
00621         if ( $r==0)
00622             return false;
00623         return true;
00624     }
00625     /*
00626      *!\brief test if a schema exists
00627      * \return true if the schemas exists otherwise false
00628      */
00629     function exist_schema($p_name)
00630     {
00631         $r=$this->count_sql("select nspname from pg_namespace where nspname=lower($1)",array($p_name));
00632         if ( $r==0)
00633             return false;
00634         return true;
00635     }
00636     /*!
00637      *\brief create a string containing the value separated by comma
00638      * for use in a SQL in statement
00639      *\return the string or empty if nothing is found
00640      *\see fid_card.php
00641      */
00642     function make_list($sql,$p_array=null)
00643     {
00644         if ( $p_array == null )
00645         {
00646             $aArray=$this->get_array($sql);
00647         }
00648         else
00649         {
00650             $aArray=$this->get_array($sql,$p_array);
00651         }
00652         if (empty ($aArray) ) return "";
00653         $aIdx=array_keys($aArray[0]);
00654         $idx=$aIdx[0];
00655         $ret="";
00656         $f="";
00657         for ($i = 0; $i < count($aArray);$i++)
00658         {
00659             $row=$aArray[$i];
00660             $ret.=$f.$aArray[$i][$idx];
00661             $f=',';
00662         }
00663         $ret=trim($ret,',');
00664         return $ret;
00665     }
00666     /*!
00667      * \brief make a array with the sql
00668      *
00669      * \param $p_sql  sql statement, only the first two column will be returned in
00670      *  an array. The first col. is the label and the second the value
00671      *  \param $p_null if the array start with a null value
00672      *\note this function is used with ISelect when it is needed to have a list of
00673      * options
00674      * \return: a double array like
00675      \verbatim
00676     Array
00677     (
00678     [0] => Array
00679         (
00680             [value] => 1
00681             [label] => Marchandise A
00682         )
00683 
00684     [1] => Array
00685         (
00686             [value] => 2
00687             [label] => Marchandise B
00688         )
00689 
00690     [2] => Array
00691         (
00692             [value] => 3
00693             [label] => Marchandise C
00694         )
00695     )
00696      \endverbatim
00697      * \see ISelect
00698      */
00699     function make_array($p_sql,$p_null=0)
00700     {
00701         $a=$this->exec_sql($p_sql);
00702         $max=pg_NumRows($a);
00703         if ( $max==0 && $p_null==0) return null;
00704         for ($i=0;$i<$max;$i++)
00705         {
00706             $row=pg_fetch_row($a);
00707             $r[$i]['value']=$row[0];
00708             $r[$i]['label']=h($row[1]);
00709         }
00710         // add a blank item ?
00711         if ( $p_null == 1 )
00712         {
00713             for ($i=$max;$i!=0;$i--)
00714             {
00715                 $r[$i]['value']=    $r[$i-1]['value'];
00716                 $r[$i]['label']=    h($r[$i-1]['label']);
00717             }
00718             $r[0]['value']=-1;
00719             $r[0]['label']=" ";
00720         } //   if ( $p_null == 1 )
00721 
00722         return $r;
00723     }
00724     /*!
00725      * \brief Save a "piece justificative"
00726      *
00727      * \param $seq jr_grpt_id
00728      * \return $oid of the lob file if success
00729      *         null if a error occurs
00730      *
00731      */
00732     function save_upload_document ($seq)
00733     {
00734         /* there is
00735         no file to
00736         upload */
00737         if ($_FILES["pj"]["error"] == UPLOAD_ERR_NO_FILE )
00738         {
00739             return;
00740         }
00741 
00742         $new_name=tempnam($_ENV['TMP'],'pj');
00743         if ($_FILES["pj"]["error"] > 0)
00744         {
00745             print_r($_FILES);
00746             echo_error(__FILE__.":".__LINE__."Error: " . $_FILES["pj"]["error"] );
00747         }
00748         if ( strlen ($_FILES['pj']['tmp_name']) != 0 )
00749         {
00750             if (move_uploaded_file($_FILES['pj']['tmp_name'],
00751                                    $new_name))
00752             {
00753                 // echo "Image saved";
00754                 $oid= pg_lo_import($this->db,$new_name);
00755                 if ( $oid == false )
00756                 {
00757                     echo_error('postgres.php',__LINE__,"cannot upload document");
00758                     $this->rollback();
00759                     return;
00760                 }
00761                 // Remove old document
00762                 $ret=$this->exec_sql("select jr_pj from jrn where jr_grpt_id=$seq");
00763                 if (pg_num_rows($ret) != 0)
00764                 {
00765                     $r=pg_fetch_array($ret,0);
00766                     $old_oid=$r['jr_pj'];
00767                     if (strlen($old_oid) != 0)
00768                         pg_lo_unlink($cn,$old_oid);
00769                 }
00770                 // Load new document
00771                 $this->exec_sql("update jrn set jr_pj=".$oid.", jr_pj_name='".$_FILES['pj']['name']."', ".
00772                                 "jr_pj_type='".$_FILES['pj']['type']."'  where jr_grpt_id=$seq");
00773                 return $oid;
00774 
00775             }
00776             else
00777             {
00778                 echo "<H1>Error</H1>";
00779                 $this->rollback();
00780 
00781             }
00782         }
00783         return 0;
00784     }
00785     /*!\brief wrapper for the function pg_NumRows
00786      *\param $ret is the result of a exec_sql
00787      *\return number of line affected
00788      */
00789     static function num_row($ret)
00790     {
00791         return pg_NumRows($ret);
00792     }
00793 
00794 
00795     /*!\brief wrapper for the function pg_fetch_array
00796      *\param $ret is the result of a pg_exec
00797      *\param $p_indice is the index
00798      *\return $array of column
00799      */
00800     static function fetch_array($ret,$p_indice=0)
00801     {
00802         return pg_fetch_array($ret,$p_indice);
00803     }
00804 
00805     /*!\brief wrapper for the function pg_fetch_all
00806      *\param $ret is the result of pg_exec (exec_sql)
00807      *\return double array (row x col )
00808      */
00809     static function fetch_all($ret)
00810     {
00811         return pg_fetch_all($ret);
00812     }
00813 
00814     /*!\brief wrapper for the function pg_fetch_all
00815      *\param $ret is the result of pg_exec (exec_sql)
00816      *\param $p_row is the indice of the row
00817      *\param $p_col is the indice of the col
00818      *\return a string or an integer
00819      */
00820     static function fetch_result($ret,$p_row=0,$p_col=0)
00821     {
00822         return pg_fetch_result($ret,$p_row,$p_col);
00823     }
00824     /*!\brief wrapper for the function pg_fetch_row
00825      *\param $ret is the result of pg_exec (exec_sql)
00826      *\param $p_row is the indice of the row
00827      *\return an array indexed from 0
00828      */
00829     static function fetch_row($ret,$p_row)
00830     {
00831         return pg_fetch_row($ret,$p_row);
00832     }
00833 
00834     /*!\brief wrapper for the function pg_lo_unlink
00835      *\param $p_oid is the of oid
00836      *\return return the result of the operation
00837      */
00838     function lo_unlink($p_oid)
00839     {
00840         return pg_lo_unlink($this->db,$p_oid);
00841     }
00842 
00843     /*!\brief wrapper for the function pg_prepare
00844      *\param $p_string string name for pg_prepare function
00845      *\param $p_sql  is the sql to prepare
00846      *\return return the result of the operation
00847      */
00848     function prepare($p_string,$p_sql)
00849     {
00850         return pg_prepare($this->db,$p_string,$p_sql);
00851     }
00852     /*!\brief wrapper for the function pg_execute
00853      *\param $p_string string name of the stmt given in pg_prepare function
00854      *\param $p_array contains the variables
00855      *\note set this->ret to the return of pg_execute
00856      *\return return the result of the operation,
00857      */
00858     function execute($p_string,$p_array)
00859     {
00860         $this->ret=pg_execute($this->db,$p_string,$p_array);
00861         return $this->ret;
00862     }
00863 
00864     /*!\brief wrapper for the function pg_lo_export
00865      *\param $p_oid is the oid of the log
00866      *\param $tmp  is the file
00867      *\return result of the operation
00868      */
00869     function lo_export($p_oid,$tmp)
00870     {
00871         return pg_lo_export($this->db,$p_oid,$tmp);
00872     }
00873     /*!\brief wrapper for the function pg_lo_export
00874      *\param $p_oid is the oid of the log
00875      *\param $tmp  is the file
00876      *\return result of the operation
00877      */
00878     function lo_import($p_oid)
00879     {
00880         return pg_lo_import($this->db,$p_oid);
00881     }
00882 
00883     /*!\brief wrapper for the function pg_escape_string
00884      *\param $p_string is the string to escape
00885      *\return escaped string
00886      */
00887     static function escape_string($p_string)
00888     {
00889         return pg_escape_string($p_string);
00890     }
00891     /*!\brief wrapper for the function pg_close
00892      */
00893     function close()
00894     {
00895         pg_close($this->db);
00896     }
00897     /*!\brief
00898      *\param
00899      *\return
00900      *\note
00901      *\see
00902      */
00903     function __toString()
00904     {
00905         return "database ";
00906     }
00907     static function test_me()
00908     {}
00909     function status()
00910     {
00911       return pg_transaction_status($this->db);
00912     }
00913     /**
00914      * with the handle of a successull query, echo each row into CSV and
00915      * send it directly
00916      * @param type $ret handle to a query
00917      * @param type $aheader  double array, each item of the array contains
00918      * a key type (num) and a key title
00919      */
00920     function query_to_csv($ret,$aheader)
00921     {
00922         $seq="";
00923         for ($i=0;$i<count($aheader);$i++)
00924         {
00925             echo $seq.'"'.$aheader[$i]['title'].'"';
00926             $seq=";";
00927         }
00928         printf("\n\r");
00929         // fetch all the rows
00930         for ($i=0;$i<Database::num_row($ret);$i++)
00931         {
00932             $row=Database::fetch_array($ret, $i);
00933             $sep2="";
00934             // for each rows, for each value
00935             for ($e=0;$e<count($row)/2;$e++)
00936             {
00937                switch ($aheader[$e]['type'])
00938                 {
00939                     case 'num':
00940                         echo $sep2.nb($row[$e]);
00941                         break;
00942                     default:
00943                         echo $sep2.'"'.$row[$e].'"';
00944                 }
00945                 $sep2=";";
00946             }
00947             printf("\n\r");
00948         }
00949     }
00950 }
00951 
00952 /* test::test_me(); */
 All Data Structures Namespaces Files Functions Variables Enumerations