dolibarr  7.0.0-beta
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  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program. If not, see <http://www.gnu.org/licenses/>.
16  * or see http://www.gnu.org/
17  */
18 
25 require_once DOL_DOCUMENT_ROOT.'/core/modules/societe/modules_societe.class.php';
26 require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
27 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
28 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
29 require_once DOL_DOCUMENT_ROOT.'/core/lib/doc.lib.php';
30 
31 
36 {
37  var $emetteur; // Objet societe qui emet
38 
39  var $phpmin = array(5,2,0); // Minimum version of PHP required by module
40 
41 
47  function __construct($db)
48  {
49  global $conf,$langs,$mysoc;
50 
51  $langs->load("main");
52  $langs->load("companies");
53 
54  $this->db = $db;
55  $this->name = "ODT templates";
56  $this->description = $langs->trans("DocumentModelOdt");
57  $this->scandir = 'COMPANY_ADDON_PDF_ODT_PATH'; // Name of constant that is used to save list of directories to scan
58 
59  // Dimension page pour format A4
60  $this->type = 'odt';
61  $this->page_largeur = 0;
62  $this->page_hauteur = 0;
63  $this->format = array($this->page_largeur,$this->page_hauteur);
64  $this->marge_gauche=0;
65  $this->marge_droite=0;
66  $this->marge_haute=0;
67  $this->marge_basse=0;
68 
69  $this->option_logo = 1; // Affiche logo
70 
71  // Recupere emmetteur
72  $this->emetteur=$mysoc;
73  if (! $this->emetteur->country_code) $this->emetteur->country_code=substr($langs->defaultlang,-2); // Par defaut, si n'etait pas defini
74  }
75 
76 
83  function info($langs)
84  {
85  global $conf,$langs;
86 
87  $langs->load("companies");
88  $langs->load("errors");
89 
90  $form = new Form($this->db);
91 
92  $texte = $this->description.".<br>\n";
93  $texte.= '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
94  $texte.= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
95  $texte.= '<input type="hidden" name="action" value="setModuleOptions">';
96  $texte.= '<input type="hidden" name="param1" value="COMPANY_ADDON_PDF_ODT_PATH">';
97  $texte.= '<table class="nobordernopadding" width="100%">';
98 
99  // List of directories area
100  $texte.= '<tr><td>';
101  $texttitle=$langs->trans("ListOfDirectories");
102  $listofdir=explode(',',preg_replace('/[\r\n]+/',',',trim($conf->global->COMPANY_ADDON_PDF_ODT_PATH)));
103  $listoffiles=array();
104  foreach($listofdir as $key=>$tmpdir)
105  {
106  $tmpdir=trim($tmpdir);
107  $tmpdir=preg_replace('/DOL_DATA_ROOT/',DOL_DATA_ROOT,$tmpdir);
108  if (! $tmpdir) { unset($listofdir[$key]); continue; }
109  if (! is_dir($tmpdir)) $texttitle.=img_warning($langs->trans("ErrorDirNotFound",$tmpdir),0);
110  else
111  {
112  $tmpfiles=dol_dir_list($tmpdir,'files',0,'\.od(s|t)$','','name',SORT_ASC,0,true); // Disable hook for the moment
113  if (count($tmpfiles)) $listoffiles=array_merge($listoffiles,$tmpfiles);
114  }
115  }
116  $texthelp=$langs->trans("ListOfDirectoriesForModelGenODT");
117  // Add list of substitution keys
118  $texthelp.='<br>'.$langs->trans("FollowingSubstitutionKeysCanBeUsed").'<br>';
119  $texthelp.=$langs->transnoentitiesnoconv("FullListOnOnlineDocumentation"); // This contains an url, we don't modify it
120 
121  $texte.= $form->textwithpicto($texttitle,$texthelp,1,'help','',1);
122  $texte.= '<table><tr><td>';
123  $texte.= '<textarea class="flat" cols="60" name="value1">';
124  $texte.=$conf->global->COMPANY_ADDON_PDF_ODT_PATH;
125  $texte.= '</textarea>';
126  $texte.= '</td>';
127  $texte.= '<td align="center">&nbsp; ';
128  $texte.= '<input type="submit" class="button" value="'.$langs->trans("Modify").'" name="Button">';
129  $texte.= '</td>';
130  $texte.= '</tr>';
131  $texte.= '</table>';
132 
133  // Scan directories
134  $nbofiles=count($listoffiles);
135  if (! empty($conf->global->COMPANY_ADDON_PDF_ODT_PATH))
136  {
137  $texte.=$langs->trans("NumberOfModelFilesFound").': <b>';
138  //$texte.=$nbofiles?'<a id="a_'.get_class($this).'" href="#">':'';
139  $texte.=$nbofiles;
140  //$texte.=$nbofiles?'</a>':'';
141  $texte.='</b>';
142  }
143 
144  if ($nbofiles)
145  {
146  $texte.='<div id="div_'.get_class($this).'" class="hidden">';
147  foreach($listoffiles as $file)
148  {
149  $texte.=$file['name'].'<br>';
150  }
151  $texte.='<div id="div_'.get_class($this).'">';
152  }
153 
154  $texte.= '</td>';
155 
156  $texte.= '<td valign="top" rowspan="2" class="hideonsmartphone">';
157  $texte.= $langs->trans("ExampleOfDirectoriesForModelGen");
158  $texte.= '</td>';
159  $texte.= '</tr>';
160 
161  $texte.= '</table>';
162  $texte.= '</form>';
163 
164  return $texte;
165  }
166 
178  function write_file($object,$outputlangs,$srctemplatepath,$hidedetails=0,$hidedesc=0,$hideref=0)
179  {
180  global $user,$langs,$conf,$mysoc,$hookmanager;
181 
182  if (empty($srctemplatepath))
183  {
184  dol_syslog("doc_generic_odt::write_file parameter srctemplatepath empty", LOG_WARNING);
185  return -1;
186  }
187 
188  // Add odtgeneration hook
189  if (! is_object($hookmanager))
190  {
191  include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
192  $hookmanager=new HookManager($this->db);
193  }
194  $hookmanager->initHooks(array('odtgeneration'));
195  global $action;
196 
197  if (! is_object($outputlangs)) $outputlangs=$langs;
198  $sav_charset_output=$outputlangs->charset_output;
199  $outputlangs->charset_output='UTF-8';
200 
201  $outputlangs->load("main");
202  $outputlangs->load("dict");
203  $outputlangs->load("companies");
204  $outputlangs->load("projects");
205 
206  if ($conf->societe->multidir_output[$object->entity])
207  {
208  $dir = $conf->societe->multidir_output[$object->entity];
209  $objectref = dol_sanitizeFileName($object->id);
210  if (! preg_match('/specimen/i',$objectref)) $dir.= "/" . $objectref;
211 
212  if (! file_exists($dir))
213  {
214  if (dol_mkdir($dir) < 0)
215  {
216  $this->error=$langs->transnoentities("ErrorCanNotCreateDir",$dir);
217  return -1;
218  }
219  }
220 
221  if (file_exists($dir))
222  {
223  //print "srctemplatepath=".$srctemplatepath; // Src filename
224  $newfile=basename($srctemplatepath);
225  $newfiletmp=preg_replace('/\.od(s|t)/i','',$newfile);
226  $newfiletmp=preg_replace('/template_/i','',$newfiletmp);
227  $newfiletmp=preg_replace('/modele_/i','',$newfiletmp);
228  // Get extension (ods or odt)
229  $newfileformat=substr($newfile, strrpos($newfile, '.')+1);
230  if ( ! empty($conf->global->MAIN_DOC_USE_OBJECT_THIRDPARTY_NAME))
231  {
232  $newfiletmp = dol_sanitizeFileName(dol_string_nospecial($object->name)).'-'.$newfiletmp;
233  }
234  if ( ! empty($conf->global->MAIN_DOC_USE_TIMING))
235  {
236  $format=$conf->global->MAIN_DOC_USE_TIMING;
237  if ($format == '1') $format='%Y%m%d%H%M%S';
238  $filename=$newfiletmp.'-'.dol_print_date(dol_now(),$format).'.'.$newfileformat;
239  }
240  else
241  {
242  $filename=$newfiletmp.'.'.$newfileformat;
243  }
244  $file=$dir.'/'.$filename;
245  $object->builddoc_filename=$filename; // For triggers
246  //print "newfileformat=".$newfileformat;
247  //print "newdir=".$dir;
248  //print "newfile=".$newfile;
249  //print "file=".$file;
250  //print "conf->societe->dir_temp=".$conf->societe->dir_temp;
251  //exit;
252 
253  dol_mkdir($conf->societe->multidir_temp[$object->entity]);
254 
255  // Open and load template
256  require_once ODTPHP_PATH.'odf.php';
257  try {
258  $odfHandler = new odf(
259  $srctemplatepath,
260  array(
261  'PATH_TO_TMP' => $conf->societe->multidir_temp[$object->entity],
262  'ZIP_PROXY' => 'PclZipProxy', // PhpZipProxy or PclZipProxy. Got "bad compression method" error when using PhpZipProxy.
263  'DELIMITER_LEFT' => '{',
264  'DELIMITER_RIGHT' => '}'
265  )
266  );
267  }
268  catch(Exception $e)
269  {
270  $this->error=$e->getMessage();
271  return -1;
272  }
273  //print $odfHandler->__toString()."\n";
274 
275  // Replace tags of lines for contacts
276  $contact_arrray=array();
277 
278  $sql = "SELECT p.rowid";
279  $sql .= " FROM ".MAIN_DB_PREFIX."socpeople as p";
280  $sql .= " WHERE p.fk_soc = ".$object->id;
281 
282  $result = $this->db->query($sql);
283  $num = $this->db->num_rows($result);
284 
285  $var=true;
286  if ($num)
287  {
288  require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
289 
290  $i=0;
291  $contactstatic = new Contact($this->db);
292 
293  while($i < $num)
294  {
295  $obj = $this->db->fetch_object($result);
296 
297  $contact_arrray[$i] = $obj->rowid;
298  $i++;
299  }
300  }
301  if((is_array($contact_arrray) && count($contact_arrray) > 0))
302  {
303  try
304  {
305  $listlines = $odfHandler->setSegment('companycontacts');
306 
307  foreach($contact_arrray as $array_key => $contact_id)
308  {
309  $res_contact = $contactstatic->fetch($contact_id);
310  $tmparray=$this->get_substitutionarray_contact($contactstatic,$outputlangs,'contact');
311  foreach($tmparray as $key => $val)
312  {
313  try
314  {
315  $listlines->setVars($key, $val, true, 'UTF-8');
316  }
317  catch(OdfException $e)
318  {
319  }
320  catch(SegmentException $e)
321  {
322  }
323  }
324  $listlines->merge();
325  }
326  $odfHandler->mergeSegment($listlines);
327  }
328  catch(OdfException $e)
329  {
330  $this->error=$e->getMessage();
331  dol_syslog($this->error, LOG_WARNING);
332  //return -1;
333  }
334  }
335 
336  // Make substitutions into odt
337  $array_user=$this->get_substitutionarray_user($user,$outputlangs);
338  $array_soc=$this->get_substitutionarray_mysoc($mysoc,$outputlangs);
339  $array_thirdparty=$this->get_substitutionarray_thirdparty($object,$outputlangs);
340  $array_other=$this->get_substitutionarray_other($outputlangs);
341 
342  $tmparray = array_merge($array_user,$array_soc,$array_thirdparty,$array_other);
343  complete_substitutions_array($tmparray, $outputlangs, $object);
344 
345  // Call the ODTSubstitution hook
346  $parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray);
347  $reshook=$hookmanager->executeHooks('ODTSubstitution',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
348 
349  // Replace variables into document
350  foreach($tmparray as $key=>$value)
351  {
352  try {
353  if (preg_match('/logo$/',$key)) // Image
354  {
355  if (file_exists($value)) $odfHandler->setImage($key, $value);
356  else $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8');
357  }
358  else // Text
359  {
360  $odfHandler->setVars($key, $value, true, 'UTF-8');
361  }
362  }
363  catch(OdfException $e)
364  {
365  // setVars failed, probably because key not found
366  }
367  }
368 
369  // Replace labels translated
370  $tmparray=$outputlangs->get_translations_for_substitutions();
371  foreach($tmparray as $key=>$value)
372  {
373  try {
374  $odfHandler->setVars($key, $value, true, 'UTF-8');
375  }
376  catch(OdfException $e)
377  {
378  }
379  }
380 
381  // Call the beforeODTSave hook
382  $parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray);
383  $reshook=$hookmanager->executeHooks('beforeODTSave',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
384 
385  // Write new file
386  if (!empty($conf->global->MAIN_ODT_AS_PDF)) {
387  try {
388  $odfHandler->exportAsAttachedPDF($file);
389  }catch (Exception $e){
390  $this->error=$e->getMessage();
391  return -1;
392  }
393  }
394  else {
395  try {
396  $odfHandler->creator = $user->getFullName($outputlangs);
397  $odfHandler->title = $object->builddoc_filename;
398  $odfHandler->subject = $object->builddoc_filename;
399 
400  if (! empty($conf->global->ODT_ADD_DOLIBARR_ID))
401  {
402  $odfHandler->userdefined['dol_id'] = $object->id;
403  $odfHandler->userdefined['dol_element'] = $object->element;
404  }
405 
406  $odfHandler->saveToDisk($file);
407  }catch (Exception $e){
408  $this->error=$e->getMessage();
409  return -1;
410  }
411  }
412  $parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray);
413  $reshook=$hookmanager->executeHooks('afterODTCreation',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
414 
415  if (! empty($conf->global->MAIN_UMASK))
416  @chmod($file, octdec($conf->global->MAIN_UMASK));
417 
418  $odfHandler=null; // Destroy object
419 
420  $this->result = array('fullpath'=>$file);
421 
422  return 1; // Success
423  }
424  else
425  {
426  $this->error=$langs->transnoentities("ErrorCanNotCreateDir",$dir);
427  return -1;
428  }
429  }
430 
431  $this->error='UnknownError';
432  return -1;
433  }
434 
435 }
436 
info($langs)
Return description of a module.
Class to manage contact/addresses.
</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.
__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.
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.
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.
img_warning($titlealt= 'default', $moreatt= '')
Show warning logo.
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.
$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)
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.
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...