dolibarr  9.0.0
doc_generic_odt.modules.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2010-2011 Laurent Destailleur <ely@users.sourceforge.net>
3  * Copyright (C) 2016 Charlie Benke <charlie@patas-monkey.com>
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/societe/modules_societe.class.php';
28 require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
29 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
30 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
31 require_once DOL_DOCUMENT_ROOT.'/core/lib/doc.lib.php';
32 
33 
38 {
43  public $emetteur;
44 
49  public $phpmin = array(5, 4);
50 
51 
57  function __construct($db)
58  {
59  global $conf, $langs, $mysoc;
60 
61  // Load translation files required by the page
62  $langs->loadLangs(array("main","companies"));
63 
64  $this->db = $db;
65  $this->name = "ODT templates";
66  $this->description = $langs->trans("DocumentModelOdt");
67  $this->scandir = 'COMPANY_ADDON_PDF_ODT_PATH'; // Name of constant that is used to save list of directories to scan
68 
69  // Dimension page pour format A4
70  $this->type = 'odt';
71  $this->page_largeur = 0;
72  $this->page_hauteur = 0;
73  $this->format = array($this->page_largeur,$this->page_hauteur);
74  $this->marge_gauche=0;
75  $this->marge_droite=0;
76  $this->marge_haute=0;
77  $this->marge_basse=0;
78 
79  $this->option_logo = 1; // Affiche logo
80 
81  // Recupere emmetteur
82  $this->emetteur=$mysoc;
83  if (! $this->emetteur->country_code) $this->emetteur->country_code=substr($langs->defaultlang,-2); // Par defaut, si n'etait pas defini
84  }
85 
86 
93  function info($langs)
94  {
95  global $conf,$langs;
96 
97  // Load traductions files requiredby by page
98  $langs->loadLangs(array("companies", "errors"));
99 
100  $form = new Form($this->db);
101 
102  $texte = $this->description.".<br>\n";
103  $texte.= '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
104  $texte.= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
105  $texte.= '<input type="hidden" name="action" value="setModuleOptions">';
106  $texte.= '<input type="hidden" name="param1" value="COMPANY_ADDON_PDF_ODT_PATH">';
107  $texte.= '<table class="nobordernopadding" width="100%">';
108 
109  // List of directories area
110  $texte.= '<tr><td>';
111  $texttitle=$langs->trans("ListOfDirectories");
112  $listofdir=explode(',',preg_replace('/[\r\n]+/',',',trim($conf->global->COMPANY_ADDON_PDF_ODT_PATH)));
113  $listoffiles=array();
114  foreach($listofdir as $key=>$tmpdir)
115  {
116  $tmpdir=trim($tmpdir);
117  $tmpdir=preg_replace('/DOL_DATA_ROOT/',DOL_DATA_ROOT,$tmpdir);
118  if (! $tmpdir) { unset($listofdir[$key]); continue; }
119  if (! is_dir($tmpdir)) $texttitle.=img_warning($langs->trans("ErrorDirNotFound",$tmpdir),0);
120  else
121  {
122  $tmpfiles=dol_dir_list($tmpdir,'files',0,'\.od(s|t)$','','name',SORT_ASC,0,true); // Disable hook for the moment
123  if (count($tmpfiles)) $listoffiles=array_merge($listoffiles,$tmpfiles);
124  }
125  }
126  $texthelp=$langs->trans("ListOfDirectoriesForModelGenODT");
127  // Add list of substitution keys
128  $texthelp.='<br>'.$langs->trans("FollowingSubstitutionKeysCanBeUsed").'<br>';
129  $texthelp.=$langs->transnoentitiesnoconv("FullListOnOnlineDocumentation"); // This contains an url, we don't modify it
130 
131  $texte.= $form->textwithpicto($texttitle,$texthelp,1,'help','',1);
132  $texte.= '<table><tr><td>';
133  $texte.= '<textarea class="flat" cols="60" name="value1">';
134  $texte.=$conf->global->COMPANY_ADDON_PDF_ODT_PATH;
135  $texte.= '</textarea>';
136  $texte.= '</td>';
137  $texte.= '<td align="center">&nbsp; ';
138  $texte.= '<input type="submit" class="button" value="'.$langs->trans("Modify").'" name="Button">';
139  $texte.= '</td>';
140  $texte.= '</tr>';
141  $texte.= '</table>';
142 
143  // Scan directories
144  $nbofiles=count($listoffiles);
145  if (! empty($conf->global->COMPANY_ADDON_PDF_ODT_PATH))
146  {
147  $texte.=$langs->trans("NumberOfModelFilesFound").': <b>';
148  //$texte.=$nbofiles?'<a id="a_'.get_class($this).'" href="#">':'';
149  $texte.=$nbofiles;
150  //$texte.=$nbofiles?'</a>':'';
151  $texte.='</b>';
152  }
153 
154  if ($nbofiles)
155  {
156  $texte.='<div id="div_'.get_class($this).'" class="hidden">';
157  foreach($listoffiles as $file)
158  {
159  $texte.=$file['name'].'<br>';
160  }
161  $texte.='<div id="div_'.get_class($this).'">';
162  }
163 
164  $texte.= '</td>';
165 
166  $texte.= '<td valign="top" rowspan="2" class="hideonsmartphone">';
167  $texte.= $langs->trans("ExampleOfDirectoriesForModelGen");
168  $texte.= '</td>';
169  $texte.= '</tr>';
170 
171  $texte.= '</table>';
172  $texte.= '</form>';
173 
174  return $texte;
175  }
176 
177  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
189  function write_file($object,$outputlangs,$srctemplatepath,$hidedetails=0,$hidedesc=0,$hideref=0)
190  {
191  // phpcs:enable
192  global $user,$langs,$conf,$mysoc,$hookmanager;
193 
194  if (empty($srctemplatepath))
195  {
196  dol_syslog("doc_generic_odt::write_file parameter srctemplatepath empty", LOG_WARNING);
197  return -1;
198  }
199 
200  // Add odtgeneration hook
201  if (! is_object($hookmanager))
202  {
203  include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
204  $hookmanager=new HookManager($this->db);
205  }
206  $hookmanager->initHooks(array('odtgeneration'));
207  global $action;
208 
209  if (! is_object($outputlangs)) $outputlangs=$langs;
210  $sav_charset_output=$outputlangs->charset_output;
211  $outputlangs->charset_output='UTF-8';
212 
213  // Load translation files required by the page
214  $outputlangs->loadLangs(array("main", "dict", "companies", "projects"));
215 
216  if ($conf->societe->multidir_output[$object->entity])
217  {
218  $dir = $conf->societe->multidir_output[$object->entity];
219  $objectref = dol_sanitizeFileName($object->id);
220  if (! preg_match('/specimen/i',$objectref)) $dir.= "/" . $objectref;
221 
222  if (! file_exists($dir))
223  {
224  if (dol_mkdir($dir) < 0)
225  {
226  $this->error=$langs->transnoentities("ErrorCanNotCreateDir",$dir);
227  return -1;
228  }
229  }
230 
231  if (file_exists($dir))
232  {
233  //print "srctemplatepath=".$srctemplatepath; // Src filename
234  $newfile=basename($srctemplatepath);
235  $newfiletmp=preg_replace('/\.od(s|t)/i','',$newfile);
236  $newfiletmp=preg_replace('/template_/i','',$newfiletmp);
237  $newfiletmp=preg_replace('/modele_/i','',$newfiletmp);
238  // Get extension (ods or odt)
239  $newfileformat=substr($newfile, strrpos($newfile, '.')+1);
240  if ( ! empty($conf->global->MAIN_DOC_USE_OBJECT_THIRDPARTY_NAME))
241  {
242  $newfiletmp = dol_sanitizeFileName(dol_string_nospecial($object->name)).'-'.$newfiletmp;
243  }
244  if ( ! empty($conf->global->MAIN_DOC_USE_TIMING))
245  {
246  $format=$conf->global->MAIN_DOC_USE_TIMING;
247  if ($format == '1') $format='%Y%m%d%H%M%S';
248  $filename=$newfiletmp.'-'.dol_print_date(dol_now(),$format).'.'.$newfileformat;
249  }
250  else
251  {
252  $filename=$newfiletmp.'.'.$newfileformat;
253  }
254  $file=$dir.'/'.$filename;
255  $object->builddoc_filename=$filename; // For triggers
256  //print "newfileformat=".$newfileformat;
257  //print "newdir=".$dir;
258  //print "newfile=".$newfile;
259  //print "file=".$file;
260  //print "conf->societe->dir_temp=".$conf->societe->dir_temp;
261  //exit;
262 
263  dol_mkdir($conf->societe->multidir_temp[$object->entity]);
264 
265  // Open and load template
266  require_once ODTPHP_PATH.'odf.php';
267  try {
268  $odfHandler = new odf(
269  $srctemplatepath,
270  array(
271  'PATH_TO_TMP' => $conf->societe->multidir_temp[$object->entity],
272  'ZIP_PROXY' => 'PclZipProxy', // PhpZipProxy or PclZipProxy. Got "bad compression method" error when using PhpZipProxy.
273  'DELIMITER_LEFT' => '{',
274  'DELIMITER_RIGHT' => '}'
275  )
276  );
277  }
278  catch(Exception $e)
279  {
280  $this->error=$e->getMessage();
281  dol_syslog($e->getMessage(), LOG_INFO);
282  return -1;
283  }
284  //print $odfHandler->__toString()."\n";
285 
286  // Replace tags of lines for contacts
287  $contact_arrray=array();
288 
289  $sql = "SELECT p.rowid";
290  $sql .= " FROM ".MAIN_DB_PREFIX."socpeople as p";
291  $sql .= " WHERE p.fk_soc = ".$object->id;
292 
293  $result = $this->db->query($sql);
294  $num = $this->db->num_rows($result);
295 
296  if ($num)
297  {
298  require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
299 
300  $i=0;
301  $contactstatic = new Contact($this->db);
302 
303  while($i < $num)
304  {
305  $obj = $this->db->fetch_object($result);
306 
307  $contact_arrray[$i] = $obj->rowid;
308  $i++;
309  }
310  }
311  if((is_array($contact_arrray) && count($contact_arrray) > 0))
312  {
313  try
314  {
315  $listlines = $odfHandler->setSegment('companycontacts');
316 
317  foreach($contact_arrray as $array_key => $contact_id)
318  {
319  $res_contact = $contactstatic->fetch($contact_id);
320  $tmparray=$this->get_substitutionarray_contact($contactstatic,$outputlangs,'contact');
321  foreach($tmparray as $key => $val)
322  {
323  try
324  {
325  $listlines->setVars($key, $val, true, 'UTF-8');
326  }
327  catch(OdfException $e)
328  {
329  dol_syslog($e->getMessage(), LOG_INFO);
330  }
331  catch(SegmentException $e)
332  {
333  dol_syslog($e->getMessage(), LOG_INFO);
334  }
335  }
336  $listlines->merge();
337  }
338  $odfHandler->mergeSegment($listlines);
339  }
340  catch(OdfException $e)
341  {
342  $this->error=$e->getMessage();
343  dol_syslog($this->error, LOG_WARNING);
344  //return -1;
345  }
346  }
347 
348  // Make substitutions into odt
349  $array_user=$this->get_substitutionarray_user($user,$outputlangs);
350  $array_soc=$this->get_substitutionarray_mysoc($mysoc,$outputlangs);
351  $array_thirdparty=$this->get_substitutionarray_thirdparty($object,$outputlangs);
352  $array_other=$this->get_substitutionarray_other($outputlangs);
353 
354  $tmparray = array_merge($array_user,$array_soc,$array_thirdparty,$array_other);
355  complete_substitutions_array($tmparray, $outputlangs, $object);
356 
357  // Call the ODTSubstitution hook
358  $parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray);
359  $reshook=$hookmanager->executeHooks('ODTSubstitution',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
360 
361  // Replace variables into document
362  foreach($tmparray as $key=>$value)
363  {
364  try {
365  if (preg_match('/logo$/',$key)) // Image
366  {
367  if (file_exists($value)) $odfHandler->setImage($key, $value);
368  else $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8');
369  }
370  else // Text
371  {
372  $odfHandler->setVars($key, $value, true, 'UTF-8');
373  }
374  }
375  catch (OdfException $e)
376  {
377  // setVars failed, probably because key not found
378  dol_syslog($e->getMessage(), LOG_INFO);
379  }
380  }
381 
382  // Replace labels translated
383  $tmparray=$outputlangs->get_translations_for_substitutions();
384  foreach($tmparray as $key=>$value)
385  {
386  try {
387  $odfHandler->setVars($key, $value, true, 'UTF-8');
388  }
389  catch (OdfException $e)
390  {
391  dol_syslog($e->getMessage(), LOG_INFO);
392  }
393  }
394 
395  // Call the beforeODTSave hook
396  $parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray);
397  $reshook=$hookmanager->executeHooks('beforeODTSave',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
398 
399  // Write new file
400  if (!empty($conf->global->MAIN_ODT_AS_PDF)) {
401  try {
402  $odfHandler->exportAsAttachedPDF($file);
403  } catch (Exception $e) {
404  $this->error=$e->getMessage();
405  dol_syslog($e->getMessage(), LOG_INFO);
406  return -1;
407  }
408  }
409  else {
410  try {
411  $odfHandler->creator = $user->getFullName($outputlangs);
412  $odfHandler->title = $object->builddoc_filename;
413  $odfHandler->subject = $object->builddoc_filename;
414 
415  if (! empty($conf->global->ODT_ADD_DOLIBARR_ID))
416  {
417  $odfHandler->userdefined['dol_id'] = $object->id;
418  $odfHandler->userdefined['dol_element'] = $object->element;
419  }
420 
421  $odfHandler->saveToDisk($file);
422  }catch (Exception $e){
423  $this->error=$e->getMessage();
424  dol_syslog($e->getMessage(), LOG_INFO);
425  return -1;
426  }
427  }
428  $parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray);
429  $reshook=$hookmanager->executeHooks('afterODTCreation',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
430 
431  if (! empty($conf->global->MAIN_UMASK))
432  @chmod($file, octdec($conf->global->MAIN_UMASK));
433 
434  $odfHandler=null; // Destroy object
435 
436  $this->result = array('fullpath'=>$file);
437 
438  return 1; // Success
439  }
440  else
441  {
442  $this->error=$langs->transnoentities("ErrorCanNotCreateDir",$dir);
443  return -1;
444  }
445  }
446 
447  $this->error='UnknownError';
448  return -1;
449  }
450 }
img_warning($titlealt='default', $moreatt='')
Show warning logo.
info($langs)
Return description of a module.
</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
Class to manage contact/addresses.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
__construct($db)
Constructor.
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.
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition: repair.php:103
Class to manage hooks.
Class to manage generation of HTML components Only common components must be here.
Parent class for third parties models of doc generators.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='')
Write log message into outputs.
type
Definition: viewcat.php:284
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.
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)
get_substitutionarray_other($outputlangs)
Define array with couple subtitution key => subtitution value.
dol_string_nospecial($str, $newstr='_', $badcharstoreplace='')
Clean a string from all punctuation characters to use it as a ref or login.
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...