class_document.php

Go to the documentation of this file.
00001 <?php
00002 /*
00003  *   This file is part of PhpCompta.
00004  *
00005  *   PhpCompta 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  *   PhpCompta 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 PhpCompta; if not, write to the Free Software
00017  *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
00018 */
00019 /* $Revision: 4896 $ */
00020 // Copyright Author Dany De Bontridder ddebontridder@yahoo.fr
00021 require_once('class_own.php');
00022 require_once('class_acc_account_ledger.php');
00023 require_once('class_follow_up.php');
00024 require_once('class_acc_tva.php');
00025 require_once('class_user.php');
00026 require_once('class_zip_extended.php');
00027 
00028 /*! \file
00029  * \brief Class Document corresponds to the table document
00030  */
00031 /*! \brief Class Document corresponds to the table document
00032  */
00033 class Document
00034 {
00035     var $db;          /*!< $db Database connexion*/
00036     var $d_id;        /*!< $d_id Document id */
00037     var $ag_id;       /*!< $ag_id action_gestion.ag_id (pk) */
00038     var $d_mimetype;  /*!< $d_mimetype  */
00039     var $d_filename;  /*!< $d_filename */
00040     var $d_lob;       /*!< $d_lob the oid of the lob */
00041     var $d_number;    /*!< $d_number number of the document */
00042     var $md_id;       /*!< $md_id document's template */
00043     /* Constructor
00044      * \param $p_cn Database connection
00045      */
00046     function Document($p_cn,$p_d_id=0)
00047     {
00048         $this->db=$p_cn;
00049         $this->d_id=$p_d_id;
00050     }
00051     /*!\brief insert a minimal document and set the d_id
00052      */
00053     function blank()
00054     {
00055         $this->d_id=$this->db->get_next_seq("document_d_id_seq");
00056         // affect a number
00057         $this->d_number=$this->db->get_next_seq("seq_doc_type_".$this->md_type);
00058         $sql=sprintf('insert into document(d_id,ag_id,d_number) values(%d,%d,%d)',
00059                      $this->d_id,
00060                      $this->ag_id,
00061                      $this->d_number);
00062         $this->db->exec_sql($sql);
00063 
00064     }
00065 
00066     /*!
00067      * \brief Generate the document, Call $this->Replace to replace
00068      *        tag by value
00069      *\p_array contains the data normally it is the $_POST
00070      *
00071      * \return an array : the url where the generated doc can be found, the name
00072      * of the file and his mimetype
00073      */
00074     function Generate($p_array)
00075     {
00076         // create a temp directory in /tmp to unpack file and to parse it
00077         $dirname=tempnam($_ENV['TMP'],'doc_');
00078 
00079 
00080         unlink($dirname);
00081         mkdir ($dirname);
00082         // Retrieve the lob and save it into $dirname
00083         $this->db->start();
00084         $dm_info="select md_name,md_type,md_lob,md_filename,md_mimetype
00085                  from document_modele where md_id=".$this->md_id;
00086         $Res=$this->db->exec_sql($dm_info);
00087 
00088         $row=Database::fetch_array($Res,0);
00089         $this->d_lob=$row['md_lob'];
00090         $this->d_filename=$row['md_filename'];
00091         $this->d_mimetype=$row['md_mimetype'];
00092         $this->d_name=$row['md_name'];
00093 
00094 
00095         chdir($dirname);
00096         $filename=$row['md_filename'];
00097         $exp=$this->db->lo_export($row['md_lob'],$dirname.DIRECTORY_SEPARATOR.$filename);
00098         if ( $exp === false ) echo_warning( __FILE__.":".__LINE__."Export NOK $filename");
00099 
00100         $type="n";
00101         // if the doc is a OOo, we need to unzip it first
00102         // and the name of the file to change is always content.xml
00103         if ( strpos($row['md_mimetype'],'vnd.oasis') != 0 )
00104         {
00105             ob_start();
00106             $zip = new Zip_Extended;
00107             if ($zip->open($filename) === TRUE) {
00108               $zip->extractTo($dirname.DIRECTORY_SEPARATOR);
00109               $zip->close();
00110             } else {
00111               echo __FILE__.":".__LINE__."cannot unzip model ".$filename;
00112             }
00113 
00114             // Remove the file we do  not need anymore
00115             unlink($filename);
00116             ob_end_clean();
00117             $file_to_parse="content.xml";
00118             $type="OOo";
00119         }
00120         else
00121             $file_to_parse=$filename;
00122         // affect a number
00123         $this->d_number=$this->db->get_next_seq("seq_doc_type_".$row['md_type']);
00124 
00125         // parse the document - return the doc number ?
00126         $this->ParseDocument($dirname,$file_to_parse,$type,$p_array);
00127 
00128         $this->db->commit();
00129         // if the doc is a OOo, we need to re-zip it
00130         if ( strpos($row['md_mimetype'],'vnd.oasis') != 0 )
00131         {
00132             ob_start();
00133             $zip = new Zip_Extended;
00134             $res = $zip->open($filename, ZipArchive::CREATE);
00135             if($res !== TRUE)
00136               {
00137                 echo __FILE__.":".__LINE__."cannot recreate zip";
00138                 exit;
00139               }
00140             $zip->add_recurse_folder($dirname.DIRECTORY_SEPARATOR);
00141             $zip->close();
00142 
00143             ob_end_clean();
00144 
00145             $file_to_parse=$filename;
00146         }
00147 
00148         $this->SaveGenerated($dirname.DIRECTORY_SEPARATOR.$file_to_parse);
00149         // Invoice
00150         $ret='<A class="mtitle" HREF="show_document.php?d_id='.$this->d_id.'&'.dossier::get().'">Document g&eacute;n&eacute;r&eacute;</A>';
00151         @rmdir($dirname);
00152         return $ret;
00153     }
00154 
00155     /*! ParseDocument
00156      * \brief This function parse a document and replace all
00157      *        the predefined tags by a value. This functions
00158      *        generate diffent documents (invoice, order, letter)
00159      *        with the info from the database
00160      *
00161      * \param $p_dir directory name
00162      * \param $p_file filename
00163      * \param $p_type For the OOo document the tag are &lt and &gt instead of < and >
00164      * \param $p_array variable from $_POST
00165      */
00166     function ParseDocument($p_dir,$p_file,$p_type,$p_array)
00167     {
00168 
00169         /*!\note Replace in the doc the tags by their values.
00170          *  - MY_*   table parameter
00171          *  - ART_VEN* table quant_sold for invoice
00172          *  - CUST_* table quant_sold and fiche for invoice
00173          *  - e_* for the invoice in the $_POST
00174          */
00175         // open the document
00176         $infile_name=$p_dir.DIRECTORY_SEPARATOR.$p_file;
00177         $h=fopen($infile_name,"r");
00178 
00179         // check if tmpdir exist otherwise create it
00180         $temp_dir=$_SERVER["DOCUMENT_ROOT"].DIRECTORY_SEPARATOR.'tmp';
00181         if ( is_dir($temp_dir) == false )
00182         {
00183             if ( mkdir($temp_dir) == false )
00184             {
00185                 echo "Ne peut pas créer le répertoire ".$temp_dir;
00186                 exit();
00187             }
00188         }
00189         // Compute output_name
00190         $output_name=tempnam($temp_dir,"gen_doc_");
00191         $output_file=fopen($output_name,"w+");
00192         // check if the opening is sucessfull
00193         if (  $h === false )
00194         {
00195             echo __FILE__.":".__LINE__."cannot open $p_dir $p_file ";
00196             exit();
00197         }
00198         if ( $output_file == false)
00199         {
00200             echo "ne peut pas ouvrir le fichier de sortie";
00201             exit();
00202         }
00203         // compute the regex
00204         if ( $p_type=='OOo')
00205         {
00206             $regex="/=*&lt;&lt;[A-Z]+_*[A-Z]*_*[A-Z]*_*[A-Z]*_*[0-9]*&gt;&gt;/i";
00207             $lt="&lt;";
00208             $gt="&gt;";
00209         }
00210         else
00211         {
00212             $regex="/=*<<[A-Z]+_*[A-Z]*_*[A-Z]*_*[A-Z]*_*[0-9]*>>/i";
00213             $lt="<";
00214             $gt=">";
00215         }
00216 
00217         //read the file
00218         while(! feof($h))
00219           {
00220             // replace the tag
00221             $buffer=fgets($h);
00222             // search in the buffer the magic << and >>
00223             // while preg_match_all finds something to replace
00224             while ( preg_match_all ($regex,$buffer,$f) >0  )
00225               {
00226 
00227 
00228                 foreach ( $f as $apattern )
00229                   {
00230 
00231 
00232                     foreach($apattern as $pattern)
00233                       {
00234 
00235 
00236                         $to_remove=$pattern;
00237                         // we remove the < and > from the pattern
00238                         $pattern=str_replace($lt,'',$pattern);
00239                         $pattern=str_replace($gt,'',$pattern);
00240 
00241 
00242                         // if the pattern if found we replace it
00243                         $value=$this->Replace($pattern,$p_array);
00244                         if ( strpos($value,'ERROR') != false )            $value="";
00245                         // replace into the $buffer
00246                         // take the position in the buffer
00247                         $pos=strpos($buffer,$to_remove);
00248                         // get the length of the string to remove
00249                         $len=strlen($to_remove);
00250                         if ( $p_type=='OOo' )
00251                           {
00252                             $value=str_replace('&','&amp;',$value);
00253                             $value=str_replace('<','&lt;',$value);
00254                             $value=str_replace('>','&gt;',$value);
00255                             $value=str_replace('"','&quot;',$value);
00256                             $value=str_replace("'",'&apos;',$value);
00257                           }
00258                         $buffer=substr_replace($buffer,$value,$pos,$len);
00259 
00260                         // if the pattern if found we replace it
00261                       }
00262                   }
00263               }
00264             // write into the output_file
00265             fwrite($output_file,$buffer);
00266 
00267           }
00268         fclose($h);
00269         fclose($output_file);
00270         if ( ($ret=copy ($output_name,$infile_name)) == FALSE )
00271         {
00272             echo _('Ne peut pas sauver '.$output_name.' vers '.$infile_name.' code d\'erreur ='.$ret);
00273         }
00274 
00275 
00276     }
00277     /*! SaveGenerated
00278      * \brief Save the generated Document
00279      * \param $p_file is the generated file
00280      *
00281      *
00282      * \return 0 if no error otherwise 1
00283      */
00284     function SaveGenerated($p_file)
00285     {
00286         // We save the generated file
00287         $doc=new Document($this->db);
00288         $this->db->start();
00289         $this->d_lob=$this->db->lo_import($p_file);
00290         if ( $this->d_lob == false )
00291         {
00292             echo "ne peut pas importer [$p_file]";
00293             return 1;
00294         }
00295 
00296         $sql="insert into document(ag_id,d_lob,d_number,d_filename,d_mimetype)
00297              values ($1,$2,$3,$4,$5)";
00298 
00299         $this->db->exec_sql($sql,      array($this->ag_id,
00300                                              $this->d_lob,
00301                                              $this->d_number,
00302                                              $this->d_filename,
00303                                              $this->d_mimetype));
00304         $this->d_id=$this->db->get_current_seq("document_d_id_seq");
00305         // Clean the file
00306         unlink ($p_file);
00307         $this->db->commit();
00308         return 0;
00309     }
00310     /*! Upload
00311      * \brief Upload a file into document
00312      *  all the needed data are in $_FILES we don't increment the seq
00313      * \param $p_file : array containing by default $_FILES
00314      *
00315      * \return
00316      */
00317     function Upload($p_ag_id)
00318     {
00319         // nothing to save
00320         if ( sizeof($_FILES) == 0 ) return;
00321 
00322         /* for several files  */
00323         /* $_FILES is now an array */
00324         // Start Transaction
00325         $this->db->start();
00326         $name=$_FILES['file_upload']['name'];
00327         for ($i = 0; $i < sizeof($name);$i++)
00328         {
00329             $new_name=tempnam($_ENV['TMP'],'doc_');
00330             // check if a file is submitted
00331             if ( strlen($_FILES['file_upload']['tmp_name'][$i]) != 0 )
00332             {
00333                 // upload the file and move it to temp directory
00334                 if ( move_uploaded_file($_FILES['file_upload']['tmp_name'][$i],$new_name))
00335                 {
00336                     $oid=$this->db->lo_import($new_name);
00337                     // check if the lob is in the database
00338                     if ( $oid == false )
00339                     {
00340                         $this->db->rollback();
00341                         return 1;
00342                     }
00343                 }
00344                 // the upload in the database is successfull
00345                 $this->d_lob=$oid;
00346                 $this->d_filename=$_FILES['file_upload']['name'][$i];
00347                 $this->d_mimetype=$_FILES['file_upload']['type'][$i];
00348 
00349                 // insert into  the table
00350                 $sql="insert into document (ag_id, d_lob,d_filename,d_mimetype,d_number) values ($1,$2,$3,$4,5)";
00351                 $this->db->exec_sql($sql,array($p_ag_id,$this->d_lob,$this->d_filename,$this->d_mimetype));
00352             }
00353         } /* end for */
00354         $this->db->commit();
00355 
00356     }
00357     /*! a_ref
00358      * \brief create and compute a string for reference the doc <A ...>
00359      *
00360      * \return a string
00361      */
00362     function anchor()
00363     {
00364         if ( $this->d_id == 0 )
00365             return '';
00366         $image='<IMG SRC="image/insert_table.gif" title="'.$this->d_filename.'" border="0">';
00367         $r="";
00368         $r='<A class="mtitle" HREF="show_document.php?d_id='.$this->d_id.'&'.dossier::get().'">'.$image.'</A>';
00369         return $r;
00370     }
00371     /* ! Get
00372      * \brief Send the document
00373      */
00374     function Send()
00375     {
00376         // retrieve the template and generate document
00377         $this->db->start();
00378         $ret=$this->db->exec_sql(
00379                  "select d_id,d_lob,d_filename,d_mimetype from document where d_id=".$this->d_id );
00380         if ( Database::num_row ($ret) == 0 )
00381             return;
00382         $row=Database::fetch_array($ret,0);
00383         //the document  is saved into file $tmp
00384         $tmp=tempnam($_ENV['TMP'],'document_');
00385         $this->db->lo_export($row['d_lob'],$tmp);
00386         $this->d_mimetype=$row['d_mimetype'];
00387         $this->d_filename=$row['d_filename'];
00388 
00389         // send it to stdout
00390         ini_set('zlib.output_compression','Off');
00391         header("Pragma: public");
00392         header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
00393         header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
00394         header("Cache-Control: must-revalidate");
00395         header('Content-type: '.$this->d_mimetype);
00396         header('Content-Disposition: attachment;filename="'.$this->d_filename.'"',FALSE);
00397         header("Accept-Ranges: bytes");
00398         $file=fopen($tmp,'r');
00399         while ( !feof ($file) )
00400         {
00401             echo fread($file,8192);
00402         }
00403         fclose($file);
00404 
00405         unlink ($tmp);
00406 
00407         $this->db->commit();
00408 
00409     }
00410     /*!\brief get all the document of a given action
00411      *\param $ag_id the ag_id from action::ag_id (primary key)
00412      *\return an array of objects document or an empty array if nothing found
00413      */
00414     function get_all($ag_id)
00415     {
00416         $res=$this->db->get_array('select d_id, ag_id, d_lob, d_number, d_filename,'.
00417                                   ' d_mimetype from document where ag_id=$1',array($ag_id));
00418         $a=array();
00419         for ($i=0;$i<sizeof($res); $i++ )
00420         {
00421             $doc=new Document($this->db);
00422             $doc->d_id=$res[$i]['d_id'];
00423             $doc->ag_id=$res[$i]['ag_id'];
00424             $doc->d_lob=$res[$i]['d_lob'];
00425             $doc->d_number=$res[$i]['d_number'];
00426             $doc->d_filename=$res[$i]['d_filename'];
00427             $doc->d_mimetype=$res[$i]['d_mimetype'];
00428             $a[$i]=clone $doc;
00429         }
00430         return $a;
00431     }
00432 
00433     /*!\brief Get  complete all the data member thx info from the database
00434      */
00435     function get()
00436     {
00437         $sql="select * from document where d_id=".$this->d_id;
00438         $ret=$this->db->exec_sql($sql);
00439         if ( Database::num_row($ret) == 0 )
00440             return;
00441         $row=Database::fetch_array($ret,0);
00442         $this->ag_id=$row['ag_id'];
00443         $this->d_mimetype=$row['d_mimetype'];
00444         $this->d_filename=$row['d_filename'];
00445         $this->d_lob=$row['d_lob'];
00446         $this->d_number=$row['d_number'];
00447 
00448     }
00449     /*!
00450      * \brief replace the TAG by the real value, this value can be into
00451      * the database or in $_POST
00452      * The possible tags are
00453      *  - [CUST_NAME] customer's name
00454      *  - [CUST_ADDR_1] customer's address line 1
00455      *  - [CUST_CP] customer's ZIP code
00456      *  - [CUST_CO] customer's country
00457      *  - [CUST_CITY] customer's city
00458      *  - [CUST_VAT] customer's VAT
00459      *  - [MARCH_NEXT]   end this item and increment the counter $i
00460      *  - [DATE_LIMIT]
00461      *  - [VEN_ART_NAME]
00462      *  - [VEN_ART_PRICE]
00463      *  - [VEN_ART_QUANT]
00464      *  - [VEN_ART_TVA_CODE]
00465      *  - [VEN_ART_TVA_AMOUNT]
00466      *  - [VEN_ART_STOCK_CODE]
00467      *  - [VEN_HTVA]
00468      *  - [VEN_TVAC]
00469      *  - [VEN_TVA]
00470      *  - [TOTAL_VEN_HTVA]
00471      *  - [DATE_CALC]
00472      *  - [DATE]
00473      *  - [DATE_LIMIT]
00474      *  - [DATE_LIMIT_CALC]
00475      *  - [NUMBER]
00476      *  - [MY_NAME]
00477      *  - [MY_CP]
00478      *  - [MY_COMMUNE]
00479      *  - [MY_TVA]
00480      *  - [MY_STREET]
00481      *  - [MY_NUMBER]
00482      *  - [TVA_CODE]
00483      *  - [TVA_RATE]
00484      *  - [BON_COMMANDE]
00485      *  - [OTHER_INFO]
00486      *  - [CUST_NUM]
00487      *  - [CUST_BANQUE_NAME]
00488      *  - [CUST_BANQUE_NO]
00489      *  - [USER]
00490      *  - [REFERENCE]
00491      *  - [BENEF_NAME]
00492      *  - [BENEF_BANQUE_NAME]
00493      *  - [BENEF_BANQUE_NO]
00494      *  - [BENEF_ADDR_1]
00495      *  - [BENEF_CP]
00496      *  - [BENEF_CO]
00497      *  - [BENEF_CITY]
00498      *  - [BENEF_VAT]
00499      *  - [ACOMPTE]
00500      *
00501      * \param $p_tag TAG
00502      * \param $p_array data from $_POST
00503      * \return String which must replace the tag
00504      */
00505     function Replace($p_tag,$p_array)
00506     {
00507                 global $g_parameter;
00508         $p_tag=strtoupper($p_tag);
00509         $p_tag=str_replace('=','',$p_tag);
00510         $r="Tag inconnu";
00511         static $counter=0;
00512         switch ($p_tag)
00513         {
00514                 case 'DATE':
00515                         $r=(isset ($p_array['ag_timestamp']))?$p_array['ag_timestamp']:$p_array['e_date'];
00516                         break;
00517         case 'DATE_CALC':
00518                 $r=' Date inconnue ';
00519             // Date are in $p_array['ag_date']
00520             // or $p_array['e_date']
00521             if ( isset ($p_array['ag_timestamp'])) {
00522                 $date=format_date($p_array['ag_timestamp'],'DD.MM.YYYY','YYYY-MM-DD');
00523                 $r=$date;
00524             }
00525             if ( isset ($p_array['e_date'])) {
00526                 $date=format_date($p_array['e_date'],'DD.MM.YYYY','YYYY-MM-DD');
00527                 $r=$date;
00528             }
00529             break;
00530             //
00531             //  the company priv
00532 
00533         case 'MY_NAME':
00534             $r=$g_parameter->MY_NAME;
00535             break;
00536         case 'MY_CP':
00537             $r=$g_parameter->MY_CP;
00538             break;
00539         case 'MY_COMMUNE':
00540             $r=$g_parameter->MY_COMMUNE;
00541             break;
00542         case 'MY_TVA':
00543             $r=$g_parameter->MY_TVA;
00544             break;
00545         case 'MY_STREET':
00546             $r=$g_parameter->MY_STREET;
00547             break;
00548         case 'MY_NUMBER':
00549             $r=$g_parameter->MY_NUMBER;
00550             break;
00551         case 'MY_TEL':
00552             $r=$g_parameter->MY_TEL;
00553             break;
00554         case 'MY_FAX':
00555             $r=$g_parameter->MY_FAX;
00556             break;
00557         case 'MY_PAYS':
00558             $r=$g_parameter->MY_PAYS;
00559             break;
00560 
00561             // customer
00562             /*\note The CUST_* are retrieved thx the $p_array['tiers']
00563              * which contains the quick_code
00564              */
00565         case 'SOLDE':
00566             $tiers=new Fiche($this->db);
00567             $qcode=isset($p_array['qcode_dest'])?$p_array['qcode_dest']:$p_array['e_client'];
00568             $tiers->get_by_qcode($qcode,false);
00569             $p=$tiers->strAttribut(ATTR_DEF_ACCOUNT);
00570             $poste=new Acc_Account_Ledger($this->db,$p);
00571             $r=$poste->get_solde(' true' );
00572             break;
00573         case 'CUST_NAME':
00574             $tiers=new Fiche($this->db);
00575             $qcode=isset($p_array['qcode_dest'])?$p_array['qcode_dest']:$p_array['e_client'];
00576             $tiers->get_by_qcode($qcode,false);
00577             $r=$tiers->strAttribut(ATTR_DEF_NAME);
00578             break;
00579         case 'CUST_ADDR_1':
00580             $tiers=new Fiche($this->db);
00581             $qcode=isset($p_array['qcode_dest'])?$p_array['qcode_dest']:$p_array['e_client'];
00582             $tiers->get_by_qcode($qcode,false);
00583             $r=$tiers->strAttribut(ATTR_DEF_ADRESS);
00584 
00585             break ;
00586         case 'CUST_CP':
00587             $tiers=new Fiche($this->db);
00588 
00589             $qcode=isset($p_array['qcode_dest'])?$p_array['qcode_dest']:$p_array['e_client'];
00590             $tiers->get_by_qcode($qcode,false);
00591             $r=$tiers->strAttribut(ATTR_DEF_CP);
00592 
00593             break;
00594         case 'CUST_CITY':
00595             $tiers=new Fiche($this->db);
00596 
00597             $qcode=isset($p_array['qcode_dest'])?$p_array['qcode_dest']:$p_array['e_client'];
00598             $tiers->get_by_qcode($qcode,false);
00599             $r=$tiers->strAttribut(ATTR_DEF_CITY);
00600 
00601             break;
00602 
00603         case 'CUST_CO':
00604             $tiers=new Fiche($this->db);
00605 
00606             $qcode=isset($p_array['qcode_dest'])?$p_array['qcode_dest']:$p_array['e_client'];
00607             $tiers->get_by_qcode($qcode,false);
00608             $r=$tiers->strAttribut(ATTR_DEF_PAYS);
00609 
00610             break;
00611             // Marchandise in $p_array['e_march*']
00612             // \see user_form_achat.php or user_form_ven.php
00613         case 'CUST_VAT':
00614             $tiers=new Fiche($this->db);
00615 
00616             $qcode=isset($p_array['qcode_dest'])?$p_array['qcode_dest']:$p_array['e_client'];
00617             $tiers->get_by_qcode($qcode,false);
00618             $r=$tiers->strAttribut(ATTR_DEF_NUMTVA);
00619             break;
00620         case 'CUST_NUM':
00621             $tiers=new Fiche($this->db);
00622             $qcode=isset($p_array['qcode_dest'])?$p_array['qcode_dest']:$p_array['e_client'];
00623             $tiers->get_by_qcode($qcode,false);
00624             $r=$tiers->strAttribut(ATTR_DEF_NUMBER_CUSTOMER);
00625             break;
00626         case 'CUST_BANQUE_NO':
00627             $tiers=new Fiche($this->db);
00628             $qcode=isset($p_array['qcode_dest'])?$p_array['qcode_dest']:$p_array['e_client'];
00629             $tiers->get_by_qcode($qcode,false);
00630             $r=$tiers->strAttribut(ATTR_DEF_BQ_NO);
00631             break;
00632         case 'CUST_BANQUE_NAME':
00633             $tiers=new Fiche($this->db);
00634             $qcode=isset($p_array['qcode_dest'])?$p_array['qcode_dest']:$p_array['e_client'];
00635             $tiers->get_by_qcode($qcode,false);
00636             $r=$tiers->strAttribut(ATTR_DEF_BQ_NAME);
00637             break;
00638             /* -------------------------------------------------------------------------------- */
00639             /* BENEFIT (fee notes */
00640         case 'BENEF_NAME':
00641             $tiers=new Fiche($this->db);
00642             $qcode=isset($p_array['qcode_benef'])?$p_array['qcode_benef']:'';
00643             if ( $qcode=='')
00644             {
00645                 $r='';
00646                 break;
00647             }
00648             $tiers->get_by_qcode($qcode,false);
00649             $r=$tiers->strAttribut(ATTR_DEF_NAME);
00650             break;
00651         case 'BENEF_ADDR_1':
00652             $tiers=new Fiche($this->db);
00653             $qcode=isset($p_array['qcode_benef'])?$p_array['qcode_benef']:'';
00654             if ( $qcode=='')
00655             {
00656                 $r='';
00657                 break;
00658             }
00659             $tiers->get_by_qcode($qcode,false);
00660             $r=$tiers->strAttribut(ATTR_DEF_ADRESS);
00661 
00662             break ;
00663         case 'BENEF_CP':
00664             $tiers=new Fiche($this->db);
00665 
00666             $qcode=isset($p_array['qcode_benef'])?$p_array['qcode_benef']:'';
00667             if ( $qcode=='')
00668             {
00669                 $r='';
00670                 break;
00671             }
00672             $tiers->get_by_qcode($qcode,false);
00673             $r=$tiers->strAttribut(ATTR_DEF_CP);
00674 
00675             break;
00676         case 'BENEF_CITY':
00677             $tiers=new Fiche($this->db);
00678 
00679             $qcode=isset($p_array['qcode_benef'])?$p_array['qcode_benef']:'';
00680             if ( $qcode=='')
00681             {
00682                 $r='';
00683                 break;
00684             }
00685             $tiers->get_by_qcode($qcode,false);
00686             $r=$tiers->strAttribut(ATTR_DEF_CITY);
00687 
00688             break;
00689 
00690         case 'BENEF_CO':
00691             $tiers=new Fiche($this->db);
00692 
00693             $qcode=isset($p_array['qcode_benef'])?$p_array['qcode_benef']:'';
00694             if ( $qcode=='')
00695             {
00696                 $r='';
00697                 break;
00698             }
00699             $tiers->get_by_qcode($qcode,false);
00700             $r=$tiers->strAttribut(ATTR_DEF_PAYS);
00701 
00702             break;
00703             // Marchandise in $p_array['e_march*']
00704             // \see user_form_achat.php or user_form_ven.php
00705         case 'BENEF_VAT':
00706             $tiers=new Fiche($this->db);
00707 
00708             $qcode=isset($p_array['qcode_benef'])?$p_array['qcode_benef']:'';
00709             if ( $qcode=='')
00710             {
00711                 $r='';
00712                 break;
00713             }
00714             $tiers->get_by_qcode($qcode,false);
00715             $r=$tiers->strAttribut(ATTR_DEF_NUMTVA);
00716             break;
00717         case 'BENEF_NUM':
00718             $tiers=new Fiche($this->db);
00719             $qcode=isset($p_array['qcode_benef'])?$p_array['qcode_benef']:'';
00720             if ( $qcode=='')
00721             {
00722                 $r='';
00723                 break;
00724             }
00725             $tiers->get_by_qcode($qcode,false);
00726             $r=$tiers->strAttribut(ATTR_DEF_NUMBER_CUSTOMER);
00727             break;
00728         case 'BENEF_BANQUE_NO':
00729             $tiers=new Fiche($this->db);
00730             $qcode=isset($p_array['qcode_benef'])?$p_array['qcode_benef']:'';
00731             if ( $qcode=='')
00732             {
00733                 $r='';
00734                 break;
00735             }
00736             $tiers->get_by_qcode($qcode,false);
00737             $r=$tiers->strAttribut(ATTR_DEF_BQ_NO);
00738             break;
00739         case 'BENEF_BANQUE_NAME':
00740             $tiers=new Fiche($this->db);
00741             $qcode=isset($p_array['qcode_benef'])?$p_array['qcode_benef']:'';
00742             if ( $qcode=='')
00743             {
00744                 $r='';
00745                 break;
00746             }
00747             $tiers->get_by_qcode($qcode,false);
00748             $r=$tiers->strAttribut(ATTR_DEF_BQ_NAME);
00749             break;
00750 
00751             // Marchandise in $p_array['e_march*']
00752             // \see user_form_achat.php or user_form_ven.php
00753         case 'NUMBER':
00754             $r=$this->d_number;
00755             break;
00756 
00757         case 'USER' :
00758             return $_SESSION['use_name'].', '.$_SESSION['use_first_name'];
00759 
00760             break;
00761         case 'REFERENCE':
00762             $act=new Follow_Up($this->db);
00763             $act->ag_id=$this->ag_id;
00764             $act->get();
00765             $r=$act->ag_ref;
00766             break;
00767 
00768             /*
00769              *  - [VEN_ART_NAME]
00770              *  - [VEN_ART_PRICE]
00771              *  - [VEN_ART_QUANT]
00772              *  - [VEN_ART_TVA_CODE]
00773              *  - [VEN_ART_TVA_AMOUNT]
00774              *  - [VEN_ART_STOCK_CODE]
00775              *  - [VEN_HTVA]
00776              *  - [VEN_TVAC]
00777              *  - [VEN_TVA]
00778              *  - [TOTAL_VEN_HTVA]
00779              *  - [DATE_LIMIT]
00780              */
00781         case 'DATE_LIMIT_CALC':
00782             extract ($p_array);
00783             $id='e_ech' ;
00784             if ( !isset (${$id}) ) return "";
00785             $r=format_date(${$id},'DD.MM.YYYY','YYYY-MM-DD');
00786             break;
00787       case 'DATE_LIMIT':
00788             extract ($p_array);
00789             $id='e_ech' ;
00790             if ( !isset (${$id}) ) return "";
00791             $r=${$id};
00792             break;
00793         case 'MARCH_NEXT':
00794             $counter++;
00795             $r='';
00796             break;
00797 
00798         case 'VEN_ART_NAME':
00799             extract ($p_array);
00800             $id='e_march'.$counter;
00801             // check if the march exists
00802             if ( ! isset (${$id})) return "";
00803             // check that something is sold
00804             if ( ${'e_march'.$counter.'_price'} != 0 && ${'e_quant'.$counter} != 0 )
00805             {
00806                 $f=new Fiche($this->db);
00807                 $f->get_by_qcode(${$id},false);
00808                 $r=$f->strAttribut(ATTR_DEF_NAME);
00809             }
00810             else $r = "";
00811             break;
00812        case 'VEN_ART_LABEL':
00813             extract ($p_array);
00814             $id='e_march'.$counter."_label";
00815             // check if the march exists
00816 
00817             if (! isset (${$id}) || (isset (${$id}) && strlen(trim(${$id})) == 0))
00818                 {
00819                     $id = 'e_march' . $counter;
00820                     // check if the march exists
00821                     if (!isset(${$id}))
00822                         $r= "";
00823                     // check that something is sold
00824                     if (${'e_march' . $counter . '_price'} != 0 && ${'e_quant' . $counter} != 0)
00825                     {
00826                         $f = new Fiche($this->db);
00827                         $f->get_by_qcode(${$id}, false);
00828                         $r = $f->strAttribut(ATTR_DEF_NAME);
00829                     }
00830                                         else
00831                                                 $r="";
00832                 }
00833                 else
00834                     $r=${'e_march'.$counter.'_label'};
00835             break;
00836 
00837         case 'VEN_ART_PRICE':
00838             extract ($p_array);
00839             $id='e_march'.$counter.'_price' ;
00840             if ( !isset (${$id}) ) return "";
00841                         if (${$id} == 0 ) return "";
00842             $r=${$id};
00843             break;
00844 
00845         case 'TVA_RATE':
00846         case 'VEN_ART_TVA_RATE':
00847             extract ($p_array);
00848             $id='e_march'.$counter.'_tva_id';
00849             if ( !isset (${$id}) ) return "";
00850             if ( ${$id} == -1 || ${$id}=='' ) return "";
00851             $march_id='e_march'.$counter.'_price' ;
00852             if ( ! isset (${$march_id})) return '';
00853             $tva=new Acc_Tva($this->db);
00854             $tva->set_parameter("id",${$id});
00855             if ( $tva->load() == -1) return '';
00856             return $tva->get_parameter("rate");
00857             break;
00858 
00859         case 'TVA_CODE':
00860         case 'VEN_ART_TVA_CODE':
00861             extract ($p_array);
00862             $id='e_march'.$counter.'_tva_id';
00863             if ( !isset (${$id}) ) return "";
00864             if ( ${$id} == -1 ) return "";
00865             $qt='e_quant'.$counter;
00866             $price='e_march'.$counter.'_price' ;
00867             if ( ${$price} == 0 || ${$qt} == 0
00868                     || strlen(trim( $price )) ==0
00869                     || strlen(trim($qt)) ==0)
00870                 return "";
00871 
00872             $r=${$id};
00873             break;
00874 
00875         case 'TVA_LABEL':
00876             extract ($p_array);
00877             $id='e_march'.$counter.'_tva_id';
00878             if ( !isset (${$id}) ) return "";
00879             $march_id='e_march'.$counter.'_price' ;
00880             if ( ! isset (${$march_id})) return '';
00881             if ( ${$march_id} == 0) return '';
00882             $tva=new Acc_Tva($this->db,${$id});
00883             if ($tva->load() == -1 ) return "";
00884             $r=$tva->get_parameter('label');
00885 
00886             break;
00887 
00888             /* total VAT for one sold */
00889         case 'TVA_AMOUNT':
00890             extract ($p_array);
00891             $qt='e_quant'.$counter;
00892             $price='e_march'.$counter.'_price' ;
00893             $tva='e_march'.$counter.'_tva_id';
00894             /* if we do not use vat this var. is not set */
00895             if ( !isset(${$tva}) ) return '';
00896             if ( !isset (${'e_march'.$counter}) ) return "";
00897             // check that something is sold
00898             if ( ${$price} == 0 || ${$qt} == 0
00899                     || strlen(trim( $price )) ==0
00900                     || strlen(trim($qt)) ==0)
00901                 return "";
00902             $r=${'e_march'.$counter.'_tva_amount'};
00903             break;
00904             /* TVA automatically computed */
00905         case 'VEN_ART_TVA':
00906             extract ($p_array);
00907             $qt='e_quant'.$counter;
00908             $price='e_march'.$counter.'_price' ;
00909             $tva='e_march'.$counter.'_tva_id';
00910             if ( !isset (${'e_march'.$counter}) ) return "";
00911             // check that something is sold
00912             if ( ${$price} == 0 || ${$qt} == 0
00913                     || strlen(trim( $price )) ==0
00914                     || strlen(trim($qt)) ==0)
00915                 return "";
00916             $oTva=new Acc_Tva($this->db,${$tva});
00917             if ($oTva->load() == -1 ) return "";
00918             $r=round(${$price},2)*$oTva->get_parameter('rate');
00919             $r=round($r,2);
00920             break;
00921 
00922         case 'VEN_ART_TVAC':
00923             extract ($p_array);
00924             $qt='e_quant'.$counter;
00925             $price='e_march'.$counter.'_price' ;
00926             $tva='e_march'.$counter.'_tva_id';
00927             if ( !isset (${'e_march'.$counter}) ) return "";
00928             // check that something is sold
00929             if ( ${$price} == 0 || ${$qt} == 0
00930                     || strlen(trim( $price )) ==0
00931                     || strlen(trim($qt)) ==0)
00932                 return "";
00933             if ( ! isset (${$tva}) ) return '';
00934             $tva=new Acc_Tva($this->db,${$tva});
00935             if ($tva->load() == -1 )
00936             {
00937                 $r=round(${$price},2);
00938             }
00939             else
00940             {
00941                 $r=round(${$price}*$tva->get_parameter('rate')+${$price},2);
00942             }
00943 
00944             break;
00945 
00946         case 'VEN_ART_QUANT':
00947             extract ($p_array);
00948             $id='e_quant'.$counter;
00949             if ( !isset (${$id}) ) return "";
00950             // check that something is sold
00951             if ( ${'e_march'.$counter.'_price'} == 0
00952                     || ${'e_quant'.$counter} == 0
00953                     || strlen(trim( ${'e_march'.$counter.'_price'} )) ==0
00954                     || strlen(trim(${'e_quant'.$counter})) ==0 )
00955                 return "";
00956             $r=${$id};
00957             break;
00958 
00959         case 'VEN_HTVA':
00960             extract ($p_array);
00961             $id='e_march'.$counter.'_price' ;
00962             $quant='e_quant'.$counter;
00963             if ( !isset (${$id}) ) return "";
00964 
00965             // check that something is sold
00966             if ( ${'e_march'.$counter.'_price'} == 0 || ${'e_quant'.$counter} == 0
00967                     || strlen(trim( ${'e_march'.$counter.'_price'} )) ==0
00968                     || strlen(trim(${'e_quant'.$counter})) ==0)
00969                 return "";
00970                         bcscale(4);
00971             $r=bcmul(${$id},${$quant});
00972                         $r=round($r,2);
00973             break;
00974 
00975         case 'VEN_TVAC':
00976             extract ($p_array);
00977             $id='e_march'.$counter.'_tva_amount' ;
00978             $price='e_march'.$counter.'_price' ;
00979             $quant='e_quant'.$counter;
00980             if ( ! isset(${'e_march'.$counter.'_price'})|| !isset(${'e_quant'.$counter}))     return "";
00981             // check that something is sold
00982             if ( ${'e_march'.$counter.'_price'} == 0 || ${'e_quant'.$counter} == 0 ) return "";
00983                         bcscale(4);
00984             // if TVA not exist
00985             if ( ! isset(${$id}))
00986                 $r=  bcmul(${$price},${$quant});
00987             else{
00988                 $r=  bcmul(${$price},${$quant});
00989                 $r=bcadd($r,${$id});
00990                         }
00991                         $r=round($r,2);
00992                         return $r;
00993             break;
00994 
00995         case 'TOTAL_VEN_HTVA':
00996             extract($p_array);
00997                         bcscale(4);
00998             $sum=0.0;
00999             for ($i=0;$i<$nb_item;$i++)
01000             {
01001                 $sell='e_march'.$i.'_price';
01002                 $qt='e_quant'.$i;
01003 
01004                 if ( ! isset (${$sell}) ) break;
01005 
01006                 if ( strlen(trim(${$sell})) == 0 ||
01007                         strlen(trim(${$qt})) == 0 ||
01008                         ${$qt}==0 || ${$sell}==0)
01009                     continue;
01010                 $tmp1=bcmul(${$sell},${$qt});
01011                 $sum=bcadd($sum,$tmp1);
01012 
01013 
01014             }
01015             $r=round($sum,2);
01016             break;
01017         case 'TOTAL_VEN_TVAC':
01018             extract($p_array);
01019             $sum=0.0;
01020                         bcscale(4);
01021             for ($i=0;$i<$nb_item;$i++)
01022             {
01023                 $tva='e_march'.$i.'_tva_amount';
01024                 $tva_amount=0;
01025                 /* if we do not use vat this var. is not set */
01026                 if ( isset(${$tva}) )
01027                 {
01028                     $tva_amount=${$tva};
01029                 }
01030                 $sell=${'e_march'.$i.'_price'};
01031                 $qt=${'e_quant'.$i};
01032                                 $tot=bcmul($sell,$qt);
01033                                 $tot=bcadd($tot,$tva_amount);
01034                                 $sum=bcadd($sum,$tot);
01035             }
01036             $r=round($sum,2);
01037 
01038             break;
01039         case 'TOTAL_TVA':
01040             extract($p_array);
01041             $sum=0.0;
01042             for ($i=0;$i<$nb_item;$i++)
01043             {
01044                 $tva='e_march'.$i.'_tva_amount';
01045                 if (! isset(${$tva})) $tva_amount=0.0;
01046                 else $tva_amount=$
01047                                      {
01048                                          $tva
01049                                      };
01050                 $sum+=$tva_amount;
01051                 $sum=round($sum,2);
01052             }
01053             $r=$sum;
01054 
01055             break;
01056         case 'BON_COMMANDE':
01057             if ( isset($p_array['bon_comm']))
01058                 return $p_array['bon_comm'];
01059             else
01060                 return "";
01061             break;
01062         case 'PJ':
01063             if ( isset($p_array['e_pj']))
01064                 return $p_array['e_pj'];
01065             else
01066                 return "";
01067 
01068         case 'OTHER_INFO':
01069             if ( isset($p_array['other_info']))
01070                 return $p_array['other_info'];
01071             else
01072                 return "";
01073             break;
01074         case 'COMMENT':
01075             if ( isset($p_array['e_comm']))
01076                 return $p_array['e_comm'];
01077             break;
01078         case 'ACOMPTE':
01079             if ( isset($p_array['acompte']))
01080                 return $p_array['acompte'];
01081                         return "0";
01082             break;
01083         }
01084         /*
01085          * retrieve the value of ATTR for e_march
01086          */
01087         if (preg_match('/^ATTR/', $p_tag) == 1)
01088         {
01089             // Retrieve f_id
01090             if ( isset ($p_array['e_march'.$counter]))
01091             {
01092                 $id = $p_array['e_march' . $counter];
01093                 $r=$this->replace_special_tag($id,$p_tag);
01094             }
01095         }
01096         /*
01097          * retrieve the value of ATTR for e_march
01098          */
01099         if (preg_match('/^BENEFATTR/', $p_tag) == 1)
01100         {
01101             $qcode=isset($p_array['qcode_benef'])?$p_array['qcode_benef']:'';
01102             // Retrieve f_id
01103              $r=$this->replace_special_tag($qcode,$p_tag);
01104         }
01105         if (preg_match('/^CUSTATTR/', $p_tag) == 1)
01106         {
01107             if ( isset($p_array['qcode_dest']) || isset($p_array['e_client']) )
01108             {
01109                 $qcode=(isset($p_array['qcode_dest']))?$p_array['qcode_dest']:$p_array['e_client'];
01110                 $r=$this->replace_special_tag($qcode,$p_tag);
01111             }
01112         }
01113         return $r;
01114     }
01115     /*!\brief remove a row from the table document, the lob object is not deleted
01116      *        because can be linked elsewhere
01117      */
01118     function remove()
01119     {
01120       $d_lob=$this->db->get_value('select d_lob from document where d_id=$1',
01121                                   array($this->d_id));
01122         $sql='delete from document where d_id='.$this->d_id;
01123         $this->db->exec_sql($sql);
01124         if ( $d_lob != 0 )
01125             $this->db->lo_unlink($d_lob);
01126     }
01127     /*!\brief Move a document from the table document into the concerned row
01128      *        the document is not copied : it is only a link
01129      *
01130      * \param $p_internal internal code
01131      *
01132      */
01133     function MoveDocumentPj($p_internal)
01134     {
01135         $sql="update jrn set jr_pj=$1,jr_pj_name=$2,jr_pj_type=$3 where jr_internal=$4";
01136 
01137         $this->db->exec_sql($sql,array($this->d_lob,$this->d_filename,$this->d_mimetype,$p_internal));
01138         // clean the table document
01139         $sql='delete from document where d_id='.$this->d_id;
01140         $this->db->exec_sql($sql);
01141 
01142 
01143     }
01144     /**
01145      *Replace a special tag *TAGxxxx with the value from fiche_detail, the xxxx
01146      * is the ad_value
01147      * @param $p_qcode qcode of the card
01148      * @param $p_tag tag to parse
01149      * @return  the ad_value contained in fiche_detail or for the type "select" the
01150      *          label
01151      */
01152     function replace_special_tag($p_qcode, $p_tag)
01153     {
01154         // check if the march exists
01155         if ($p_qcode == "")
01156             return "";
01157 
01158         $f = new Fiche($this->db);
01159         $found = $f->get_by_qcode($p_qcode, false);
01160         // if not found exit
01161         if ($found == 1)
01162             return "";
01163 
01164         // get the ad_id
01165         $attr=preg_replace("/^.*ATTR/","",$p_tag);
01166 
01167         if (isNumber($attr) == 0) return "";
01168         $ad_type=$this->db->get_value("select ad_type from attr_def where ad_id=$1",array($attr));
01169 
01170         // get ad_value
01171         $ad_value=$this->db->get_value("select ad_value from fiche_detail where f_id=$1 and ad_id=$2",array($f->id,$attr));
01172 
01173         // if ad_id is type select execute select and get value
01174         if ( $ad_type=="select")
01175         {
01176             $sql=$this->db->get_value("select ad_extra from attr_def where ad_id=$1",array($attr));
01177             $array= $this->db->make_array($sql);
01178             for ($a=0;$a<count ($array);$a++)
01179             {
01180                 if ($array[$a]['value']==$ad_value)
01181                     return $array[$a]['label'];
01182             }
01183 
01184         }
01185         // if ad_id is not type select get value
01186         return $ad_value;
01187     }
01188 
01189 }