dolibarr  7.0.0-beta
doc_generic_proposal_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) 2016 Charlie Benke <charlie@patas-monkey.com>
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/propale/modules_propale.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 {
40  var $emetteur; // Objet societe qui emet
41 
42  var $phpmin = array(5,2,0); // Minimum version of PHP required by module
43  var $version = 'dolibarr';
44 
45 
51  function __construct($db)
52  {
53  global $conf,$langs,$mysoc;
54 
55  $langs->load("main");
56  $langs->load("companies");
57 
58  $this->db = $db;
59  $this->name = "ODT templates";
60  $this->description = $langs->trans("DocumentModelOdt");
61  $this->scandir = 'PROPALE_ADDON_PDF_ODT_PATH'; // Name of constant that is used to save list of directories to scan
62 
63  // Dimension page pour format A4
64  $this->type = 'odt';
65  $this->page_largeur = 0;
66  $this->page_hauteur = 0;
67  $this->format = array($this->page_largeur,$this->page_hauteur);
68  $this->marge_gauche=0;
69  $this->marge_droite=0;
70  $this->marge_haute=0;
71  $this->marge_basse=0;
72 
73  $this->option_logo = 1; // Affiche logo
74  $this->option_tva = 0; // Gere option tva PROPALE_TVAOPTION
75  $this->option_modereg = 0; // Affiche mode reglement
76  $this->option_condreg = 0; // Affiche conditions reglement
77  $this->option_codeproduitservice = 0; // Affiche code produit-service
78  $this->option_multilang = 1; // Dispo en plusieurs langues
79  $this->option_escompte = 0; // Affiche si il y a eu escompte
80  $this->option_credit_note = 0; // Support credit notes
81  $this->option_freetext = 1; // Support add of a personalised text
82  $this->option_draft_watermark = 0; // Support add of a watermark on drafts
83 
84  // Recupere emetteur
85  $this->emetteur=$mysoc;
86  if (! $this->emetteur->country_code) $this->emetteur->country_code=substr($langs->defaultlang,-2); // By default if not defined
87  }
88 
89 
96  function info($langs)
97  {
98  global $conf,$langs;
99 
100  $langs->load("companies");
101  $langs->load("errors");
102 
103  $form = new Form($this->db);
104 
105  $texte = $this->description.".<br>\n";
106  $texte.= '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
107  $texte.= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
108  $texte.= '<input type="hidden" name="action" value="setModuleOptions">';
109  $texte.= '<input type="hidden" name="param1" value="PROPALE_ADDON_PDF_ODT_PATH">';
110  if ($conf->global->MAIN_PROPAL_CHOOSE_ODT_DOCUMENT > 0)
111  {
112  $texte.= '<input type="hidden" name="param2" value="PROPALE_ADDON_PDF_ODT_DEFAULT">';
113  $texte.= '<input type="hidden" name="param3" value="PROPALE_ADDON_PDF_ODT_TOBILL">';
114  $texte.= '<input type="hidden" name="param4" value="PROPALE_ADDON_PDF_ODT_CLOSED">';
115  }
116  $texte.= '<table class="nobordernopadding" width="100%">';
117 
118  // List of directories area
119  $texte.= '<tr><td>';
120  $texttitle=$langs->trans("ListOfDirectories");
121  $listofdir=explode(',',preg_replace('/[\r\n]+/',',',trim($conf->global->PROPALE_ADDON_PDF_ODT_PATH)));
122  $listoffiles=array();
123  foreach($listofdir as $key=>$tmpdir)
124  {
125  $tmpdir=trim($tmpdir);
126  $tmpdir=preg_replace('/DOL_DATA_ROOT/',DOL_DATA_ROOT,$tmpdir);
127  if (! $tmpdir) {
128  unset($listofdir[$key]); continue;
129  }
130  if (! is_dir($tmpdir)) $texttitle.=img_warning($langs->trans("ErrorDirNotFound",$tmpdir),0);
131  else
132  {
133  $tmpfiles=dol_dir_list($tmpdir,'files',0,'\.(ods|odt)');
134  if (count($tmpfiles)) $listoffiles=array_merge($listoffiles,$tmpfiles);
135  }
136  }
137  $texthelp=$langs->trans("ListOfDirectoriesForModelGenODT");
138  // Add list of substitution keys
139  $texthelp.='<br>'.$langs->trans("FollowingSubstitutionKeysCanBeUsed").'<br>';
140  $texthelp.=$langs->transnoentitiesnoconv("FullListOnOnlineDocumentation"); // This contains an url, we don't modify it
141 
142  $texte.= $form->textwithpicto($texttitle,$texthelp,1,'help','',1);
143  $texte.= '<div><div style="display: inline-block; min-width: 100px; vertical-align: middle;">';
144  $texte.= '<textarea class="flat" cols="60" name="value1">';
145  $texte.=$conf->global->PROPALE_ADDON_PDF_ODT_PATH;
146  $texte.= '</textarea>';
147  $texte.= '</div><div style="display: inline-block; vertical-align: middle;">';
148  $texte.= '<input type="submit" class="button" value="'.$langs->trans("Modify").'" name="Button">';
149  $texte.= '<br></div></div>';
150 
151  // Scan directories
152  $nbofiles=count($listoffiles);
153  if (! empty($conf->global->PROPALE_ADDON_PDF_ODT_PATH))
154  {
155  $texte.=$langs->trans("NumberOfModelFilesFound").': <b>';
156  //$texte.=$nbofiles?'<a id="a_'.get_class($this).'" href="#">':'';
157  $texte.=count($listoffiles);
158  //$texte.=$nbofiles?'</a>':'';
159  $texte.='</b>';
160  }
161 
162  if ($nbofiles)
163  {
164  $texte.='<div id="div_'.get_class($this).'" class="hidden">';
165  foreach($listoffiles as $file)
166  {
167  $texte.=$file['name'].'<br>';
168  }
169  $texte.='<div id="div_'.get_class($this).'">';
170 
171  if ($conf->global->MAIN_PROPAL_CHOOSE_ODT_DOCUMENT > 0)
172  {
173  // Model for creation
174  $liste=ModelePDFPropales::liste_modeles($this->db);
175  $texte.= '<table width="50%;">';
176  $texte.= '<tr>';
177  $texte.= '<td width="60%;">'.$langs->trans("DefaultModelPropalCreate").'</td>';
178  $texte.= '<td colspan="">';
179  $texte.= $form->selectarray('value2',$liste,$conf->global->PROPALE_ADDON_PDF_ODT_DEFAULT);
180  $texte.= "</td></tr>";
181 
182  $texte.= '<tr>';
183  $texte.= '<td width="60%;">'.$langs->trans("DefaultModelPropalToBill").'</td>';
184  $texte.= '<td colspan="">';
185  $texte.= $form->selectarray('value3',$liste,$conf->global->PROPALE_ADDON_PDF_ODT_TOBILL);
186  $texte.= "</td></tr>";
187  $texte.= '<tr>';
188 
189  $texte.= '<td width="60%;">'.$langs->trans("DefaultModelPropalClosed").'</td>';
190  $texte.= '<td colspan="">';
191  $texte.= $form->selectarray('value4',$liste,$conf->global->PROPALE_ADDON_PDF_ODT_CLOSED);
192  $texte.= "</td></tr>";
193  $texte.= '</table>';
194  }
195  }
196 
197  $texte.= '</td>';
198 
199  $texte.= '<td valign="top" rowspan="2" class="hideonsmartphone">';
200  $texte.= $langs->trans("ExampleOfDirectoriesForModelGen");
201  $texte.= '</td>';
202  $texte.= '</tr>';
203 
204  $texte.= '</table>';
205  $texte.= '</form>';
206 
207  return $texte;
208  }
209 
221  function write_file($object,$outputlangs,$srctemplatepath,$hidedetails=0,$hidedesc=0,$hideref=0)
222  {
223  global $user,$langs,$conf,$mysoc,$hookmanager;
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  $outputlangs->load("main");
245  $outputlangs->load("dict");
246  $outputlangs->load("companies");
247  $outputlangs->load("bills");
248 
249  if ($conf->propal->dir_output)
250  {
251  // If $object is id instead of object
252  if (! is_object($object))
253  {
254  $id = $object;
255  $object = new Propal($this->db);
256  $result=$object->fetch($id);
257  if ($result < 0)
258  {
259  dol_print_error($this->db,$object->error);
260  return -1;
261  }
262  }
263 
264  $dir = $conf->propal->dir_output;
265  $objectref = dol_sanitizeFileName($object->ref);
266  if (! preg_match('/specimen/i',$objectref)) $dir.= "/" . $objectref;
267  $file = $dir . "/" . $objectref . ".odt";
268 
269  if (! file_exists($dir))
270  {
271  if (dol_mkdir($dir) < 0)
272  {
273  $this->error=$langs->transnoentities("ErrorCanNotCreateDir",$dir);
274  return -1;
275  }
276  }
277 
278  if (file_exists($dir))
279  {
280  //print "srctemplatepath=".$srctemplatepath; // Src filename
281  $newfile=basename($srctemplatepath);
282  $newfiletmp=preg_replace('/\.od(t|s)/i','',$newfile);
283  $newfiletmp=preg_replace('/template_/i','',$newfiletmp);
284  $newfiletmp=preg_replace('/modele_/i','',$newfiletmp);
285 
286  $newfiletmp=$objectref.'_'.$newfiletmp;
287 
288  // Get extension (ods or odt)
289  $newfileformat=substr($newfile, strrpos($newfile, '.')+1);
290  if ( ! empty($conf->global->MAIN_DOC_USE_TIMING))
291  {
292  $format=$conf->global->MAIN_DOC_USE_TIMING;
293  if ($format == '1') $format='%Y%m%d%H%M%S';
294  $filename=$newfiletmp.'-'.dol_print_date(dol_now(),$format).'.'.$newfileformat;
295  }
296  else
297  {
298  $filename=$newfiletmp.'.'.$newfileformat;
299  }
300  $file=$dir.'/'.$filename;
301  //print "newdir=".$dir;
302  //print "newfile=".$newfile;
303  //print "file=".$file;
304  //print "conf->propal->dir_temp=".$conf->propal->dir_temp;
305 
306  dol_mkdir($conf->propal->dir_temp);
307 
308 
309  // If CUSTOMER contact defined on proposal, we use it
310  $usecontact=false;
311  $arrayidcontact=$object->getIdContact('external','CUSTOMER');
312  if (count($arrayidcontact) > 0)
313  {
314  $usecontact=true;
315  $result=$object->fetch_contact($arrayidcontact[0]);
316  }
317 
318  // Recipient name
319  if (! empty($usecontact))
320  {
321  // On peut utiliser le nom de la societe du contact
322  if (! empty($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT)) $socobject = $object->contact;
323  else {
324  $socobject = $object->thirdparty;
325  // if we have a CUSTOMER contact and we dont use it as recipient we store the contact object for later use
326  $contactobject = $object->contact;
327  }
328  }
329  else
330  {
331  $socobject=$object->thirdparty;
332  }
333  // Make substitution
334  $substitutionarray=array(
335  '__FROM_NAME__' => $this->emetteur->name,
336  '__FROM_EMAIL__' => $this->emetteur->email,
337  '__TOTAL_TTC__' => $object->total_ttc,
338  '__TOTAL_HT__' => $object->total_ht,
339  '__TOTAL_VAT__' => $object->total_vat
340  );
341  complete_substitutions_array($substitutionarray, $langs, $object);
342  // Call the ODTSubstitution hook
343  $parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$substitutionarray);
344  $reshook=$hookmanager->executeHooks('ODTSubstitution',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
345 
346  // Line of free text
347  $newfreetext='';
348  $paramfreetext='PROPOSAL_FREE_TEXT';
349  if (! empty($conf->global->$paramfreetext))
350  {
351  $newfreetext=make_substitutions($conf->global->$paramfreetext,$substitutionarray);
352  }
353 
354  // Open and load template
355  require_once ODTPHP_PATH.'odf.php';
356  try {
357  $odfHandler = new odf(
358  $srctemplatepath,
359  array(
360  'PATH_TO_TMP' => $conf->propal->dir_temp,
361  'ZIP_PROXY' => 'PclZipProxy', // PhpZipProxy or PclZipProxy. Got "bad compression method" error when using PhpZipProxy.
362  'DELIMITER_LEFT' => '{',
363  'DELIMITER_RIGHT' => '}'
364  )
365  );
366  }
367  catch(Exception $e)
368  {
369  $this->error=$e->getMessage();
370  return -1;
371  }
372  // After construction $odfHandler->contentXml contains content and
373  // [!-- BEGIN row.lines --]*[!-- END row.lines --] has been replaced by
374  // [!-- BEGIN lines --]*[!-- END lines --]
375  //print html_entity_decode($odfHandler->__toString());
376  //print exit;
377 
378 
379  // Make substitutions into odt of freetext
380  try {
381  $odfHandler->setVars('free_text', $newfreetext, true, 'UTF-8');
382  }
383  catch(OdfException $e)
384  {
385  }
386 
387  // Make substitutions into odt
388  $array_user=$this->get_substitutionarray_user($user,$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_object($object,$outputlangs);
392  $array_other=$this->get_substitutionarray_other($outputlangs);
393  // retrieve contact information for use in proposal as contact_xxx tags
394  $array_thirdparty_contact = array();
395  if ($usecontact)
396  $array_thirdparty_contact=$this->get_substitutionarray_contact($contactobject,$outputlangs,'contact');
397 
398  $tmparray = array_merge($array_user,$array_soc,$array_thirdparty,$array_objet,$array_other,$array_thirdparty_contact);
399  complete_substitutions_array($tmparray, $outputlangs, $object);
400  $object->fetch_optionals();
401  // Call the ODTSubstitution hook
402  $parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray);
403  $reshook=$hookmanager->executeHooks('ODTSubstitution',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
404  foreach($tmparray as $key=>$value)
405  {
406  try {
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  }
420  }
421  // Replace tags of lines
422  try
423  {
424  $listlines = $odfHandler->setSegment('lines');
425  foreach ($object->lines as $line)
426  {
427  $tmparray=$this->get_substitutionarray_lines($line,$outputlangs);
428  complete_substitutions_array($tmparray, $outputlangs, $object, $line, "completesubstitutionarray_lines");
429  // Call the ODTSubstitutionLine hook
430  $parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray,'line'=>$line);
431  $reshook=$hookmanager->executeHooks('ODTSubstitutionLine',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
432  foreach($tmparray as $key => $val)
433  {
434  try
435  {
436  $listlines->setVars($key, $val, true, 'UTF-8');
437  }
438  catch(OdfException $e)
439  {
440  }
441  catch(SegmentException $e)
442  {
443  }
444  }
445  $listlines->merge();
446  }
447  $odfHandler->mergeSegment($listlines);
448  }
449  catch(OdfException $e)
450  {
451  $this->error=$e->getMessage();
452  dol_syslog($this->error, LOG_WARNING);
453  return -1;
454  }
455 
456  // Replace labels translated
457  $tmparray=$outputlangs->get_translations_for_substitutions();
458  foreach($tmparray as $key=>$value)
459  {
460  try {
461  $odfHandler->setVars($key, $value, true, 'UTF-8');
462  }
463  catch(OdfException $e)
464  {
465  }
466  }
467 
468  // Call the beforeODTSave hook
469  $parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray);
470  $reshook=$hookmanager->executeHooks('beforeODTSave',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
471 
472  // Write new file
473  if (!empty($conf->global->MAIN_ODT_AS_PDF)) {
474  try {
475  $odfHandler->exportAsAttachedPDF($file);
476  }catch (Exception $e){
477  $this->error=$e->getMessage();
478  return -1;
479  }
480  }
481  else {
482  try {
483  $odfHandler->saveToDisk($file);
484  }catch (Exception $e){
485  $this->error=$e->getMessage();
486  return -1;
487  }
488  }
489  $parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray);
490  $reshook=$hookmanager->executeHooks('afterODTCreation',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
491 
492  if (! empty($conf->global->MAIN_UMASK))
493  @chmod($file, octdec($conf->global->MAIN_UMASK));
494 
495  $odfHandler=null; // Destroy object
496 
497  $this->result = array('fullpath'=>$file);
498 
499  return 1; // Success
500  }
501  else
502  {
503  $this->error=$langs->transnoentities("ErrorCanNotCreateDir",$dir);
504  return -1;
505  }
506  }
507 
508  return -1;
509  }
510 
511 }
512 
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.
info($langs)
Return description of a module.
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
Classe mere des modeles de propale.
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.
get_substitutionarray_mysoc($mysoc, $outputlangs)
Define array with couple subtitution key => subtitution value.
dol_now($mode='gmt')
Return date for now.
Class to build documents using ODF templates generator.
$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).
static liste_modeles($db, $maxfilenamelength=0)
Return list of active generation modules.
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.
write_file($object, $outputlangs, $srctemplatepath, $hidedetails=0, $hidedesc=0, $hideref=0)
Function to build a document on disk using the generic odt module.
type
Definition: viewcat.php:283
Class to manage proposals.
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...