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