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