dolibarr  9.0.0
doc_generic_product_odt.modules.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2010-2012 Laurent Destailleur <eldy@products.sourceforge.net>
3  * Copyright (C) 2012 Juanjo Menent <jmenent@2byte.es>
4  * Copyright (C) 2018 Frédéric France <frederic.france@netlogic.fr>
5  *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 * or see http://www.gnu.org/
19 */
20 
27 require_once DOL_DOCUMENT_ROOT.'/core/modules/product/modules_product.class.php';
28 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
29 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
30 require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
31 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
32 require_once DOL_DOCUMENT_ROOT.'/core/lib/doc.lib.php';
33 
34 
39 {
44  public $emetteur;
45 
50  public $phpmin = array(5, 4);
51 
56  public $version = 'dolibarr';
57 
58 
64  function __construct($db)
65  {
66  global $conf, $langs, $mysoc;
67 
68  // Load translation files required by the page
69  $langs->loadLangs(array("main","companies"));
70 
71  $this->db = $db;
72  $this->name = "ODT templates";
73  $this->description = $langs->trans("DocumentModelOdt");
74  $this->scandir = 'PRODUCT_ADDON_PDF_ODT_PATH'; // Name of constant that is used to save list of directories to scan
75 
76  // Dimension page pour format A4
77  $this->type = 'odt';
78  $this->page_largeur = 0;
79  $this->page_hauteur = 0;
80  $this->format = array($this->page_largeur,$this->page_hauteur);
81  $this->marge_gauche=0;
82  $this->marge_droite=0;
83  $this->marge_haute=0;
84  $this->marge_basse=0;
85 
86  $this->option_logo = 1; // Affiche logo
87  $this->option_tva = 0; // Gere option tva PRODUCT_TVAOPTION
88  $this->option_modereg = 0; // Affiche mode reglement
89  $this->option_condreg = 0; // Affiche conditions reglement
90  $this->option_codeproduitservice = 0; // Affiche code produit-service
91  $this->option_multilang = 1; // Dispo en plusieurs langues
92  $this->option_escompte = 0; // Affiche si il y a eu escompte
93  $this->option_credit_note = 0; // Support credit notes
94  $this->option_freetext = 1; // Support add of a personalised text
95  $this->option_draft_watermark = 0; // Support add of a watermark on drafts
96 
97  // Recupere emetteur
98  $this->emetteur=$mysoc;
99  if (! $this->emetteur->country_code) $this->emetteur->country_code=substr($langs->defaultlang,-2); // By default if not defined
100  }
101 
102 
109  function info($langs)
110  {
111  global $conf, $langs;
112 
113  // Load translation files required by the page
114  $langs->loadLangs(array("errors","companies"));
115 
116  $form = new Form($this->db);
117 
118  $texte = $this->description.".<br>\n";
119  $texte.= '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
120  $texte.= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
121  $texte.= '<input type="hidden" name="action" value="setModuleOptions">';
122  $texte.= '<input type="hidden" name="param1" value="PRODUCT_ADDON_PDF_ODT_PATH">';
123  if ($conf->global->MAIN_PROPAL_CHOOSE_ODT_DOCUMENT > 0)
124  {
125  $texte.= '<input type="hidden" name="param2" value="PRODUCT_ADDON_PDF_ODT_DEFAULT">';
126  $texte.= '<input type="hidden" name="param3" value="PRODUCT_ADDON_PDF_ODT_TOBILL">';
127  $texte.= '<input type="hidden" name="param4" value="PRODUCT_ADDON_PDF_ODT_CLOSED">';
128  }
129  $texte.= '<table class="nobordernopadding" width="100%">';
130 
131  // List of directories area
132  $texte.= '<tr><td>';
133  $texttitle=$langs->trans("ListOfDirectories");
134  $listofdir=explode(',',preg_replace('/[\r\n]+/',',',trim($conf->global->PRODUCT_ADDON_PDF_ODT_PATH)));
135  $listoffiles=array();
136  foreach($listofdir as $key=>$tmpdir)
137  {
138  $tmpdir=trim($tmpdir);
139  $tmpdir=preg_replace('/DOL_DATA_ROOT/',DOL_DATA_ROOT,$tmpdir);
140  if (! $tmpdir) {
141  unset($listofdir[$key]); continue;
142  }
143  if (! is_dir($tmpdir)) $texttitle.=img_warning($langs->trans("ErrorDirNotFound",$tmpdir),0);
144  else
145  {
146  $tmpfiles=dol_dir_list($tmpdir,'files',0,'\.(ods|odt)');
147  if (count($tmpfiles)) $listoffiles=array_merge($listoffiles,$tmpfiles);
148  }
149  }
150  $texthelp=$langs->trans("ListOfDirectoriesForModelGenODT");
151  // Add list of substitution keys
152  $texthelp.='<br>'.$langs->trans("FollowingSubstitutionKeysCanBeUsed").'<br>';
153  $texthelp.=$langs->transnoentitiesnoconv("FullListOnOnlineDocumentation"); // This contains an url, we don't modify it
154 
155  $texte.= $form->textwithpicto($texttitle,$texthelp,1,'help','',1);
156  $texte.= '<div><div style="display: inline-block; min-width: 100px; vertical-align: middle;">';
157  $texte.= '<textarea class="flat" cols="60" name="value1">';
158  $texte.=$conf->global->PRODUCT_ADDON_PDF_ODT_PATH;
159  $texte.= '</textarea>';
160  $texte.= '</div><div style="display: inline-block; vertical-align: middle;">';
161  $texte.= '<input type="submit" class="button" value="'.$langs->trans("Modify").'" name="Button">';
162  $texte.= '<br></div></div>';
163 
164  // Scan directories
165  if (count($listofdir))
166  {
167  $texte.=$langs->trans("NumberOfModelFilesFound").': <b>'.count($listoffiles).'</b>';
168 
169  /*if ($conf->global->MAIN_PRODUCT_CHOOSE_ODT_DOCUMENT > 0)
170  {
171  // Model for creation
172  $liste=ModelePDFProduct::liste_modeles($this->db);
173  $texte.= '<table width="50%;">';
174  $texte.= '<tr>';
175  $texte.= '<td width="60%;">'.$langs->trans("DefaultModelPropalCreate").'</td>';
176  $texte.= '<td colspan="">';
177  $texte.= $form->selectarray('value2',$liste,$conf->global->PRODUCT_ADDON_PDF_ODT_DEFAULT);
178  $texte.= "</td></tr>";
179 
180  $texte.= '<tr>';
181  $texte.= '<td width="60%;">'.$langs->trans("DefaultModelPropalToBill").'</td>';
182  $texte.= '<td colspan="">';
183  $texte.= $form->selectarray('value3',$liste,$conf->global->PRODUCT_ADDON_PDF_ODT_TOBILL);
184  $texte.= "</td></tr>";
185  $texte.= '<tr>';
186 
187  $texte.= '<td width="60%;">'.$langs->trans("DefaultModelPropalClosed").'</td>';
188  $texte.= '<td colspan="">';
189  $texte.= $form->selectarray('value4',$liste,$conf->global->PRODUCT_ADDON_PDF_ODT_CLOSED);
190  $texte.= "</td></tr>";
191  $texte.= '</table>';
192  }*/
193  }
194 
195  $texte.= '</td>';
196 
197  $texte.= '<td valign="top" rowspan="2" class="hideonsmartphone">';
198  $texte.= $langs->trans("ExampleOfDirectoriesForModelGen");
199  $texte.= '</td>';
200  $texte.= '</tr>';
201 
202  $texte.= '</table>';
203  $texte.= '</form>';
204 
205  return $texte;
206  }
207 
208  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
220  function write_file($object,$outputlangs,$srctemplatepath,$hidedetails=0,$hidedesc=0,$hideref=0)
221  {
222  // phpcs:enable
223  global $product,$langs,$conf,$mysoc,$hookmanager,$user;
224 
225  if (empty($srctemplatepath))
226  {
227  dol_syslog("doc_generic_odt::write_file parameter srctemplatepath empty", LOG_WARNING);
228  return -1;
229  }
230 
231  // Add odtgeneration hook
232  if (! is_object($hookmanager))
233  {
234  include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
235  $hookmanager=new HookManager($this->db);
236  }
237  $hookmanager->initHooks(array('odtgeneration'));
238  global $action;
239 
240  if (! is_object($outputlangs)) $outputlangs=$langs;
241  $sav_charset_output=$outputlangs->charset_output;
242  $outputlangs->charset_output='UTF-8';
243 
244  // Load translation files required by the page
245  $outputlangs->loadLangs(array("main", "dict", "companies", "bills"));
246 
247  if ($conf->produit->dir_output)
248  {
249  // If $object is id instead of object
250  if (! is_object($object))
251  {
252  $id = $object;
253  $object = new Product($this->db);
254  $result=$object->fetch($id);
255  if ($result < 0)
256  {
257  dol_print_error($this->db,$object->error);
258  return -1;
259  }
260  }
261  $productFournisseur = new ProductFournisseur($this->db);
262  $supplierprices = $productFournisseur->list_product_fournisseur_price($object->id);
263  $object->supplierprices = $supplierprices;
264 
265  $dir = $conf->produit->dir_output;
266  $objectref = dol_sanitizeFileName($object->ref);
267  if (! preg_match('/specimen/i',$objectref)) $dir.= "/" . $objectref;
268  $file = $dir . "/" . $objectref . ".odt";
269 
270  if (! file_exists($dir))
271  {
272  if (dol_mkdir($dir) < 0)
273  {
274  $this->error=$langs->transnoentities("ErrorCanNotCreateDir",$dir);
275  return -1;
276  }
277  }
278 
279  if (file_exists($dir))
280  {
281  //print "srctemplatepath=".$srctemplatepath; // Src filename
282  $newfile=basename($srctemplatepath);
283  $newfiletmp=preg_replace('/\.od(t|s)/i','',$newfile);
284  $newfiletmp=preg_replace('/template_/i','',$newfiletmp);
285  $newfiletmp=preg_replace('/modele_/i','',$newfiletmp);
286 
287  $newfiletmp=$objectref.'_'.$newfiletmp;
288 
289  // Get extension (ods or odt)
290  $newfileformat=substr($newfile, strrpos($newfile, '.')+1);
291  if ( ! empty($conf->global->MAIN_DOC_USE_TIMING))
292  {
293  $format=$conf->global->MAIN_DOC_USE_TIMING;
294  if ($format == '1') $format='%Y%m%d%H%M%S';
295  $filename=$newfiletmp.'-'.dol_print_date(dol_now(),$format).'.'.$newfileformat;
296  }
297  else
298  {
299  $filename=$newfiletmp.'.'.$newfileformat;
300  }
301  $file=$dir.'/'.$filename;
302  //print "newdir=".$dir;
303  //print "newfile=".$newfile;
304  //print "file=".$file;
305  //print "conf->produit->dir_temp=".$conf->produit->dir_temp;
306 
307  dol_mkdir($conf->produit->dir_temp);
308 
309 
310  // If CUSTOMER contact defined on product, we use it
311  $usecontact=false;
312  $arrayidcontact=$object->getIdContact('external','CUSTOMER');
313  if (count($arrayidcontact) > 0)
314  {
315  $usecontact=true;
316  $result=$object->fetch_contact($arrayidcontact[0]);
317  }
318 
319  // Recipient name
320  $contactobject=null;
321  if (! empty($usecontact))
322  {
323  // On peut utiliser le nom de la societe du contact
324  if (! empty($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT)) $socobject = $object->contact;
325  else {
326  $socobject = $object->thirdparty;
327  // if we have a CUSTOMER contact and we dont use it as recipient we store the contact object for later use
328  $contactobject = $object->contact;
329  }
330  }
331  else
332  {
333  $socobject=$object->thirdparty;
334  }
335  // Make substitution
336  $substitutionarray=array(
337  '__FROM_NAME__' => $this->emetteur->name,
338  '__FROM_EMAIL__' => $this->emetteur->email,
339  '__TOTAL_TTC__' => $object->total_ttc,
340  '__TOTAL_HT__' => $object->total_ht,
341  '__TOTAL_VAT__' => $object->total_vat
342  );
343  complete_substitutions_array($substitutionarray, $langs, $object);
344  // Call the ODTSubstitution hook
345  $parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$substitutionarray);
346  $reshook=$hookmanager->executeHooks('ODTSubstitution',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
347 
348  // Line of free text
349  $newfreetext='';
350  $paramfreetext='product_FREE_TEXT';
351  if (! empty($conf->global->$paramfreetext))
352  {
353  $newfreetext=make_substitutions($conf->global->$paramfreetext,$substitutionarray);
354  }
355 
356  // Open and load template
357  require_once ODTPHP_PATH.'odf.php';
358  try {
359  $odfHandler = new odf(
360  $srctemplatepath,
361  array(
362  'PATH_TO_TMP' => $conf->produit->dir_temp,
363  'ZIP_PROXY' => 'PclZipProxy', // PhpZipProxy or PclZipProxy. Got "bad compression method" error when using PhpZipProxy.
364  'DELIMITER_LEFT' => '{',
365  'DELIMITER_RIGHT' => '}'
366  )
367  );
368  }
369  catch (Exception $e)
370  {
371  $this->error=$e->getMessage();
372  dol_syslog($e->getMessage(), LOG_INFO);
373  return -1;
374  }
375  // After construction $odfHandler->contentXml contains content and
376  // [!-- BEGIN row.lines --]*[!-- END row.lines --] has been replaced by
377  // [!-- BEGIN lines --]*[!-- END lines --]
378  //print html_entity_decode($odfHandler->__toString());
379  //print exit;
380 
381  $object->fetch_optionals();
382 
383  // Make substitutions into odt of freetext
384  try {
385  $odfHandler->setVars('free_text', $newfreetext, true, 'UTF-8');
386  }
387  catch (OdfException $e)
388  {
389  dol_syslog($e->getMessage(), LOG_INFO);
390  }
391 
392  // Define substitution array
393  $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object);
394  $array_object_from_properties = $this->get_substitutionarray_each_var_object($object, $outputlangs);
395  //$array_objet=$this->get_substitutionarray_object($object,$outputlangs);
396  $array_user=$this->get_substitutionarray_user($user,$outputlangs);
397  $array_soc=$this->get_substitutionarray_mysoc($mysoc,$outputlangs);
398  $array_thirdparty=$this->get_substitutionarray_thirdparty($socobject,$outputlangs);
399  $array_other=$this->get_substitutionarray_other($outputlangs);
400  // retrieve contact information for use in object as contact_xxx tags
401  $array_thirdparty_contact = array();
402  if ($usecontact && is_object($contactobject)) $array_thirdparty_contact=$this->get_substitutionarray_contact($contactobject,$outputlangs,'contact');
403 
404  $tmparray = array_merge($substitutionarray,$array_object_from_properties,$array_user,$array_soc,$array_thirdparty,$array_other,$array_thirdparty_contact);
405  complete_substitutions_array($tmparray, $outputlangs, $object);
406 
407  // Call the ODTSubstitution hook
408  $parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray);
409  $reshook=$hookmanager->executeHooks('ODTSubstitution',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
410 
411  foreach($tmparray as $key=>$value)
412  {
413  try {
414  if (preg_match('/logo$/',$key)) // Image
415  {
416  if (file_exists($value)) $odfHandler->setImage($key, $value);
417  else $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8');
418  }
419  else // Text
420  {
421  $odfHandler->setVars($key, $value, true, 'UTF-8');
422  }
423  }
424  catch (OdfException $e)
425  {
426  dol_syslog($e->getMessage(), LOG_INFO);
427  }
428  }
429  // Replace tags of lines
430  try
431  {
432  $listlines = $odfHandler->setSegment('supplierprices');
433  if(!empty($object->supplierprices)){
434  foreach ($object->supplierprices as $supplierprice)
435  {
436  $array_lines = $this->get_substitutionarray_each_var_object($supplierprice, $outputlangs);
437  complete_substitutions_array($array_lines, $outputlangs, $object, $supplierprice, "completesubstitutionarray_lines");
438  // Call the ODTSubstitutionLine hook
439  $parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$array_lines,'line'=>$supplierprice);
440  $reshook=$hookmanager->executeHooks('ODTSubstitutionLine',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
441  foreach($array_lines as $key => $val)
442  {
443  try
444  {
445  $listlines->setVars($key, $val, true, 'UTF-8');
446  }
447  catch (OdfException $e)
448  {
449  dol_syslog($e->getMessage(), LOG_INFO);
450  }
451  catch (SegmentException $e)
452  {
453  dol_syslog($e->getMessage(), LOG_INFO);
454  }
455  }
456  $listlines->merge();
457  }
458  }
459  $odfHandler->mergeSegment($listlines);
460  }
461  catch (OdfException $e)
462  {
463  $this->error=$e->getMessage();
464  dol_syslog($this->error, LOG_WARNING);
465  return -1;
466  }
467 
468  // Replace labels translated
469  $tmparray=$outputlangs->get_translations_for_substitutions();
470  foreach($tmparray as $key=>$value)
471  {
472  try {
473  $odfHandler->setVars($key, $value, true, 'UTF-8');
474  }
475  catch(OdfException $e)
476  {
477  dol_syslog($e->getMessage(), LOG_INFO);
478  }
479  }
480 
481  // Call the beforeODTSave hook
482  $parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs);
483  $reshook=$hookmanager->executeHooks('beforeODTSave',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
484 
485  // Write new file
486  if (!empty($conf->global->MAIN_ODT_AS_PDF)) {
487  try {
488  $odfHandler->exportAsAttachedPDF($file);
489  } catch (Exception $e) {
490  $this->error=$e->getMessage();
491  dol_syslog($e->getMessage(), LOG_INFO);
492  return -1;
493  }
494  }
495  else {
496  try {
497  $odfHandler->saveToDisk($file);
498  } catch (Exception $e) {
499  $this->error=$e->getMessage();
500  dol_syslog($e->getMessage(), LOG_INFO);
501  return -1;
502  }
503  }
504 
505  $reshook=$hookmanager->executeHooks('afterODTCreation',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
506 
507  if (! empty($conf->global->MAIN_UMASK))
508  @chmod($file, octdec($conf->global->MAIN_UMASK));
509 
510  $odfHandler=null; // Destroy object
511 
512  $this->result = array('fullpath'=>$file);
513 
514  return 1; // Success
515  }
516  else
517  {
518  $this->error=$langs->transnoentities("ErrorCanNotCreateDir",$dir);
519  return -1;
520  }
521  }
522 
523  return -1;
524  }
525 }
img_warning($titlealt='default', $moreatt='')
Show warning logo.
write_file($object, $outputlangs, $srctemplatepath, $hidedetails=0, $hidedesc=0, $hideref=0)
Function to build a document on disk using the generic odt module.
Class to build documents using ODF templates generator.
</td >< td class="liste_titre" align="right"></td ></tr >< tr class="liste_titre">< input type="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< tr class="oddeven">< td >< input type="checkbox" class="check" name="' . $i . '"' . $disabled . '></td >< td >< input type="checkbox" class="check" name="choose'.$i.'"></td >< td class="nowrap"></td >< td >< input type="hidden" name="desc' . $i . '" value="' . dol_escape_htmltag($objp-> description
Only used if Module[ID]Desc translation string is not found.
Definition: replenish.php:573
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
get_substitutionarray_each_var_object(&$object, $outputlangs, $recursive=true)
Define array with couple subtitution key => subtitution value.
Class to manage products or services.
$version
Dolibarr version of the loaded document string.
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...
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition: repair.php:103
info($langs)
Return description of a module.
getCommonSubstitutionArray($outputlangs, $onlykey=0, $exclude=null, $object=null)
Return array of possible common substitutions.
Class to manage hooks.
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.
type
Definition: viewcat.php:284
get_substitutionarray_mysoc($mysoc, $outputlangs)
Define array with couple subtitution key => subtitution value.
dol_dir_list($path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0)
Scan a directory and return a list of files/directories.
Definition: files.lib.php:59
dol_now($mode='gmt')
Return date for now.
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_contact($object, $outputlangs, $array_key='object')
Define array with couple subtitution key => subtitution value.
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)
Parent class to manage intervention document templates.
make_substitutions($text, $substitutionarray, $outputlangs=null)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
get_substitutionarray_other($outputlangs)
Define array with couple subtitution key => subtitution value.
Class to manage predefined suppliers products.
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...