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