dolibarr  7.0.0-beta
doc_generic_invoice_odt.modules.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2010-2012 Laurent Destailleur <ely@users.sourceforge.net>
3 * Copyright (C) 2012 Regis Houssin <regis.houssin@capnetworks.com>
4 * Copyright (C) 2014 Marcos GarcĂ­a <marcosgdf@gmail.com>
5 * Copyright (C) 2016 Charlie Benke <charlie@patas-monkey.com>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 * or see http://www.gnu.org/
20 */
21 
28 require_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php';
29 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
30 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
31 require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
32 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
33 require_once DOL_DOCUMENT_ROOT.'/core/lib/doc.lib.php';
34 
35 
40 {
41  var $emetteur; // Objet societe qui emet
42 
43  var $phpmin = array(5,2,0); // Minimum version of PHP required by module
44  var $version = 'dolibarr';
45 
46 
52  function __construct($db)
53  {
54  global $conf,$langs,$mysoc;
55 
56  $langs->load("main");
57  $langs->load("companies");
58 
59  $this->db = $db;
60  $this->name = "ODT/ODS templates";
61  $this->description = $langs->trans("DocumentModelOdt");
62  $this->scandir = 'FACTURE_ADDON_PDF_ODT_PATH'; // Name of constant that is used to save list of directories to scan
63 
64  // Dimension page pour format A4
65  $this->type = 'odt';
66  $this->page_largeur = 0;
67  $this->page_hauteur = 0;
68  $this->format = array($this->page_largeur,$this->page_hauteur);
69  $this->marge_gauche=0;
70  $this->marge_droite=0;
71  $this->marge_haute=0;
72  $this->marge_basse=0;
73 
74  $this->option_logo = 1; // Affiche logo
75  $this->option_tva = 0; // Gere option tva FACTURE_TVAOPTION
76  $this->option_modereg = 0; // Affiche mode reglement
77  $this->option_condreg = 0; // Affiche conditions reglement
78  $this->option_codeproduitservice = 0; // Affiche code produit-service
79  $this->option_multilang = 1; // Dispo en plusieurs langues
80  $this->option_escompte = 0; // Affiche si il y a eu escompte
81  $this->option_credit_note = 0; // Support credit notes
82  $this->option_freetext = 1; // Support add of a personalised text
83  $this->option_draft_watermark = 0; // Support add of a watermark on drafts
84 
85  // Recupere emetteur
86  $this->emetteur=$mysoc;
87  if (! $this->emetteur->country_code) $this->emetteur->country_code=substr($langs->defaultlang,-2); // Par defaut, si n'etait pas defini
88  }
89 
90 
97  function info($langs)
98  {
99  global $conf,$langs;
100 
101  $langs->load("companies");
102  $langs->load("errors");
103 
104  $form = new Form($this->db);
105 
106  $texte = $this->description.".<br>\n";
107  $texte.= '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
108  $texte.= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
109  $texte.= '<input type="hidden" name="action" value="setModuleOptions">';
110  $texte.= '<input type="hidden" name="param1" value="FACTURE_ADDON_PDF_ODT_PATH">';
111  $texte.= '<table class="nobordernopadding" width="100%">';
112 
113  // List of directories area
114  $texte.= '<tr><td valign="middle">';
115  $texttitle=$langs->trans("ListOfDirectories");
116  $listofdir=explode(',',preg_replace('/[\r\n]+/',',',trim($conf->global->FACTURE_ADDON_PDF_ODT_PATH)));
117  $listoffiles=array();
118  foreach($listofdir as $key=>$tmpdir)
119  {
120  $tmpdir=trim($tmpdir);
121  $tmpdir=preg_replace('/DOL_DATA_ROOT/',DOL_DATA_ROOT,$tmpdir);
122  if (! $tmpdir) {
123  unset($listofdir[$key]); continue;
124  }
125  if (! is_dir($tmpdir)) $texttitle.=img_warning($langs->trans("ErrorDirNotFound",$tmpdir),0);
126  else
127  {
128  $tmpfiles=dol_dir_list($tmpdir,'files',0,'\.(ods|odt)');
129  if (count($tmpfiles)) $listoffiles=array_merge($listoffiles,$tmpfiles);
130  }
131  }
132  $texthelp=$langs->trans("ListOfDirectoriesForModelGenODT");
133  // Add list of substitution keys
134  $texthelp.='<br>'.$langs->trans("FollowingSubstitutionKeysCanBeUsed").'<br>';
135  $texthelp.=$langs->transnoentitiesnoconv("FullListOnOnlineDocumentation"); // This contains an url, we don't modify it
136 
137  $texte.= $form->textwithpicto($texttitle,$texthelp,1,'help','',1);
138  $texte.= '<div><div style="display: inline-block; min-width: 100px; vertical-align: middle;">';
139  $texte.= '<textarea class="flat" cols="60" name="value1">';
140  $texte.=$conf->global->FACTURE_ADDON_PDF_ODT_PATH;
141  $texte.= '</textarea>';
142  $texte.= '</div><div style="display: inline-block; vertical-align: middle;">';
143  $texte.= '<input type="submit" class="button" value="'.$langs->trans("Modify").'" name="Button">';
144  $texte.= '<br></div></div>';
145 
146  // Scan directories
147  $nbofiles=count($listoffiles);
148  if (! empty($conf->global->FACTURE_ADDON_PDF_ODT_PATH))
149  {
150  $texte.=$langs->trans("NumberOfModelFilesFound").': <b>';
151  //$texte.=$nbofiles?'<a id="a_'.get_class($this).'" href="#">':'';
152  $texte.=count($listoffiles);
153  //$texte.=$nbofiles?'</a>':'';
154  $texte.='</b>';
155  }
156  if ($nbofiles)
157  {
158  $texte.='<div id="div_'.get_class($this).'" class="hidden">';
159  foreach($listoffiles as $file)
160  {
161  $texte.=$file['name'].'<br>';
162  }
163  $texte.='<div id="div_'.get_class($this).'">';
164  }
165 
166  $texte.= '</td>';
167 
168  $texte.= '<td valign="top" rowspan="2" class="hideonsmartphone">';
169  $texte.= $langs->trans("ExampleOfDirectoriesForModelGen");
170  $texte.= '</td>';
171  $texte.= '</tr>';
172 
173  $texte.= '</table>';
174  $texte.= '</form>';
175 
176  return $texte;
177  }
178 
190  function write_file($object,$outputlangs,$srctemplatepath,$hidedetails=0,$hidedesc=0,$hideref=0)
191  {
192  global $user,$langs,$conf,$mysoc,$hookmanager;
193 
194  if (empty($srctemplatepath))
195  {
196  dol_syslog("doc_generic_odt::write_file parameter srctemplatepath empty", LOG_WARNING);
197  return -1;
198  }
199 
200  // Add odtgeneration hook
201  if (! is_object($hookmanager))
202  {
203  include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
204  $hookmanager=new HookManager($this->db);
205  }
206  $hookmanager->initHooks(array('odtgeneration'));
207  global $action;
208 
209  if (! is_object($outputlangs)) $outputlangs=$langs;
210  $sav_charset_output=$outputlangs->charset_output;
211  $outputlangs->charset_output='UTF-8';
212 
213  $outputlangs->load("main");
214  $outputlangs->load("dict");
215  $outputlangs->load("companies");
216  $outputlangs->load("bills");
217 
218  if ($conf->facture->dir_output)
219  {
220  // If $object is id instead of object
221  if (! is_object($object))
222  {
223  $id = $object;
224  $object = new Facture($this->db);
225  $result=$object->fetch($id);
226  if ($result < 0)
227  {
228  dol_print_error($this->db,$object->error);
229  return -1;
230  }
231  }
232 
233  $dir = $conf->facture->dir_output;
234  $objectref = dol_sanitizeFileName($object->ref);
235  if (! preg_match('/specimen/i',$objectref)) $dir.= "/" . $objectref;
236  $file = $dir . "/" . $objectref . ".odt";
237 
238  if (! file_exists($dir))
239  {
240  if (dol_mkdir($dir) < 0)
241  {
242  $this->error=$langs->transnoentities("ErrorCanNotCreateDir",$dir);
243  return -1;
244  }
245  }
246 
247  if (file_exists($dir))
248  {
249  //print "srctemplatepath=".$srctemplatepath; // Src filename
250  $newfile=basename($srctemplatepath);
251  $newfiletmp=preg_replace('/\.od(t|s)/i','',$newfile);
252  $newfiletmp=preg_replace('/template_/i','',$newfiletmp);
253  $newfiletmp=preg_replace('/modele_/i','',$newfiletmp);
254 
255  $newfiletmp=$objectref.'_'.$newfiletmp;
256 
257  // Get extension (ods or odt)
258  $newfileformat=substr($newfile, strrpos($newfile, '.')+1);
259  if ( ! empty($conf->global->MAIN_DOC_USE_TIMING))
260  {
261  $format=$conf->global->MAIN_DOC_USE_TIMING;
262  if ($format == '1') $format='%Y%m%d%H%M%S';
263  $filename=$newfiletmp.'-'.dol_print_date(dol_now(),$format).'.'.$newfileformat;
264  }
265  else
266  {
267  $filename=$newfiletmp.'.'.$newfileformat;
268  }
269  $file=$dir.'/'.$filename;
270  //$file=$dir.'/'.$newfiletmp.'.'.dol_print_date(dol_now(),'%Y%m%d%H%M%S').'.odt';
271  //print "newdir=".$dir;
272  //print "newfile=".$newfile;
273  //print "file=".$file;
274  //print "conf->societe->dir_temp=".$conf->societe->dir_temp;
275 
276  dol_mkdir($conf->facture->dir_temp);
277 
278 
279  // If BILLING contact defined on invoice, we use it
280  $usecontact=false;
281  $arrayidcontact=$object->getIdContact('external','BILLING');
282  if (count($arrayidcontact) > 0)
283  {
284  $usecontact=true;
285  $result=$object->fetch_contact($arrayidcontact[0]);
286  }
287 
288  // Recipient name
289  if (! empty($usecontact))
290  {
291  // On peut utiliser le nom de la societe du contact
292  if (! empty($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT)) $socobject = $object->contact;
293  else {
294  $socobject = $object->thirdparty;
295  // if we have a BILLING contact and we dont use it as recipient we store the contact object for later use
296  $contactobject = $object->contact;
297  }
298  }
299  else
300  {
301  $socobject=$object->thirdparty;
302  }
303 
304  // Fetch info for linked propal
305  $object->fetchObjectLinked('','','','');
306  //print_r($object->linkedObjects['propal']); exit;
307 
308  $propal_object = $object->linkedObjects['propal'][0];
309 
310  // Make substitution
311  $substitutionarray=array(
312  '__FROM_NAME__' => $this->emetteur->name,
313  '__FROM_EMAIL__' => $this->emetteur->email,
314  '__TOTAL_TTC__' => $object->total_ttc,
315  '__TOTAL_HT__' => $object->total_ht,
316  '__TOTAL_VAT__' => $object->total_tva
317  );
318  complete_substitutions_array($substitutionarray, $langs, $object);
319  // Call the ODTSubstitution hook
320  $parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$substitutionarray);
321  $reshook=$hookmanager->executeHooks('ODTSubstitution',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
322 
323  // Line of free text
324  $newfreetext='';
325  $paramfreetext='INVOICE_FREE_TEXT';
326  if (! empty($conf->global->$paramfreetext))
327  {
328  $newfreetext=make_substitutions($conf->global->$paramfreetext,$substitutionarray);
329  }
330 
331  // Open and load template
332  require_once ODTPHP_PATH.'odf.php';
333  try {
334  $odfHandler = new odf(
335  $srctemplatepath,
336  array(
337  'PATH_TO_TMP' => $conf->facture->dir_temp,
338  'ZIP_PROXY' => 'PclZipProxy', // PhpZipProxy or PclZipProxy. Got "bad compression method" error when using PhpZipProxy.
339  'DELIMITER_LEFT' => '{',
340  'DELIMITER_RIGHT' => '}'
341  )
342  );
343  }
344  catch(Exception $e)
345  {
346  $this->error=$e->getMessage();
347  return -1;
348  }
349  // After construction $odfHandler->contentXml contains content and
350  // [!-- BEGIN row.lines --]*[!-- END row.lines --] has been replaced by
351  // [!-- BEGIN lines --]*[!-- END lines --]
352  //print html_entity_decode($odfHandler->__toString());
353  //print exit;
354 
355 
356  // Make substitutions into odt of freetext
357  try {
358  $odfHandler->setVars('free_text', $newfreetext, true, 'UTF-8');
359  }
360  catch(OdfException $e)
361  {
362  }
363 
364  // Make substitutions into odt
365  $array_user=$this->get_substitutionarray_user($user,$outputlangs);
366  $array_soc=$this->get_substitutionarray_mysoc($mysoc,$outputlangs);
367  $array_thirdparty=$this->get_substitutionarray_thirdparty($socobject,$outputlangs);
368  $array_objet=$this->get_substitutionarray_object($object,$outputlangs);
369  $array_propal=is_object($propal_object)?$this->get_substitutionarray_object($propal_object,$outputlangs,'propal'):array();
370  $array_other=$this->get_substitutionarray_other($outputlangs);
371  // retrieve contact information for use in invoice as contact_xxx tags
372  $array_thirdparty_contact = array();
373  if ($usecontact)
374  $array_thirdparty_contact=$this->get_substitutionarray_contact($contactobject,$outputlangs,'contact');
375 
376  $tmparray = array_merge($array_user,$array_soc,$array_thirdparty,$array_objet,$array_propal,$array_other,$array_thirdparty_contact);
377  complete_substitutions_array($tmparray, $outputlangs, $object);
378  // Call the ODTSubstitution hook
379  $parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray);
380  $reshook=$hookmanager->executeHooks('ODTSubstitution',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
381 
382  //var_dump($tmparray); exit;
383  foreach($tmparray as $key=>$value)
384  {
385  try {
386  if (preg_match('/logo$/',$key)) // Image
387  {
388  //var_dump($value);exit;
389  if (file_exists($value)) $odfHandler->setImage($key, $value);
390  else $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8');
391  }
392  else // Text
393  {
394  $odfHandler->setVars($key, $value, true, 'UTF-8');
395  }
396  }
397  catch(OdfException $e)
398  {
399  }
400  }
401  // Replace tags of lines
402  try
403  {
404  $listlines = $odfHandler->setSegment('lines');
405  foreach ($object->lines as $line)
406  {
407  $tmparray=$this->get_substitutionarray_lines($line,$outputlangs);
408  complete_substitutions_array($tmparray, $outputlangs, $object, $line, "completesubstitutionarray_lines");
409  // Call the ODTSubstitutionLine hook
410  $parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray,'line'=>$line);
411  $reshook=$hookmanager->executeHooks('ODTSubstitutionLine',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
412  foreach($tmparray as $key => $val)
413  {
414  try
415  {
416  $listlines->setVars($key, $val, true, 'UTF-8');
417  }
418  catch(OdfException $e)
419  {
420  }
421  catch(SegmentException $e)
422  {
423  }
424  }
425  $listlines->merge();
426  }
427  $odfHandler->mergeSegment($listlines);
428  }
429  catch(OdfException $e)
430  {
431  $this->error=$e->getMessage();
432  dol_syslog($this->error, LOG_WARNING);
433  return -1;
434  }
435 
436  // Replace labels translated
437  $tmparray=$outputlangs->get_translations_for_substitutions();
438  foreach($tmparray as $key=>$value)
439  {
440  try {
441  $odfHandler->setVars($key, $value, true, 'UTF-8');
442  }
443  catch(OdfException $e)
444  {
445  }
446  }
447 
448  // Call the beforeODTSave hook
449  $parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray);
450  $reshook=$hookmanager->executeHooks('beforeODTSave',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
451 
452  // Write new file
453  if (!empty($conf->global->MAIN_ODT_AS_PDF)) {
454  try {
455  $odfHandler->exportAsAttachedPDF($file);
456  }catch (Exception $e){
457  $this->error=$e->getMessage();
458  return -1;
459  }
460  }
461  else {
462  try {
463  $odfHandler->saveToDisk($file);
464  }catch (Exception $e){
465  $this->error=$e->getMessage();
466  return -1;
467  }
468  }
469  $parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray);
470  $reshook=$hookmanager->executeHooks('afterODTCreation',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
471 
472  if (! empty($conf->global->MAIN_UMASK))
473  @chmod($file, octdec($conf->global->MAIN_UMASK));
474 
475  $odfHandler=null; // Destroy object
476 
477  $this->result = array('fullpath'=>$file);
478 
479  return 1; // Success
480  }
481  else
482  {
483  $this->error=$langs->transnoentities("ErrorCanNotCreateDir",$dir);
484  return -1;
485  }
486  }
487 
488  return -1;
489  }
490 
491 }
492 
get_substitutionarray_lines($line, $outputlangs)
Define array with couple substitution key => substitution value.
</td >< tdclass="liste_titre"align="right"></td ></tr >< trclass="liste_titre">< inputtype="checkbox"onClick="toggle(this)"/> Ref p ref Label p label Duration p duration warehouseinternal SELECT description FROM product_lang WHERE qty< br > qty qty qty StockTooLow img yes disabled img no img no< trclass="oddeven">< td >< inputtype="checkbox"class="check"name="'.$i.'"'.$disabled.'></td >< td >< inputtype="checkbox"class="check"name="choose'.$i.'"></td >< tdclass="nowrap"></td >< td >< inputtype="hidden"name="desc'.$i.'"value="'.dol_escape_htmltag($objp-> description
Only used if Module[ID]Desc translation string is not found.
Definition: replenish.php:554
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
get_substitutionarray_object($object, $outputlangs, $array_key='object')
Define array with couple substitution key => substitution value.
get_substitutionarray_user($user, $outputlangs)
Define array with couple subtitution key => subtitution value.
dol_print_error($db='', $error='', $errors=null)
Affiche message erreur system avec toutes les informations pour faciliter le diagnostic et la remonte...
if(empty($reshook)) $form
View.
Definition: perms.php:103
dol_dir_list($path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="")
Scan a directory and return a list of files/directories.
Definition: files.lib.php:58
Class to manage hooks.
get_substitutionarray_contact($object, $outputlangs, $array_key= 'object')
Define array with couple subtitution key => subtitution value.
Class to manage generation of HTML components Only common components must be here.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='')
Write log message into outputs.
info($langs)
Return description of a module.
img_warning($titlealt= 'default', $moreatt= '')
Show warning logo.
Class to build documents using ODF templates generator.
Parent class of invoice document generators.
get_substitutionarray_mysoc($mysoc, $outputlangs)
Define array with couple subtitution key => subtitution value.
dol_now($mode='gmt')
Return date for now.
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition: repair.php:104
dol_print_date($time, $format='', $tzoutput='tzserver', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
write_file($object, $outputlangs, $srctemplatepath, $hidedetails=0, $hidedesc=0, $hideref=0)
Function to build a document on disk using the generic odt module.
get_substitutionarray_thirdparty($object, $outputlangs)
Define array with couple subtitution key => subtitution value.
dol_mkdir($dir, $dataroot='', $newmask=null)
Creation of a directory (this can create recursive subdir)
make_substitutions($text, $substitutionarray, $outputlangs=null)
Make substition into a text string, replacing keys with vals from $substitutionarray (oldval=>newval)...
get_substitutionarray_other($outputlangs)
Define array with couple subtitution key => subtitution value.
Class to manage invoices.
type
Definition: viewcat.php:283
complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
Complete the $substitutionarray with more entries coming from external module that had set the "subst...