dolibarr 18.0.6
doc_generic_mo_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) 2014 Marcos García <marcosgdf@gmail.com>
5 * Copyright (C) 2016 Charlie Benke <charlie@patas-monkey.com>
6 * Copyright (C) 2018-2021 Philippe Grand <philippe.grand@atoo-net.com>
7 * Copyright (C) 2018-2023 Frédéric France <frederic.france@netlogic.fr>
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 3 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 * or see https://www.gnu.org/
22 */
23
30require_once DOL_DOCUMENT_ROOT.'/core/modules/mrp/modules_mo.php';
31require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
32require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
33require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
34require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
35require_once DOL_DOCUMENT_ROOT.'/core/lib/doc.lib.php';
36
37
42{
47 public $emetteur;
48
52 public $version = 'dolibarr';
53
54
60 public function __construct($db)
61 {
62 global $conf, $langs, $mysoc;
63
64 // Load translation files required by the page
65 $langs->loadLangs(array("main", "companies"));
66
67 $this->db = $db;
68 $this->name = "ODT templates";
69 $this->description = $langs->trans("DocumentModelOdt");
70 $this->scandir = 'MRP_MO_ADDON_PDF_ODT_PATH'; // Name of constant that is used to save list of directories to scan
71
72 // Page size for A4 format
73 $this->type = 'odt';
74 $this->page_largeur = 0;
75 $this->page_hauteur = 0;
76 $this->format = array($this->page_largeur, $this->page_hauteur);
77 $this->marge_gauche = 0;
78 $this->marge_droite = 0;
79 $this->marge_haute = 0;
80 $this->marge_basse = 0;
81
82 $this->option_logo = 1; // Display logo
83 $this->option_tva = 0; // Manage the vat option
84 $this->option_modereg = 0; // Display payment mode
85 $this->option_condreg = 0; // Display payment terms
86 $this->option_multilang = 1; // Available in several languages
87 $this->option_escompte = 0; // Displays if there has been a discount
88 $this->option_credit_note = 0; // Support credit notes
89 $this->option_freetext = 1; // Support add of a personalised text
90 $this->option_draft_watermark = 0; // Support add of a watermark on drafts
91
92 // Get source company
93 $this->emetteur = $mysoc;
94 if (!$this->emetteur->country_code) {
95 $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default if not defined
96 }
97 }
98
99
106 public function info($langs)
107 {
108 global $conf, $langs;
109
110 // Load translation files required by the page
111 $langs->loadLangs(array("errors", "companies"));
112
113 $form = new Form($this->db);
114
115 $texte = $this->description.".<br>\n";
116 $texte .= '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
117 $texte .= '<input type="hidden" name="token" value="'.newToken().'">';
118 $texte .= '<input type="hidden" name="page_y" value="">';
119 $texte .= '<input type="hidden" name="action" value="setModuleOptions">';
120 $texte .= '<input type="hidden" name="param1" value="MRP_MO_ADDON_PDF_ODT_PATH">';
121 $texte .= '<table class="nobordernopadding" width="100%">';
122
123 // List of directories area
124 $texte .= '<tr><td>';
125 $texttitle = $langs->trans("ListOfDirectories");
126 $listofdir = explode(',', preg_replace('/[\r\n]+/', ',', trim($conf->global->MRP_MO_ADDON_PDF_ODT_PATH)));
127 $listoffiles = array();
128 foreach ($listofdir as $key => $tmpdir) {
129 $tmpdir = trim($tmpdir);
130 $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
131 if (!$tmpdir) {
132 unset($listofdir[$key]);
133 continue;
134 }
135 if (!is_dir($tmpdir)) {
136 $texttitle .= img_warning($langs->trans("ErrorDirNotFound", $tmpdir), 0);
137 } else {
138 $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.(ods|odt)');
139 if (count($tmpfiles)) {
140 $listoffiles = array_merge($listoffiles, $tmpfiles);
141 }
142 }
143 }
144 $texthelp = $langs->trans("ListOfDirectoriesForModelGenODT");
145 // Add list of substitution keys
146 $texthelp .= '<br>'.$langs->trans("FollowingSubstitutionKeysCanBeUsed").'<br>';
147 $texthelp .= $langs->transnoentitiesnoconv("FullListOnOnlineDocumentation"); // This contains an url, we don't modify it
148
149 $texte .= $form->textwithpicto($texttitle, $texthelp, 1, 'help', '', 1);
150 $texte .= '<div><div style="display: inline-block; min-width: 100px; vertical-align: middle;">';
151 $texte .= '<textarea class="flat" cols="60" name="value1">';
152 $texte .= $conf->global->MRP_MO_ADDON_PDF_ODT_PATH;
153 $texte .= '</textarea>';
154 $texte .= '</div><div style="display: inline-block; vertical-align: middle;">';
155 $texte .= '<input type="submit" class="button small reposition" name="modify" value="'.$langs->trans("Modify").'">';
156 $texte .= '<br></div></div>';
157
158 // Scan directories
159 $nbofiles = count($listoffiles);
160 if (!empty($conf->global->MRP_MO_ADDON_PDF_ODT_PATH)) {
161 $texte .= $langs->trans("NumberOfModelFilesFound").': <b>';
162 //$texte.=$nbofiles?'<a id="a_'.get_class($this).'" href="#">':'';
163 $texte .= count($listoffiles);
164 //$texte.=$nbofiles?'</a>':'';
165 $texte .= '</b>';
166 }
167
168 if ($nbofiles) {
169 $texte .= '<div id="div_'.get_class($this).'" class="hiddenx">';
170 // Show list of found files
171 foreach ($listoffiles as $file) {
172 $texte .= '- '.$file['name'].' <a href="'.DOL_URL_ROOT.'/document.php?modulepart=doctemplates&file=mrps/'.urlencode(basename($file['name'])).'">'.img_picto('', 'listlight').'</a>';
173 $texte .= ' &nbsp; <a class="reposition" href="'.$_SERVER["PHP_SELF"].'?modulepart=doctemplates&keyforuploaddir=MRP_MO_ADDON_PDF_ODT_PATH&action=deletefile&token='.newToken().'&file='.urlencode(basename($file['name'])).'">'.img_picto('', 'delete').'</a>';
174 $texte .= '<br>';
175 }
176 $texte .= '</div>';
177 }
178
179 $texte .= '</td>';
180
181 $texte .= '<td rowspan="2" class="tdtop hideonsmartphone">';
182 $texte .= '<span class="opacitymedium">';
183 $texte .= $langs->trans("ExampleOfDirectoriesForModelGen");
184 $texte .= '</span>';
185 $texte .= '</td>';
186 $texte .= '</tr>';
187
188 $texte .= '</table>';
189 $texte .= '</form>';
190
191 return $texte;
192 }
193
194 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
206 public function write_file($object, $outputlangs, $srctemplatepath, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
207 {
208 // phpcs:enable
209 global $user, $langs, $conf, $mysoc, $hookmanager;
210
211 if (empty($srctemplatepath)) {
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 include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
219 $hookmanager = new HookManager($this->db);
220 }
221 $hookmanager->initHooks(array('odtgeneration'));
222 global $action;
223
224 if (!is_object($outputlangs)) {
225 $outputlangs = $langs;
226 }
227 $sav_charset_output = $outputlangs->charset_output;
228 $outputlangs->charset_output = 'UTF-8';
229
230 $outputlangs->loadLangs(array("main", "dict", "companies", "bills"));
231
232 if ($conf->mrp->dir_output) {
233 // If $object is id instead of object
234 if (!is_object($object)) {
235 $id = $object;
236 $object = new Mo($this->db);
237 $result = $object->fetch($id);
238 if ($result < 0) {
239 dol_print_error($this->db, $object->error);
240 return -1;
241 }
242 }
243
244 $object->fetch_thirdparty();
245
246 $dir = $conf->mrp->multidir_output[isset($object->entity) ? $object->entity : 1];
247 $objectref = dol_sanitizeFileName($object->ref);
248 if (!preg_match('/specimen/i', $objectref)) {
249 $dir .= "/".$objectref;
250 }
251 $file = $dir."/".$objectref.".odt";
252
253 if (!file_exists($dir)) {
254 if (dol_mkdir($dir) < 0) {
255 $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir);
256 return -1;
257 }
258 }
259
260 if (file_exists($dir)) {
261 //print "srctemplatepath=".$srctemplatepath; // Src filename
262 $newfile = basename($srctemplatepath);
263 $newfiletmp = preg_replace('/\.od[ts]/i', '', $newfile);
264 $newfiletmp = preg_replace('/template_/i', '', $newfiletmp);
265 $newfiletmp = preg_replace('/modele_/i', '', $newfiletmp);
266 $newfiletmp = $objectref . '_' . $newfiletmp;
267 //$file=$dir.'/'.$newfiletmp.'.'.dol_print_date(dol_now(),'%Y%m%d%H%M%S').'.odt';
268 // Get extension (ods or odt)
269 $newfileformat = substr($newfile, strrpos($newfile, '.') + 1);
270 if (getDolGlobalString('MAIN_DOC_USE_TIMING')) {
271 $format = getDolGlobalString('MAIN_DOC_USE_TIMING');
272 if ($format == '1') {
273 $format = '%Y%m%d%H%M%S';
274 }
275 $filename = $newfiletmp . '-' . dol_print_date(dol_now(), $format) . '.' . $newfileformat;
276 } else {
277 $filename = $newfiletmp . '.' . $newfileformat;
278 }
279 $file = $dir . '/' . $filename;
280 //print "newdir=".$dir;
281 //print "newfile=".$newfile;
282 //print "file=".$file;
283 //print "conf->societe->dir_temp=".$conf->societe->dir_temp;
284
285 dol_mkdir($conf->mrp->dir_temp);
286 if (!is_writable($conf->mrp->dir_temp)) {
287 $this->error = $langs->transnoentities("ErrorFailedToWriteInTempDirectory", $conf->mrp->dir_temp);
288 dol_syslog('Error in write_file: ' . $this->error, LOG_ERR);
289 return -1;
290 }
291
292 // If CUSTOMER contact defined on order, we use it
293 $usecontact = false;
294 $arrayidcontact = $object->getIdContact('external', 'CUSTOMER');
295 if (count($arrayidcontact) > 0) {
296 $usecontact = true;
297 $result = $object->fetch_contact($arrayidcontact[0]);
298 }
299
300 // Recipient name
301 $contactobject = null;
302 if (!empty($usecontact)) {
303 // We can use the company of contact instead of thirdparty company
304 if ($object->contact->socid != $object->thirdparty->id && (!isset($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT) || !empty($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT))) {
305 $object->contact->fetch_thirdparty();
306 $socobject = $object->contact->thirdparty;
307 $contactobject = $object->contact;
308 } else {
309 $socobject = $object->thirdparty;
310 // if we have a CUSTOMER contact and we dont use it as thirdparty recipient we store the contact object for later use
311 $contactobject = $object->contact;
312 }
313 } else {
314 $socobject = $object->thirdparty;
315 }
316
317 // Make substitution
318 $substitutionarray = array(
319 '__QTY_TO_PRODUCE__' => $object->qty,
320 );
321 complete_substitutions_array($substitutionarray, $langs, $object);
322 // Call the ODTSubstitution hook
323 $parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs, 'substitutionarray'=>&$substitutionarray);
324 $reshook = $hookmanager->executeHooks('ODTSubstitution', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
325
326 // Line of free text
327 $newfreetext = '';
328 $paramfreetext = 'MRP_MO_FREE_TEXT';
329 if (!empty($conf->global->$paramfreetext)) {
330 $newfreetext = make_substitutions($conf->global->$paramfreetext, $substitutionarray);
331 }
332
333 // Open and load template
334 require_once ODTPHP_PATH.'odf.php';
335 try {
336 $odfHandler = new Odf(
337 $srctemplatepath,
338 array(
339 'PATH_TO_TMP' => $conf->mrp->dir_temp,
340 'ZIP_PROXY' => 'PclZipProxy', // PhpZipProxy or PclZipProxy. Got "bad compression method" error when using PhpZipProxy.
341 'DELIMITER_LEFT' => '{',
342 'DELIMITER_RIGHT' => '}'
343 )
344 );
345 } catch (Exception $e) {
346 $this->error = $e->getMessage();
347 dol_syslog($e->getMessage(), LOG_INFO);
348 return -1;
349 }
350
351 // After construction $odfHandler->contentXml contains content and
352 // [!-- BEGIN row.lines --]*[!-- END row.lines --] has been replaced by
353 // [!-- BEGIN lines --]*[!-- END lines --]
354 //print html_entity_decode($odfHandler->__toString());
355 //print exit;
356
357 // Make substitutions into odt of freetext
358 try {
359 $odfHandler->setVars('free_text', $newfreetext, true, 'UTF-8');
360 } catch (OdfException $e) {
361 dol_syslog($e->getMessage(), LOG_INFO);
362 }
363
364 // Define substitution array
365 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object);
366 $array_object_from_properties = $this->get_substitutionarray_each_var_object($object, $outputlangs);
367 $array_objet = $this->get_substitutionarray_object($object, $outputlangs);
368 $array_user = $this->get_substitutionarray_user($user, $outputlangs);
369 $array_soc = $this->get_substitutionarray_mysoc($mysoc, $outputlangs);
370 $array_thirdparty = $this->get_substitutionarray_thirdparty($socobject, $outputlangs);
371 $array_other = $this->get_substitutionarray_other($outputlangs);
372 // retrieve contact information for use in object as contact_xxx tags
373 $array_thirdparty_contact = array();
374 if ($usecontact && is_object($contactobject)) {
375 $array_thirdparty_contact = $this->get_substitutionarray_contact($contactobject, $outputlangs, 'contact');
376 }
377
378 $tmparray = array_merge($substitutionarray, $array_object_from_properties, $array_user, $array_soc, $array_thirdparty, $array_objet, $array_other, $array_thirdparty_contact);
379 complete_substitutions_array($tmparray, $outputlangs, $object);
380
381 // Call the ODTSubstitution hook
382 $parameters = array('odfHandler'=>&$odfHandler, 'file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs, 'substitutionarray'=>&$tmparray);
383 $reshook = $hookmanager->executeHooks('ODTSubstitution', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
384
385 foreach ($tmparray as $key => $value) {
386 try {
387 if (preg_match('/logo$/', $key)) {
388 // Image
389 if (file_exists($value)) {
390 $odfHandler->setImage($key, $value);
391 } else {
392 $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8');
393 }
394 } else {
395 // Text
396 $odfHandler->setVars($key, $value, true, 'UTF-8');
397 }
398 } catch (OdfException $e) {
399 dol_syslog($e->getMessage(), LOG_INFO);
400 }
401 }
402
403 // Replace tags of lines
404 try {
405 $foundtagforlines = 1;
406 try {
407 $listlines = $odfHandler->setSegment('lines');
408 } catch (OdfException $e) {
409 // We may arrive here if tags for lines not present into template
410 $foundtagforlines = 0;
411 dol_syslog($e->getMessage(), LOG_INFO);
412 }
413
414 if ($foundtagforlines) {
415 $linenumber = 0;
416 foreach ($object->lines as $line) {
417 $linenumber++;
418 $tmparray = $this->get_substitutionarray_lines($line, $outputlangs, $linenumber);
419 complete_substitutions_array($tmparray, $outputlangs, $object, $line, "completesubstitutionarray_lines");
420 // Call the ODTSubstitutionLine hook
421 $parameters = array('odfHandler'=>&$odfHandler, 'file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs, 'substitutionarray'=>&$tmparray, 'line'=>$line);
422 $reshook = $hookmanager->executeHooks('ODTSubstitutionLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
423 foreach ($tmparray as $key => $val) {
424 try {
425 $listlines->setVars($key, $val, true, 'UTF-8');
426 } catch (OdfException $e) {
427 dol_syslog($e->getMessage(), LOG_INFO);
428 } catch (SegmentException $e) {
429 dol_syslog($e->getMessage(), LOG_INFO);
430 }
431 }
432 $listlines->merge();
433 }
434 $odfHandler->mergeSegment($listlines);
435 }
436 } catch (OdfException $e) {
437 $this->error = $e->getMessage();
438 dol_syslog($this->error, LOG_WARNING);
439 return -1;
440 }
441
442 // Replace labels translated
443 $tmparray = $outputlangs->get_translations_for_substitutions();
444 foreach ($tmparray as $key => $value) {
445 try {
446 $odfHandler->setVars($key, $value, true, 'UTF-8');
447 } catch (OdfException $e) {
448 dol_syslog($e->getMessage(), LOG_INFO);
449 }
450 }
451
452 // Call the beforeODTSave hook
453
454 $parameters = array('odfHandler'=>&$odfHandler, 'file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs, 'substitutionarray'=>&$tmparray);
455 $reshook = $hookmanager->executeHooks('beforeODTSave', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
456
457 // Write new file
458 if (!empty($conf->global->MAIN_ODT_AS_PDF)) {
459 try {
460 $odfHandler->exportAsAttachedPDF($file);
461 } catch (Exception $e) {
462 $this->error = $e->getMessage();
463 dol_syslog('Error in exportAsAttachedPDF: '.$e->getMessage(), LOG_INFO);
464 return -1;
465 }
466 } else {
467 try {
468 $odfHandler->saveToDisk($file);
469 } catch (Exception $e) {
470 $this->error = $e->getMessage();
471 dol_syslog('Error in saveToDisk: '.$e->getMessage(), LOG_INFO);
472 return -1;
473 }
474 }
475
476 $parameters = array('odfHandler'=>&$odfHandler, 'file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs, 'substitutionarray'=>&$tmparray);
477 $reshook = $hookmanager->executeHooks('afterODTCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
478
479 dolChmod($file);
480
481 $odfHandler = null; // Destroy object
482
483 $this->result = array('fullpath'=>$file);
484
485 return 1; // Success
486 } else {
487 $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir);
488 return -1;
489 }
490 }
491
492 return -1;
493 }
494}
get_substitutionarray_each_var_object(&$object, $outputlangs, $recursive=1)
Define array with couple substitution key => substitution value.
get_substitutionarray_object($object, $outputlangs, $array_key='object')
Define array with couple substitution key => substitution value Note that vars into substitutions arr...
get_substitutionarray_mysoc($mysoc, $outputlangs)
Define array with couple substitution key => substitution value.
get_substitutionarray_contact($object, $outputlangs, $array_key='object')
Define array with couple substitution key => substitution value.
get_substitutionarray_other($outputlangs)
Define array with couple substitution key => substitution value.
get_substitutionarray_lines($line, $outputlangs, $linenumber=0)
Define array with couple substitution key => substitution value Note that vars into substitutions arr...
get_substitutionarray_thirdparty($object, $outputlangs, $array_key='company')
Define array with couple substitution key => substitution value For example {company_name}...
get_substitutionarray_user($user, $outputlangs)
Define array with couple substitution key => substitution value.
Class to manage generation of HTML components Only common components must be here.
Class to manage hooks.
Class for Mo.
Definition mo.class.php:34
Parent class for mos models.
Class to build documents using ODF templates generator.
write_file($object, $outputlangs, $srctemplatepath, $hidedetails=0, $hidedesc=0, $hideref=0)
Function to build a document on disk using the generic odt module.
info($langs)
Return description of a module.
print $script_file $mode $langs defaultlang(is_numeric($duration_value) ? " delay=". $duration_value :"").(is_numeric($duration_value2) ? " after cd cd cd description as description
Only used if Module[ID]Desc translation string is not found.
dol_dir_list($path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:62
img_warning($titlealt='default', $moreatt='', $morecss='pictowarning')
Show warning logo.
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dolChmod($filepath, $newmask='')
Change mod of a file.
dol_now($mode='auto')
Return date for now.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
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...
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
getCommonSubstitutionArray($outputlangs, $onlykey=0, $exclude=null, $object=null, $include=null)
Return array of possible common substitutions.
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
if(preg_match('/crypted:/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
Definition repair.php:120
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition repair.php:123