dolibarr 25.0.0-alpha
doc_generic_reception_odt.modules.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2018 Quentin Vial-Gouteyron <quentin.vial-gouteyron@atm-consulting.fr>
3 * Copyright (C) 2019-2025 Frédéric France <frederic.france@free.fr>
4 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.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 <https://www.gnu.org/licenses/>.
18 * or see https://www.gnu.org/
19 */
20
27require_once DOL_DOCUMENT_ROOT.'/core/modules/reception/modules_reception.php';
28require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
29require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
30require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
31require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
32require_once DOL_DOCUMENT_ROOT.'/core/lib/doc.lib.php';
33
34
39{
43 public $version = 'dolibarr';
44
45
51 public function __construct($db)
52 {
53 global $conf, $langs, $mysoc;
54
55 // Load translation files required by the page
56 $langs->loadLangs(array("main", "companies"));
57
58 $this->db = $db;
59 $this->name = "ODT templates";
60 $this->description = $langs->trans("DocumentModelOdt");
61 $this->scandir = 'RECEPTION_ADDON_PDF_ODT_PATH'; // Name of constant that is used to save list of directories to scan
62
63 // Page size for A4 format
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; // Display logo
74 $this->option_tva = 0; // Manage the vat option RECEPTION_TVAOPTION
75 $this->option_modereg = 0; // Display payment mode
76 $this->option_condreg = 0; // Display payment terms
77 $this->option_multilang = 1; // Available in several languages
78 $this->option_escompte = 0; // Displays if there has been a discount
79 $this->option_credit_note = 0; // Support credit notes
80 $this->option_freetext = 1; // Support add of a personalised text
81 $this->option_draft_watermark = 0; // Support add of a watermark on drafts
82
83 if ($mysoc === null) {
84 dol_syslog(get_class($this).'::__construct() Global $mysoc should not be null.'. getCallerInfoString(), LOG_ERR);
85 return;
86 }
87
88 // Get source company
89 $this->emetteur = $mysoc;
90 if (!$this->emetteur->country_code) {
91 $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default if not defined
92 }
93 }
94
95
102 public function info($langs)
103 {
104 global $conf, $langs;
105
106 // Load translation files required by the page
107 $langs->loadLangs(array("companies", "errors"));
108
109 $form = new Form($this->db);
110
111 $odtPath = trim(getDolGlobalString('RECEPTION_ADDON_PDF_ODT_PATH'));
112
113 $texte = $this->description.".<br>\n";
114 $texte .= '<form action="'.$_SERVER["PHP_SELF"].'" method="POST" enctype="multipart/form-data">';
115 $texte .= '<input type="hidden" name="token" value="'.newToken().'">';
116 $texte .= '<input type="hidden" name="page_y" value="">';
117 $texte .= '<input type="hidden" name="action" value="setModuleOptions">';
118 $texte .= '<input type="hidden" name="param1" value="RECEPTION_ADDON_PDF_ODT_PATH">';
119 $texte .= '<table class="nobordernopadding centpercent">';
120
121 // List of directories area
122 $texte .= '<tr><td>';
123 $texttitle = $langs->trans("ListOfDirectories");
124 $listofdir = explode(',', preg_replace('/[\r\n]+/', ',', $odtPath));
125 $listoffiles = array();
126 foreach ($listofdir as $key => $tmpdir) {
127 $tmpdir = trim($tmpdir);
128 $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
129 if (!$tmpdir) {
130 unset($listofdir[$key]);
131 continue;
132 }
133 if (!is_dir($tmpdir)) {
134 $texttitle .= img_warning($langs->trans("ErrorDirNotFound", $tmpdir), '');
135 } else {
136 $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.(ods|odt)');
137 if (count($tmpfiles)) {
138 $listoffiles = array_merge($listoffiles, $tmpfiles);
139 }
140 }
141 }
142 $texthelp = $langs->trans("ListOfDirectoriesForModelGenODT");
143 $texthelp .= '<br><br><span class="opacitymedium">'.$langs->trans("ExampleOfDirectoriesForModelGen").'</span>';
144 // Add list of substitution keys
145 $texthelp .= '<br>'.$langs->trans("FollowingSubstitutionKeysCanBeUsed").'<br>';
146 $texthelp .= $langs->transnoentitiesnoconv("FullListOnOnlineDocumentation"); // This contains an url, we don't modify it
147
148 // Scan directories
149 $nbofiles = count($listoffiles);
150 if (!empty($odtPath)) {
151 $texte .= '<span class="opacitylow">'.$langs->trans("NumberOfModelFilesFound").': <b>';
152 //$texte.=$nbofiles?'<a id="a_'.get_class($this).'" href="#">':'';
153 $texte .= count($listoffiles);
154 //$texte.=$nbofiles?'</a>':'';
155 $texte .= '</b></span><br>';
156 }
157 if ($nbofiles) {
158 $texte .= '<div id="div_'.get_class($this).'" class="hiddenx opacitylow">';
159 // Show list of found files
160 foreach ($listoffiles as $file) {
161 $texte .= '- '.$file['name'];
162 $texte .= ' <a href="'.DOL_URL_ROOT.'/document.php?modulepart=doctemplates&file=receptions/'.urlencode(basename($file['name'])).'">'.img_picto('', 'listlight').'</a>';
163 $texte .= ' &nbsp; <a class="reposition" href="'.$_SERVER["PHP_SELF"].'?modulepart=doctemplates&keyforuploaddir=RECEPTION_ADDON_PDF_ODT_PATH&action=deletefile&token='.newToken().'&file='.urlencode(basename($file['name'])).'">'.img_picto('', 'delete').'</a>';
164 $texte .= '<br>';
165 }
166 $texte .= '</div>';
167 }
168
169 $texte .= '<br>';
170 // Link to show/hide the area to manage directories of ODT models and template files
171 $texte .= '<span class="classlink cursorpointer" onclick="javascript: jQuery(\'.div_odtmodelsof'.get_class($this).'\').toggle();">'.img_picto('', 'add').' '.$langs->trans("UploadNewTemplate").'...</span>';
172 $texte .= '<div class="div_odtmodelsof'.get_class($this).'" style="display: none; margin-top: 6px;">';
173 $texte .= $form->textwithpicto($texttitle, $texthelp, 1, 'help', '', 1, 3, $this->name);
174 $texte .= '<div><div style="display: inline-block; min-width: 100px; vertical-align: middle;">';
175 $texte .= '<textarea class="flat textareafordir" spellcheck="false" cols="60" name="value1">';
176 $texte .= $odtPath;
177 $texte .= '</textarea>';
178 $texte .= '</div><div style="display: inline-block; vertical-align: middle;">';
179 $texte .= '<input type="submit" class="button button-edit reposition smallpaddingimp" name="modify" value="'.dol_escape_htmltag($langs->trans("Modify")).'">';
180 $texte .= '<br></div></div>';
181
182 // Add input to upload a new template file.
183 $texte .= '<div>';
184 $maxfilesizearray = getMaxFileSizeArray();
185 $maxmin = $maxfilesizearray['maxmin'];
186 if ($maxmin > 0) {
187 $texte .= '<input type="hidden" name="MAX_FILE_SIZE" value="'.($maxmin * 1024).'">'; // MAX_FILE_SIZE must precede the field type=file
188 }
189 $texte .= ' <input type="file" name="uploadfile">';
190 $texte .= '<input type="hidden" value="RECEPTION_ADDON_PDF_ODT_PATH" name="keyforuploaddir">';
191 $texte .= '<input type="submit" class="button smallpaddingimp reposition" value="'.dol_escape_htmltag($langs->trans("Upload")).'" name="upload">';
192 $texte .= '</div>';
193 $texte .= '</div>';
194
195 $texte .= '</td>';
196
197 $texte .= '</tr>';
198
199 $texte .= '</table>';
200 $texte .= '</form>';
201
202 return $texte;
203 }
204
205 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
217 public function write_file($object, $outputlangs, $srctemplatepath = '', $hidedetails = 0, $hidedesc = 0, $hideref = 0)
218 {
219 // phpcs:enable
220 global $user, $langs, $conf, $mysoc, $hookmanager;
221
222 if (empty($srctemplatepath)) {
223 dol_syslog("doc_generic_odt::write_file parameter srctemplatepath empty", LOG_WARNING);
224 return -1;
225 }
226
227 // Add odtgeneration hook
228 if (!is_object($hookmanager)) {
229 include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
230 $hookmanager = new HookManager($this->db);
231 }
232 $hookmanager->initHooks(array('odtgeneration'));
233 global $action;
234
235 if (!is_object($outputlangs)) {
236 $outputlangs = $langs;
237 }
238 $sav_charset_output = $outputlangs->charset_output;
239 $outputlangs->charset_output = 'UTF-8';
240
241 $outputlangs->loadLangs(array("main", "dict", "companies", "bills"));
242
243 if ($conf->reception->dir_output) {
244 // If $object is id instead of object
245 if (!is_object($object)) {
246 $id = $object;
247 $object = new Reception($this->db);
248 $result = $object->fetch($id);
249 if ($result < 0) {
250 dol_print_error($this->db, $object->error);
251 return -1;
252 }
253 }
254
255 $object->fetch_thirdparty();
256
257 $dir = !empty($conf->reception->multidir_output[$object->entity ?? $conf->entity]) ? $conf->reception->multidir_output[$object->entity ?? $conf->entity] : $conf->reception->dir_output;
258 $objectref = dol_sanitizeFileName($object->ref);
259 if (!preg_match('/specimen/i', $objectref)) {
260 $dir .= "/".$objectref;
261 }
262 $file = $dir."/".$objectref.".odt";
263
264 if (!file_exists($dir)) {
265 if (dol_mkdir($dir) < 0) {
266 $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir);
267 return -1;
268 }
269 }
270
271 if (file_exists($dir)) {
272 //print "srctemplatepath=".$srctemplatepath; // Src filename
273 $newfile = basename($srctemplatepath);
274 $newfiletmp = preg_replace('/\.od[ts]/i', '', $newfile);
275 $newfiletmp = preg_replace('/template_/i', '', $newfiletmp);
276 $newfiletmp = preg_replace('/modele_/i', '', $newfiletmp);
277 $newfiletmp = $objectref . '_' . $newfiletmp;
278 //$file=$dir.'/'.$newfiletmp.'.'.dol_print_date(dol_now(),'%Y%m%d%H%M%S').'.odt';
279 // Get extension (ods or odt)
280 $newfileformat = substr($newfile, strrpos($newfile, '.') + 1);
281 if (getDolGlobalString('MAIN_DOC_USE_TIMING')) {
282 $format = getDolGlobalString('MAIN_DOC_USE_TIMING');
283 if ($format == '1') {
284 $format = '%Y%m%d%H%M%S';
285 }
286 $filename = $newfiletmp . '-' . dol_print_date(dol_now(), $format) . '.' . $newfileformat;
287 } else {
288 $filename = $newfiletmp . '.' . $newfileformat;
289 }
290 $file = $dir . '/' . $filename;
291 //print "newdir=".$dir;
292 //print "newfile=".$newfile;
293 //print "file=".$file;
294 //print "conf->societe->dir_temp=".$conf->societe->dir_temp;
295
296 dol_mkdir($conf->reception->dir_temp);
297 if (!is_writable($conf->reception->dir_temp)) {
298 $this->error = $langs->transnoentities("ErrorFailedToWriteInTempDirectory", $conf->reception->dir_temp);
299 dol_syslog('Error in write_file: ' . $this->error, LOG_ERR);
300 return -1;
301 }
302
303 // If CUSTOMER contact defined on reception, we use it
304 $usecontact = false;
305 $arrayidcontact = $object->getIdContact('external', 'CUSTOMER');
306 if (count($arrayidcontact) > 0) {
307 $usecontact = true;
308 $result = $object->fetch_contact($arrayidcontact[0]);
309 }
310
311 // Recipient name
312 $contactobject = null;
313 if (!empty($usecontact)) {
314 // We can use the company of contact instead of thirdparty company
315 if ($object->contact->socid != $object->thirdparty->id && (!isset($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT) || getDolGlobalString('MAIN_USE_COMPANY_NAME_OF_CONTACT'))) {
316 $object->contact->fetch_thirdparty();
317 $socobject = $object->contact->thirdparty;
318 $contactobject = $object->contact;
319 } else {
320 $socobject = $object->thirdparty;
321 // if we have a CUSTOMER contact and we don't use it as thirdparty recipient we store the contact object for later use
322 $contactobject = $object->contact;
323 }
324 } else {
325 $socobject = $object->thirdparty;
326 }
327
328 // Make substitution
329 $substitutionarray = array(
330 '__FROM_NAME__' => $this->emetteur->name,
331 '__FROM_EMAIL__' => $this->emetteur->email,
332 '__TOTAL_TTC__' => $object->total_ttc,
333 '__TOTAL_HT__' => $object->total_ht,
334 '__TOTAL_VAT__' => $object->total_tva
335 );
336 complete_substitutions_array($substitutionarray, $langs, $object);
337
338 // Call the ODTSubstitution hook
339 $parameters = array('file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$substitutionarray);
340 $reshook = $hookmanager->executeHooks('ODTSubstitution', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
341
342 // Line of free text
343 $newfreetext = '';
344 $paramfreetext = 'RECEPTION_FREE_TEXT';
345 if (getDolGlobalString($paramfreetext)) {
346 $newfreetext = make_substitutions(getDolGlobalString($paramfreetext), $substitutionarray);
347 }
348
349 // Open and load template
350 require_once ODTPHP_PATH.'odf.php';
351 try {
352 $odfHandler = new Odf(
353 $srctemplatepath,
354 array(
355 'PATH_TO_TMP' => $conf->reception->dir_temp,
356 'ZIP_PROXY' => getDolGlobalString('MAIN_ODF_ZIP_PROXY', 'PclZipProxy'), // PhpZipProxy or PclZipProxy. Got "bad compression method" error when using PhpZipProxy.
357 'DELIMITER_LEFT' => '{',
358 'DELIMITER_RIGHT' => '}'
359 )
360 );
361 } catch (Exception $e) {
362 $this->error = $e->getMessage();
363 dol_syslog($e->getMessage(), LOG_INFO);
364 return -1;
365 }
366 // After construction $odfHandler->contentXml contains content and
367 // [!-- BEGIN row.lines --]*[!-- END row.lines --] has been replaced by
368 // [!-- BEGIN lines --]*[!-- END lines --]
369
370
371 // Make substitutions into odt of freetext
372 try {
373 $odfHandler->setVars('free_text', $newfreetext, true, 'UTF-8');
374 } catch (OdfException $e) {
375 dol_syslog($e->getMessage(), LOG_INFO);
376 }
377
378 // Define substitution array
379 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object);
380 $array_object_from_properties = $this->get_substitutionarray_each_var_object($object, $outputlangs);
381 $array_objet = $this->get_substitutionarray_object($object, $outputlangs);
382 $array_user = $this->get_substitutionarray_user($user, $outputlangs);
383 $array_soc = $this->get_substitutionarray_mysoc($mysoc, $outputlangs);
384 $array_thirdparty = $this->get_substitutionarray_thirdparty($socobject, $outputlangs);
385 $array_other = $this->get_substitutionarray_other($outputlangs);
386 // retrieve contact information for use in object as contact_xxx tags
387 $array_thirdparty_contact = array();
388 if ($usecontact && is_object($contactobject)) {
389 $array_thirdparty_contact = $this->get_substitutionarray_contact($contactobject, $outputlangs, 'contact');
390 }
391
392 $tmparray = array_merge($substitutionarray, $array_object_from_properties, $array_user, $array_soc, $array_thirdparty, $array_objet, $array_other, $array_thirdparty_contact);
393 complete_substitutions_array($tmparray, $outputlangs, $object);
394
395 // Call the ODTSubstitution hook
396 $parameters = array('odfHandler' => &$odfHandler, 'file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$tmparray);
397 $reshook = $hookmanager->executeHooks('ODTSubstitution', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
398
399 // retrieve the constant to apply a ratio for image size or set the ratio to 1
400 if (getDolGlobalString('MAIN_DOC_ODT_IMAGE_RATIO')) {
401 $ratio = (float) getDolGlobalString('MAIN_DOC_ODT_IMAGE_RATIO');
402 } else {
403 $ratio = 1;
404 }
405
406 foreach ($tmparray as $key => $value) {
407 try {
408 if (preg_match('/logo$/', $key)) { // Image
409 if (file_exists($value)) {
410 $odfHandler->setImage($key, $value, $ratio);
411 } else {
412 $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8');
413 }
414 } else { // Text
415 $odfHandler->setVars($key, $value, true, 'UTF-8');
416 }
417 } catch (OdfException $e) {
418 dol_syslog($e->getMessage(), LOG_INFO);
419 }
420 }
421 // Replace tags of lines
422 $foundtagforlines = 1;
423 try {
424 $listlines = $odfHandler->setSegment('lines');
425 } catch (OdfExceptionSegmentNotFound $e) {
426 // We may arrive here if tags for lines not present into template
427 $foundtagforlines = 0;
428 dol_syslog($e->getMessage(), LOG_INFO);
429 }
430 if ($foundtagforlines) {
431 $linenumber = 0;
432 foreach ($object->lines as $line) {
434 $linenumber++;
435 $tmparray = $this->get_substitutionarray_lines($line, $outputlangs);
436 complete_substitutions_array($tmparray, $outputlangs, $object, $line, "completesubstitutionarray_lines");
437 // Call the ODTSubstitutionLine hook
438 $parameters = array('odfHandler' => &$odfHandler, 'file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$tmparray, 'line' => $line);
439 $reshook = $hookmanager->executeHooks('ODTSubstitutionLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
440 foreach ($tmparray as $key => $val) {
441 try {
442 $listlines->setVars($key, $val, true, 'UTF-8');
443 } catch (SegmentException $e) {
444 dol_syslog($e->getMessage(), LOG_INFO);
445 }
446 }
447 $listlines->merge();
448 }
449 try {
450 $odfHandler->mergeSegment($listlines);
451 } catch (OdfException $e) {
452 $this->error = $e->getMessage();
453 dol_syslog($this->error, LOG_WARNING);
454 return -1;
455 }
456 }
457
458 // Replace labels translated
459 $tmparray = $outputlangs->get_translations_for_substitutions();
460 foreach ($tmparray as $key => $value) {
461 try {
462 $odfHandler->setVars($key, $value, true, 'UTF-8');
463 } catch (OdfException $e) {
464 dol_syslog($e->getMessage(), LOG_INFO);
465 }
466 }
467
468 // Call the beforeODTSave hook
469 $parameters = array('odfHandler' => &$odfHandler, 'file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$tmparray);
470 $reshook = $hookmanager->executeHooks('beforeODTSave', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
471
472 // Write new file
473 if (getDolGlobalString('MAIN_ODT_AS_PDF')) {
474 try {
475 $odfHandler->exportAsAttachedPDF($file);
476 } catch (Exception $e) {
477 $this->error = $e->getMessage();
478 dol_syslog($e->getMessage(), LOG_INFO);
479 return -1;
480 }
481 } else {
482 try {
483 $odfHandler->saveToDisk($file);
484 } catch (Exception $e) {
485 $this->error = $e->getMessage();
486 dol_syslog($e->getMessage(), LOG_INFO);
487 return -1;
488 }
489 }
490 $parameters = array('odfHandler' => &$odfHandler, 'file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$tmparray);
491 $reshook = $hookmanager->executeHooks('afterODTCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
492
493 dolChmod($file);
494
495 $odfHandler = null; // Destroy object
496
497 $this->result = array('fullpath' => $file);
498
499 return 1; // Success
500 } else {
501 $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir);
502 }
503 }
504
505 return -1;
506 }
507}
$propal type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
Definition propal.php:281
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to manage generation of HTML components Only common components must be here.
Parent class of sending receipts models.
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.
info($langs)
Return description of a module.
global $mysoc
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($utf8_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:66
getCallerInfoString()
Get caller info as a string that can be appended to a log message.
newToken()
Return the value of token currently saved into session with name 'newtoken'.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
conf($dolibarr_main_document_root, $realpathconf=null)
Load conf file (file must exists)
Definition inc.php:431
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition repair.php:165
multi select button
0 = Do not include form tag and submit button -1 = Do not include form tag but include submit button