dolibarr  7.0.0-beta
doc_generic_supplier_proposal_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) 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/supplier_proposal/modules_supplier_proposal.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 = 'SUPPLIER_PROPOSAL_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="SUPPLIER_PROPOSAL_ADDON_PDF_ODT_PATH">';
110  if ($conf->global->MAIN_SUPPLIER_PROPOSAL_CHOOSE_ODT_DOCUMENT > 0)
111  {
112  $texte.= '<input type="hidden" name="param2" value="SUPPLIER_PROPOSAL_ADDON_PDF_ODT_DEFAULT">';
113  $texte.= '<input type="hidden" name="param3" value="SUPPLIER_PROPOSAL_ADDON_PDF_ODT_TOBILL">';
114  $texte.= '<input type="hidden" name="param4" value="SUPPLIER_PROPOSAL_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->SUPPLIER_PROPOSAL_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->SUPPLIER_PROPOSAL_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->SUPPLIER_PROPOSAL_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_SUPPLIER_PROPOSAL_CHOOSE_ODT_DOCUMENT > 0)
172  {
173  // Model for creation
175  $texte.= '<table width="50%;">';
176  $texte.= '<tr>';
177  $texte.= '<td width="60%;">'.$langs->trans("DefaultModelSupplierProposalCreate").'</td>';
178  $texte.= '<td colspan="">';
179  $texte.= $form->selectarray('value2',$liste,$conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_DEFAULT);
180  $texte.= "</td></tr>";
181 
182  $texte.= '<tr>';
183  $texte.= '<td width="60%;">'.$langs->trans("DefaultModelSupplierProposalToBill").'</td>';
184  $texte.= '<td colspan="">';
185  $texte.= $form->selectarray('value3',$liste,$conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_TOBILL);
186  $texte.= "</td></tr>";
187  $texte.= '<tr>';
188 
189  $texte.= '<td width="60%;">'.$langs->trans("DefaultModelSupplierProposalClosed").'</td>';
190  $texte.= '<td colspan="">';
191  $texte.= $form->selectarray('value4',$liste,$conf->global->SUPPLIER_PROPOSAL_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->supplier_proposal->dir_output)
250  {
251  // If $object is id instead of object
252  if (! is_object($object))
253  {
254  $id = $object;
255  $object = new SupplierProposal($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->supplier_proposal->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->supplier_proposal->dir_temp);
307 
308 
309  // If BILLING contact defined on invoice, we use it
310  $usecontact=false;
311  $arrayidcontact=$object->getIdContact('external','BILLING');
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 $socobject = $object->thirdparty;
324  }
325  else
326  {
327  $socobject=$object->thirdparty;
328  }
329 
330  // Make substitution
331  $substitutionarray=array(
332  '__FROM_NAME__' => $this->emetteur->name,
333  '__FROM_EMAIL__' => $this->emetteur->email,
334  '__TOTAL_TTC__' => $object->total_ttc,
335  '__TOTAL_HT__' => $object->total_ht,
336  '__TOTAL_VAT__' => $object->total_vat
337  );
338  complete_substitutions_array($substitutionarray, $langs, $object);
339  // Call the ODTSubstitution hook
340  $parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$substitutionarray);
341  $reshook=$hookmanager->executeHooks('ODTSubstitution',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
342 
343  // Line of free text
344  $newfreetext='';
345  $paramfreetext='SUPPLIER_PROPOSAL_FREE_TEXT';
346  if (! empty($conf->global->$paramfreetext))
347  {
348  $newfreetext=make_substitutions($conf->global->$paramfreetext,$substitutionarray);
349  }
350 
351  // Open and load template
352  require_once ODTPHP_PATH.'odf.php';
353  try {
354  $odfHandler = new odf(
355  $srctemplatepath,
356  array(
357  'PATH_TO_TMP' => $conf->supplier_proposal->dir_temp,
358  'ZIP_PROXY' => 'PclZipProxy', // PhpZipProxy or PclZipProxy. Got "bad compression method" error when using PhpZipProxy.
359  'DELIMITER_LEFT' => '{',
360  'DELIMITER_RIGHT' => '}'
361  )
362  );
363  }
364  catch(Exception $e)
365  {
366  $this->error=$e->getMessage();
367  return -1;
368  }
369  // After construction $odfHandler->contentXml contains content and
370  // [!-- BEGIN row.lines --]*[!-- END row.lines --] has been replaced by
371  // [!-- BEGIN lines --]*[!-- END lines --]
372  //print html_entity_decode($odfHandler->__toString());
373  //print exit;
374 
375 
376  // Make substitutions into odt of freetext
377  try {
378  $odfHandler->setVars('free_text', $newfreetext, true, 'UTF-8');
379  }
380  catch(OdfException $e)
381  {
382  }
383 
384  // Make substitutions into odt
385  $array_user=$this->get_substitutionarray_user($user,$outputlangs);
386  $array_soc=$this->get_substitutionarray_mysoc($mysoc,$outputlangs);
387  $array_thirdparty=$this->get_substitutionarray_thirdparty($socobject,$outputlangs);
388  $array_objet=$this->get_substitutionarray_object($object,$outputlangs);
389  $array_other=$this->get_substitutionarray_other($outputlangs);
390 
391  $tmparray = array_merge($array_user,$array_soc,$array_thirdparty,$array_objet,$array_other);
392  complete_substitutions_array($tmparray, $outputlangs, $object);
393  // Call the ODTSubstitution hook
394  $parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray);
395  $reshook=$hookmanager->executeHooks('ODTSubstitution',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
396  foreach($tmparray as $key=>$value)
397  {
398  try {
399  if (preg_match('/logo$/',$key)) // Image
400  {
401  if (file_exists($value)) $odfHandler->setImage($key, $value);
402  else $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8');
403  }
404  else // Text
405  {
406  $odfHandler->setVars($key, $value, true, 'UTF-8');
407  }
408  }
409  catch(OdfException $e)
410  {
411  }
412  }
413  // Replace tags of lines
414  try
415  {
416  $listlines = $odfHandler->setSegment('lines');
417  foreach ($object->lines as $line)
418  {
419  $tmparray=$this->get_substitutionarray_lines($line,$outputlangs);
420  complete_substitutions_array($tmparray, $outputlangs, $object, $line, "completesubstitutionarray_lines");
421  // Call the ODTSubstitutionLine hook
422  $parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray,'line'=>$line);
423  $reshook=$hookmanager->executeHooks('ODTSubstitutionLine',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
424  foreach($tmparray as $key => $val)
425  {
426  try
427  {
428  $listlines->setVars($key, $val, true, 'UTF-8');
429  }
430  catch(OdfException $e)
431  {
432  }
433  catch(SegmentException $e)
434  {
435  }
436  }
437  $listlines->merge();
438  }
439  $odfHandler->mergeSegment($listlines);
440  }
441  catch(OdfException $e)
442  {
443  $this->error=$e->getMessage();
444  dol_syslog($this->error, LOG_WARNING);
445  return -1;
446  }
447 
448  // Replace labels translated
449  $tmparray=$outputlangs->get_translations_for_substitutions();
450  foreach($tmparray as $key=>$value)
451  {
452  try {
453  $odfHandler->setVars($key, $value, true, 'UTF-8');
454  }
455  catch(OdfException $e)
456  {
457  }
458  }
459 
460  // Call the beforeODTSave hook
461  $parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray);
462  $reshook=$hookmanager->executeHooks('beforeODTSave',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
463 
464  // Write new file
465  if (!empty($conf->global->MAIN_ODT_AS_PDF)) {
466  try {
467  $odfHandler->exportAsAttachedPDF($file);
468  }catch (Exception $e){
469  $this->error=$e->getMessage();
470  return -1;
471  }
472  }
473  else {
474  try {
475  $odfHandler->saveToDisk($file);
476  }catch (Exception $e){
477  $this->error=$e->getMessage();
478  return -1;
479  }
480  }
481  $parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray);
482  $reshook=$hookmanager->executeHooks('afterODTCreation',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
483 
484  if (! empty($conf->global->MAIN_UMASK))
485  @chmod($file, octdec($conf->global->MAIN_UMASK));
486 
487  $odfHandler=null; // Destroy object
488 
489  $this->result = array('fullpath'=>$file);
490 
491  return 1; // Success
492  }
493  else
494  {
495  $this->error=$langs->transnoentities("ErrorCanNotCreateDir",$dir);
496  return -1;
497  }
498  }
499 
500  return -1;
501  }
502 
503 }
504 
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.
Class to build documents using ODF templates generator.
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.
write_file($object, $outputlangs, $srctemplatepath, $hidedetails=0, $hidedesc=0, $hideref=0)
Function to build a document on disk using the generic odt module.
dol_print_error($db='', $error='', $errors=null)
Affiche message erreur system avec toutes les informations pour faciliter le diagnostic et la remonte...
Classe mere des modeles de propale.
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.
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.
$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.
Class to manage price ask supplier.
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.
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...