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