dolibarr  7.0.0-beta
doc_generic_order_odt.modules.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2010-2012 Laurent Destailleur <eldy@users.sourceforge.net>
3  * Copyright (C) 2012 Juanjo Menent <jmenent@2byte.es>
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/commande/modules_commande.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 templates";
61  $this->description = $langs->trans("DocumentModelOdt");
62  $this->scandir = 'COMMANDE_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 COMMANDE_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); // By default if not defined
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="COMMANDE_ADDON_PDF_ODT_PATH">';
111  $texte.= '<table class="nobordernopadding" width="100%">';
112 
113  // List of directories area
114  $texte.= '<tr><td>';
115  $texttitle=$langs->trans("ListOfDirectories");
116  $listofdir=explode(',',preg_replace('/[\r\n]+/',',',trim($conf->global->COMMANDE_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->COMMANDE_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->COMMANDE_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 
157  if ($nbofiles)
158  {
159  $texte.='<div id="div_'.get_class($this).'" class="hidden">';
160  foreach($listoffiles as $file)
161  {
162  $texte.=$file['name'].'<br>';
163  }
164  $texte.='<div id="div_'.get_class($this).'">';
165  }
166 
167  $texte.= '</td>';
168 
169  $texte.= '<td valign="top" rowspan="2" class="hideonsmartphone">';
170  $texte.= $langs->trans("ExampleOfDirectoriesForModelGen");
171  $texte.= '</td>';
172  $texte.= '</tr>';
173 
174  $texte.= '</table>';
175  $texte.= '</form>';
176 
177  return $texte;
178  }
179 
191  function write_file($object,$outputlangs,$srctemplatepath,$hidedetails=0,$hidedesc=0,$hideref=0)
192  {
193  global $user,$langs,$conf,$mysoc,$hookmanager;
194 
195  if (empty($srctemplatepath))
196  {
197  dol_syslog("doc_generic_odt::write_file parameter srctemplatepath empty", LOG_WARNING);
198  return -1;
199  }
200 
201  // Add odtgeneration hook
202  if (! is_object($hookmanager))
203  {
204  include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
205  $hookmanager=new HookManager($this->db);
206  }
207  $hookmanager->initHooks(array('odtgeneration'));
208  global $action;
209 
210  if (! is_object($outputlangs)) $outputlangs=$langs;
211  $sav_charset_output=$outputlangs->charset_output;
212  $outputlangs->charset_output='UTF-8';
213 
214  $outputlangs->load("main");
215  $outputlangs->load("dict");
216  $outputlangs->load("companies");
217  $outputlangs->load("bills");
218 
219  if ($conf->commande->dir_output)
220  {
221  // If $object is id instead of object
222  if (! is_object($object))
223  {
224  $id = $object;
225  $object = new Commande($this->db);
226  $result=$object->fetch($id);
227  if ($result < 0)
228  {
229  dol_print_error($this->db,$object->error);
230  return -1;
231  }
232  }
233 
234  $dir = $conf->commande->dir_output;
235  $objectref = dol_sanitizeFileName($object->ref);
236  if (! preg_match('/specimen/i',$objectref)) $dir.= "/" . $objectref;
237  $file = $dir . "/" . $objectref . ".odt";
238 
239  if (! file_exists($dir))
240  {
241  if (dol_mkdir($dir) < 0)
242  {
243  $this->error=$langs->transnoentities("ErrorCanNotCreateDir",$dir);
244  return -1;
245  }
246  }
247 
248  if (file_exists($dir))
249  {
250  //print "srctemplatepath=".$srctemplatepath; // Src filename
251  $newfile=basename($srctemplatepath);
252  $newfiletmp=preg_replace('/\.od(t|s)/i','',$newfile);
253  $newfiletmp=preg_replace('/template_/i','',$newfiletmp);
254  $newfiletmp=preg_replace('/modele_/i','',$newfiletmp);
255  $newfiletmp=$objectref.'_'.$newfiletmp;
256  //$file=$dir.'/'.$newfiletmp.'.'.dol_print_date(dol_now(),'%Y%m%d%H%M%S').'.odt';
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  //print "newdir=".$dir;
271  //print "newfile=".$newfile;
272  //print "file=".$file;
273  //print "conf->societe->dir_temp=".$conf->societe->dir_temp;
274 
275  dol_mkdir($conf->commande->dir_temp);
276 
277 
278  // If CUSTOMER contact defined on order, we use it
279  $usecontact=false;
280  $arrayidcontact=$object->getIdContact('external','CUSTOMER');
281  if (count($arrayidcontact) > 0)
282  {
283  $usecontact=true;
284  $result=$object->fetch_contact($arrayidcontact[0]);
285  }
286 
287  // Recipient name
288  if (! empty($usecontact))
289  {
290  // On peut utiliser le nom de la societe du contact
291  if (! empty($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT)) $socobject = $object->contact;
292  else {
293  $socobject = $object->thirdparty;
294  // if we have a CUSTOMER contact and we dont use it as recipient we store the contact object for later use
295  $contactobject = $object->contact;
296  }
297  }
298  else
299  {
300  $socobject=$object->thirdparty;
301  }
302 
303  // Make substitution
304  $substitutionarray=array(
305  '__FROM_NAME__' => $this->emetteur->name,
306  '__FROM_EMAIL__' => $this->emetteur->email,
307  '__TOTAL_TTC__' => $object->total_ttc,
308  '__TOTAL_HT__' => $object->total_ht,
309  '__TOTAL_VAT__' => $object->total_vat
310  );
311  complete_substitutions_array($substitutionarray, $langs, $object);
312  // Call the ODTSubstitution hook
313  $parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$substitutionarray);
314  $reshook=$hookmanager->executeHooks('ODTSubstitution',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
315 
316  // Line of free text
317  $newfreetext='';
318  $paramfreetext='ORDER_FREE_TEXT';
319  if (! empty($conf->global->$paramfreetext))
320  {
321  $newfreetext=make_substitutions($conf->global->$paramfreetext,$substitutionarray);
322  }
323 
324  // Open and load template
325  require_once ODTPHP_PATH.'odf.php';
326  try {
327  $odfHandler = new odf(
328  $srctemplatepath,
329  array(
330  'PATH_TO_TMP' => $conf->commande->dir_temp,
331  'ZIP_PROXY' => 'PclZipProxy', // PhpZipProxy or PclZipProxy. Got "bad compression method" error when using PhpZipProxy.
332  'DELIMITER_LEFT' => '{',
333  'DELIMITER_RIGHT' => '}'
334  )
335  );
336  }
337  catch(Exception $e)
338  {
339  $this->error=$e->getMessage();
340  return -1;
341  }
342  // After construction $odfHandler->contentXml contains content and
343  // [!-- BEGIN row.lines --]*[!-- END row.lines --] has been replaced by
344  // [!-- BEGIN lines --]*[!-- END lines --]
345  //print html_entity_decode($odfHandler->__toString());
346  //print exit;
347 
348 
349  // Make substitutions into odt of freetext
350  try {
351  $odfHandler->setVars('free_text', $newfreetext, true, 'UTF-8');
352  }
353  catch(OdfException $e)
354  {
355  }
356 
357  // Make substitutions into odt
358  $array_user=$this->get_substitutionarray_user($user,$outputlangs);
359  $array_soc=$this->get_substitutionarray_mysoc($mysoc,$outputlangs);
360  $array_thirdparty=$this->get_substitutionarray_thirdparty($socobject,$outputlangs);
361  $array_objet=$this->get_substitutionarray_object($object,$outputlangs);
362  $array_other=$this->get_substitutionarray_other($outputlangs);
363  // retrieve contact information for use in order as contact_xxx tags
364  $array_thirdparty_contact = array();
365  if ($usecontact)
366  $array_thirdparty_contact=$this->get_substitutionarray_contact($contactobject,$outputlangs,'contact');
367 
368  $tmparray = array_merge($array_user,$array_soc,$array_thirdparty,$array_objet,$array_other,$array_thirdparty_contact);
369  complete_substitutions_array($tmparray, $outputlangs, $object);
370  // Call the ODTSubstitution hook
371 
372  $parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray);
373  $reshook=$hookmanager->executeHooks('ODTSubstitution',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
374 
375  foreach($tmparray as $key=>$value)
376  {
377  try {
378  if (preg_match('/logo$/',$key)) // Image
379  {
380  if (file_exists($value)) $odfHandler->setImage($key, $value);
381  else $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8');
382  }
383  else // Text
384  {
385  $odfHandler->setVars($key, $value, true, 'UTF-8');
386  }
387  }
388  catch(OdfException $e)
389  {
390  }
391  }
392  // Replace tags of lines
393  try
394  {
395  $listlines = $odfHandler->setSegment('lines');
396  foreach ($object->lines as $line)
397  {
398  $tmparray=$this->get_substitutionarray_lines($line,$outputlangs);
399  complete_substitutions_array($tmparray, $outputlangs, $object, $line, "completesubstitutionarray_lines");
400  // Call the ODTSubstitutionLine hook
401  $parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray,'line'=>$line);
402  $reshook=$hookmanager->executeHooks('ODTSubstitutionLine',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
403  foreach($tmparray as $key => $val)
404  {
405  try
406  {
407  $listlines->setVars($key, $val, true, 'UTF-8');
408  }
409  catch(OdfException $e)
410  {
411  }
412  catch(SegmentException $e)
413  {
414  }
415  }
416  $listlines->merge();
417  }
418  $odfHandler->mergeSegment($listlines);
419  }
420  catch(OdfException $e)
421  {
422  $this->error=$e->getMessage();
423  dol_syslog($this->error, LOG_WARNING);
424  return -1;
425  }
426 
427  // Replace labels translated
428  $tmparray=$outputlangs->get_translations_for_substitutions();
429  foreach($tmparray as $key=>$value)
430  {
431  try {
432  $odfHandler->setVars($key, $value, true, 'UTF-8');
433  }
434  catch(OdfException $e)
435  {
436  }
437  }
438 
439  // Call the beforeODTSave hook
440 
441  $parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray);
442  $reshook=$hookmanager->executeHooks('beforeODTSave',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
443 
444  // Write new file
445  if (!empty($conf->global->MAIN_ODT_AS_PDF)) {
446  try {
447  $odfHandler->exportAsAttachedPDF($file);
448  }catch (Exception $e){
449  $this->error=$e->getMessage();
450  return -1;
451  }
452  }
453  else {
454  try {
455  $odfHandler->saveToDisk($file);
456  }catch (Exception $e){
457  $this->error=$e->getMessage();
458  return -1;
459  }
460  }
461 
462  $parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray);
463  $reshook=$hookmanager->executeHooks('afterODTCreation',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
464 
465  if (! empty($conf->global->MAIN_UMASK))
466  @chmod($file, octdec($conf->global->MAIN_UMASK));
467 
468  $odfHandler=null; // Destroy object
469 
470  $this->result = array('fullpath'=>$file);
471 
472  return 1; // Success
473  }
474  else
475  {
476  $this->error=$langs->transnoentities("ErrorCanNotCreateDir",$dir);
477  return -1;
478  }
479  }
480 
481  return -1;
482  }
483 
484 }
485 
info($langs)
Return description of a module.
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.
img_warning($titlealt= 'default', $moreatt= '')
Show warning logo.
Class to manage customers orders.
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).
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)
Class to build documents using ODF templates generator.
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.
type
Definition: viewcat.php:283
Parent class for orders models.
write_file($object, $outputlangs, $srctemplatepath, $hidedetails=0, $hidedesc=0, $hideref=0)
Function to build a document on disk using the generic odt module.
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...