dolibarr  7.0.0-beta
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 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 * or see http://www.gnu.org/
18 */
19 
26 require_once DOL_DOCUMENT_ROOT.'/core/modules/usergroup/modules_usergroup.class.php';
27 require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
28 require_once DOL_DOCUMENT_ROOT.'/user/class/usergroup.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 = 'USERGROUP_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 USERGROUP_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="USERGROUP_ADDON_PDF_ODT_PATH">';
110  if ($conf->global->MAIN_PROPAL_CHOOSE_ODT_DOCUMENT > 0)
111  {
112  $texte.= '<input type="hidden" name="param2" value="USERGROUP_ADDON_PDF_ODT_DEFAULT">';
113  $texte.= '<input type="hidden" name="param3" value="USERGROUP_ADDON_PDF_ODT_TOBILL">';
114  $texte.= '<input type="hidden" name="param4" value="USERGROUP_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->USERGROUP_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->USERGROUP_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  if (count($listofdir))
153  {
154  $texte.=$langs->trans("NumberOfModelFilesFound").': <b>'.count($listoffiles).'</b>';
155 
156  if ($conf->global->MAIN_PROPAL_CHOOSE_ODT_DOCUMENT > 0)
157  {
158  // Model for creation
159  $liste=ModelePDFUserGroup::liste_modeles($this->db);
160  $texte.= '<table width="50%;">';
161  $texte.= '<tr>';
162  $texte.= '<td width="60%;">'.$langs->trans("DefaultModelPropalCreate").'</td>';
163  $texte.= '<td colspan="">';
164  $texte.= $form->selectarray('value2',$liste,$conf->global->USERGROUP_ADDON_PDF_ODT_DEFAULT);
165  $texte.= "</td></tr>";
166 
167  $texte.= '<tr>';
168  $texte.= '<td width="60%;">'.$langs->trans("DefaultModelPropalToBill").'</td>';
169  $texte.= '<td colspan="">';
170  $texte.= $form->selectarray('value3',$liste,$conf->global->USERGROUP_ADDON_PDF_ODT_TOBILL);
171  $texte.= "</td></tr>";
172  $texte.= '<tr>';
173 
174  $texte.= '<td width="60%;">'.$langs->trans("DefaultModelPropalClosed").'</td>';
175  $texte.= '<td colspan="">';
176  $texte.= $form->selectarray('value4',$liste,$conf->global->USERGROUP_ADDON_PDF_ODT_CLOSED);
177  $texte.= "</td></tr>";
178  $texte.= '</table>';
179  }
180  }
181 
182  $texte.= '</td>';
183 
184  $texte.= '<td valign="top" rowspan="2" class="hideonsmartphone">';
185  $texte.= $langs->trans("ExampleOfDirectoriesForModelGen");
186  $texte.= '</td>';
187  $texte.= '</tr>';
188 
189  $texte.= '</table>';
190  $texte.= '</form>';
191 
192  return $texte;
193  }
194 
206  function write_file($object,$outputlangs,$srctemplatepath,$hidedetails=0,$hidedesc=0,$hideref=0)
207  {
208  global $user,$langs,$conf,$mysoc,$hookmanager;
209 
210  if (empty($srctemplatepath))
211  {
212  dol_syslog("doc_generic_odt::write_file parameter srctemplatepath empty", LOG_WARNING);
213  return -1;
214  }
215 
216  // Add odtgeneration hook
217  if (! is_object($hookmanager))
218  {
219  include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
220  $hookmanager=new HookManager($this->db);
221  }
222  $hookmanager->initHooks(array('odtgeneration'));
223  global $action;
224 
225  if (! is_object($outputlangs)) $outputlangs=$langs;
226  $sav_charset_output=$outputlangs->charset_output;
227  $outputlangs->charset_output='UTF-8';
228 
229  $outputlangs->load("main");
230  $outputlangs->load("dict");
231  $outputlangs->load("companies");
232  $outputlangs->load("bills");
233 
234  if ($conf->user->dir_output)
235  {
236  // If $object is id instead of object
237  if (! is_object($object))
238  {
239  $id = $object;
240  $object = new UserGroup($this->db);
241  $result=$object->fetch($id);
242  if ($result < 0)
243  {
244  dol_print_error($this->db,$object->error);
245  return -1;
246  }
247  }
248 
249  $dir = $conf->usergroup->dir_output;
250  $objectref = dol_sanitizeFileName($object->ref);
251  if (! preg_match('/specimen/i',$objectref)) $dir.= "/" . $objectref;
252  $file = $dir . "/" . $objectref . ".odt";
253 
254  if (! file_exists($dir))
255  {
256  if (dol_mkdir($dir) < 0)
257  {
258  $this->error=$langs->transnoentities("ErrorCanNotCreateDir",$dir);
259  return -1;
260  }
261  }
262 
263  if (file_exists($dir))
264  {
265  //print "srctemplatepath=".$srctemplatepath; // Src filename
266  $newfile=basename($srctemplatepath);
267  $newfiletmp=preg_replace('/\.od(t|s)/i','',$newfile);
268  $newfiletmp=preg_replace('/template_/i','',$newfiletmp);
269  $newfiletmp=preg_replace('/modele_/i','',$newfiletmp);
270 
271  $newfiletmp=$objectref.'_'.$newfiletmp;
272 
273  // Get extension (ods or odt)
274  $newfileformat=substr($newfile, strrpos($newfile, '.')+1);
275  if ( ! empty($conf->global->MAIN_DOC_USE_TIMING))
276  {
277  $format=$conf->global->MAIN_DOC_USE_TIMING;
278  if ($format == '1') $format='%Y%m%d%H%M%S';
279  $filename=$newfiletmp.'-'.dol_print_date(dol_now(),$format).'.'.$newfileformat;
280  }
281  else
282  {
283  $filename=$newfiletmp.'.'.$newfileformat;
284  }
285  $file=$dir.'/'.$filename;
286  //print "newdir=".$dir;
287  //print "newfile=".$newfile;
288  //print "file=".$file;
289  //print "conf->user->dir_temp=".$conf->user->dir_temp;
290 
291  dol_mkdir($conf->user->dir_temp);
292 
293 
294  // If CUSTOMER contact defined on user, we use it
295  $usecontact=false;
296  $arrayidcontact=$object->getIdContact('external','CUSTOMER');
297  if (count($arrayidcontact) > 0)
298  {
299  $usecontact=true;
300  $result=$object->fetch_contact($arrayidcontact[0]);
301  }
302 
303  // Recipient name
304  if (! empty($usecontact))
305  {
306  // On peut utiliser le nom de la societe du contact
307  if (! empty($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT)) $socobject = $object->contact;
308  else {
309  $socobject = $object->thirdparty;
310  // if we have a CUSTOMER contact and we dont use it as recipient we store the contact object for later use
311  $contactobject = $object->contact;
312  }
313  }
314  else
315  {
316  $socobject=$object->thirdparty;
317  }
318  // Make substitution
319  $substitutionarray=array(
320  '__FROM_NAME__' => $this->emetteur->name,
321  '__FROM_EMAIL__' => $this->emetteur->email,
322  '__TOTAL_TTC__' => $object->total_ttc,
323  '__TOTAL_HT__' => $object->total_ht,
324  '__TOTAL_VAT__' => $object->total_vat
325  );
326  complete_substitutions_array($substitutionarray, $langs, $object);
327  // Call the ODTSubstitution hook
328  $parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$substitutionarray);
329  $reshook=$hookmanager->executeHooks('ODTSubstitution',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
330 
331  // Line of free text
332  $newfreetext='';
333  $paramfreetext='user_FREE_TEXT';
334  if (! empty($conf->global->$paramfreetext))
335  {
336  $newfreetext=make_substitutions($conf->global->$paramfreetext,$substitutionarray);
337  }
338 
339  // Open and load template
340  require_once ODTPHP_PATH.'odf.php';
341  try {
342  $odfHandler = new odf(
343  $srctemplatepath,
344  array(
345  'PATH_TO_TMP' => $conf->user->dir_temp,
346  'ZIP_PROXY' => 'PclZipProxy', // PhpZipProxy or PclZipProxy. Got "bad compression method" error when using PhpZipProxy.
347  'DELIMITER_LEFT' => '{',
348  'DELIMITER_RIGHT' => '}'
349  )
350  );
351  }
352  catch(Exception $e)
353  {
354  $this->error=$e->getMessage();
355  return -1;
356  }
357  // After construction $odfHandler->contentXml contains content and
358  // [!-- BEGIN row.lines --]*[!-- END row.lines --] has been replaced by
359  // [!-- BEGIN lines --]*[!-- END lines --]
360  //print html_entity_decode($odfHandler->__toString());
361  //print exit;
362 
363 
364  // Make substitutions into odt of freetext
365  try {
366  $odfHandler->setVars('free_text', $newfreetext, true, 'UTF-8');
367  }
368  catch(OdfException $e)
369  {
370  }
371 
372  // Make substitutions into odt
373  $array_user=$this->get_substitutionarray_user($user,$outputlangs);
374  $array_global=$this->get_substitutionarray_each_var_object($object,$outputlangs);
375  $array_soc=$this->get_substitutionarray_mysoc($mysoc,$outputlangs);
376  $array_thirdparty=$this->get_substitutionarray_thirdparty($socobject,$outputlangs);
377  $array_objet=$this->get_substitutionarray_each_var_object($object,$outputlangs);
378  $array_other=$this->get_substitutionarray_other($outputlangs);
379  // retrieve contact information for use in user as contact_xxx tags
380  $array_thirdparty_contact = array();
381  if ($usecontact)
382  $array_thirdparty_contact=$this->get_substitutionarray_contact($contactobject,$outputlangs,'contact');
383 
384  $tmparray = array_merge($array_global,$array_user,$array_soc,$array_thirdparty,$array_objet,$array_other,$array_thirdparty_contact);
385  complete_substitutions_array($tmparray, $outputlangs, $object);
386  $object->fetch_optionals();
387  // Call the ODTSubstitution hook
388  $parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray);
389  $reshook=$hookmanager->executeHooks('ODTSubstitution',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
390  foreach($tmparray as $key=>$value)
391  {
392  try
393  {
394  if (preg_match('/logo$/',$key)) // Image
395  {
396  if (file_exists($value)) $odfHandler->setImage($key, $value);
397  else $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8');
398  }
399  else // Text
400  {
401  $odfHandler->setVars($key, $value, true, 'UTF-8');
402  }
403  }
404  catch(OdfException $e)
405  {
406  }
407  }
408  // Replace tags of lines
409  try
410  {
411  $listlines = $odfHandler->setSegment('lines');
412  foreach ($object->members as $u)
413  {
414  $tmparray=$this->get_substitutionarray_each_var_object($u,$outputlangs);
415  unset($tmparray['object_pass']);
416  unset($tmparray['object_pass_indatabase']);
417  complete_substitutions_array($tmparray, $outputlangs, $object, $user, "completesubstitutionarray_users");
418  // Call the ODTSubstitutionLine hook
419  $parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray,'line'=>$u);
420  $reshook=$hookmanager->executeHooks('ODTSubstitutionLine',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
421  foreach($tmparray as $key => $val)
422  {
423  try
424  {
425  if(!is_array($val)) {
426  $listlines->setVars($key, $val, true, 'UTF-8');
427  }
428  }
429  catch(OdfException $e)
430  {
431  }
432  catch(SegmentException $e)
433  {
434  }
435  }
436  $listlines->merge();
437  }
438  $odfHandler->mergeSegment($listlines);
439  }
440  catch(OdfException $e)
441  {
442  $this->error=$e->getMessage();
443  dol_syslog($this->error, LOG_WARNING);
444  return -1;
445  }
446 
447  // Replace labels translated
448  $tmparray=$outputlangs->get_translations_for_substitutions();
449  foreach($tmparray as $key=>$value)
450  {
451  try {
452  $odfHandler->setVars($key, $value, true, 'UTF-8');
453  }
454  catch(OdfException $e)
455  {
456  }
457  }
458 
459  // Call the beforeODTSave hook
460  $parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs);
461  $reshook=$hookmanager->executeHooks('beforeODTSave',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
462 
463  // Write new file
464  if (!empty($conf->global->MAIN_ODT_AS_PDF)) {
465  try {
466  $odfHandler->exportAsAttachedPDF($file);
467  }catch (Exception $e){
468  $this->error=$e->getMessage();
469  return -1;
470  }
471  }
472  else {
473  try {
474  $odfHandler->saveToDisk($file);
475  }catch (Exception $e){
476  $this->error=$e->getMessage();
477  return -1;
478  }
479  }
480 
481  $reshook=$hookmanager->executeHooks('afterODTCreation',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
482 
483  if (! empty($conf->global->MAIN_UMASK))
484  @chmod($file, octdec($conf->global->MAIN_UMASK));
485 
486  $odfHandler=null; // Destroy object
487 
488  $this->result = array('fullpath'=>$file);
489 
490  return 1; // Success
491  }
492  else
493  {
494  $this->error=$langs->transnoentities("ErrorCanNotCreateDir",$dir);
495  return -1;
496  }
497  }
498 
499  return -1;
500  }
501 
502 }
503 
</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_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.
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.
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.
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.
get_substitutionarray_mysoc($mysoc, $outputlangs)
Define array with couple subtitution key => subtitution value.
dol_now($mode='gmt')
Return date for now.
static liste_modeles($db, $maxfilenamelength=0)
Return list of active generation modules.
$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)
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...