dolibarr 25.0.0-alpha
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 * Copyright (C) 2018-2025 Frédéric France <frederic.france@free.fr>
5 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 * or see https://www.gnu.org/
20 */
21
28require_once DOL_DOCUMENT_ROOT.'/core/modules/societe/modules_societe.class.php';
29require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
30require_once DOL_DOCUMENT_ROOT.'/core/lib/company.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 $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 = 'COMPANY_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_freetext = 0; // Support add of a personalised text
75 $this->option_draft_watermark = 0; // Support add of a watermark on drafts
76
77 if ($mysoc === null) {
78 dol_syslog(get_class($this).'::__construct() Global $mysoc should not be null.'. getCallerInfoString(), LOG_ERR);
79 return;
80 }
81
82 // Retrieves issuer
83 $this->emetteur = $mysoc;
84 if (!$this->emetteur->country_code) {
85 $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default, if was not defined
86 }
87 }
88
89
96 public function info($langs)
97 {
98 global $langs;
99
100 // Load traductions files required by page
101 $langs->loadLangs(array("companies", "errors"));
102
103 $form = new Form($this->db);
104
105 $texte = $this->description.".<br>\n";
106 $texte .= '<!-- form for option of ODT templates -->';
107 $texte .= '<form action="'.$_SERVER["PHP_SELF"].'" method="POST" enctype="multipart/form-data">';
108 $texte .= '<input type="hidden" name="token" value="'.newToken().'">';
109 $texte .= '<input type="hidden" name="page_y" value="">';
110 $texte .= '<input type="hidden" name="action" value="setModuleOptions">';
111 $texte .= '<input type="hidden" name="param1" value="COMPANY_ADDON_PDF_ODT_PATH">';
112 $texte .= '<table class="nobordernopadding centpercent">';
113
114 // List of directories area
115 $texte .= '<tr><td>';
116 $texttitle = $langs->trans("ListOfDirectories");
117 $listofdir = explode(',', preg_replace('/[\r\n]+/', ',', trim(getDolGlobalString('COMPANY_ADDON_PDF_ODT_PATH'))));
118 $listoffiles = array();
119 foreach ($listofdir as $key => $tmpdir) {
120 $tmpdir = trim($tmpdir);
121 $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
122 if (!$tmpdir) {
123 unset($listofdir[$key]);
124 continue;
125 }
126 if (!is_dir($tmpdir)) {
127 $texttitle .= img_warning($langs->trans("ErrorDirNotFound", $tmpdir), '');
128 } else {
129 $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0, 1); // Disable hook for the moment
130 if (count($tmpfiles)) {
131 $listoffiles = array_merge($listoffiles, $tmpfiles);
132 }
133 }
134 }
135 $texthelp = $langs->trans("ListOfDirectoriesForModelGenODT");
136 $texthelp .= '<br><br><span class="opacitymedium">'.$langs->trans("ExampleOfDirectoriesForModelGen").'</span>';
137 // Add list of substitution keys
138 $texthelp .= '<br>'.$langs->trans("FollowingSubstitutionKeysCanBeUsed").'<br>';
139 $texthelp .= $langs->transnoentitiesnoconv("FullListOnOnlineDocumentation"); // This contains an url, we don't modify it
140
141 // Scan directories
142 $nbofiles = count($listoffiles);
143 if (getDolGlobalString('COMPANY_ADDON_PDF_ODT_PATH')) {
144 $texte .= '<span class="opacitylow">'.$langs->trans("NumberOfModelFilesFound").': <b>';
145 //$texte.=$nbofiles?'<a id="a_'.get_class($this).'" href="#">':'';
146 $texte .= $nbofiles;
147 //$texte.=$nbofiles?'</a>':'';
148 $texte .= '</b></span><br>';
149 }
150
151 if ($nbofiles) {
152 $texte .= '<div id="div_'.get_class($this).'" class="hiddenx opacitylow">';
153 // Show list of found files
154 foreach ($listoffiles as $file) {
155 $texte .= '- '.$file['name'].' &nbsp; <a class="reposition" href="'.DOL_URL_ROOT.'/document.php?modulepart=doctemplates&file=thirdparties/'.urlencode(basename($file['name'])).'">'.img_picto('', 'listlight').'</a>';
156 $texte .= ' &nbsp; <a class="reposition" href="'.$_SERVER["PHP_SELF"].'?modulepart=doctemplates&keyforuploaddir=COMPANY_ADDON_PDF_ODT_PATH&action=deletefile&token='.newToken().'&file='.urlencode(basename($file['name'])).'">'.img_picto('', 'delete').'</a>';
157 $texte .= '<br>';
158 }
159 $texte .= '</div>';
160 }
161 $texte .= '<br>';
162 // Link to show/hide the area to manage directories of ODT models and template files
163 $texte .= '<span class="classlink cursorpointer" onclick="javascript: jQuery(\'.div_odtmodelsof'.get_class($this).'\').toggle();">'.img_picto('', 'add').' '.$langs->trans("UploadNewTemplate").'...</span>';
164 $texte .= '<div class="div_odtmodelsof'.get_class($this).'" style="display: none; margin-top: 6px;">';
165 if (!getDolGlobalString('MAIN_NO_MULTIDIR_FOR_ODT')) {
166 $texte .= $form->textwithpicto($texttitle, $texthelp, 1, 'help', '', 1, 3, $this->name);
167 $texte .= '<div><div style="display: inline-block; min-width: 100px; vertical-align: middle;">';
168 //$texte .= '<table><tr><td>';
169 $texte .= '<textarea class="flat textareafordir" spellcheck="false" cols="60" name="value1">';
170 $texte .= getDolGlobalString('COMPANY_ADDON_PDF_ODT_PATH');
171 $texte .= '</textarea>';
172 //$texte .= '</td>';
173 //$texte .= '<td class="center">&nbsp; ';
174 $texte .= '</div><div style="display: inline-block; vertical-align: middle;">';
175 $texte .= '<input type="submit" class="button button-edit reposition smallpaddingimp" name="modify" value="'.dol_escape_htmltag($langs->trans("Modify")).'">';
176 //$texte .= '</td>';
177 //$texte .= '</tr>';
178 //$texte .= '</table>';
179 $texte .= '</div></div>';
180 } else {
181 $texte .= '<br>';
182 $texte .= '<input type="hidden" name="value1" value="COMPANY_ADDON_PDF_ODT_PATH">';
183 }
184 $texte .= '</div>';
185
186 // Add input to upload a new template file.
187 $texte .= '<div class="div_odtmodelsof'.get_class($this).'" style="display: none;">';
188 $maxfilesizearray = getMaxFileSizeArray();
189 $maxmin = $maxfilesizearray['maxmin'];
190 if ($maxmin > 0) {
191 $texte .= '<input type="hidden" name="MAX_FILE_SIZE" value="'.($maxmin * 1024).'">'; // MAX_FILE_SIZE must precede the field type=file
192 }
193 $texte .= ' <input type="file" name="uploadfile">';
194 $texte .= '<input type="hidden" value="COMPANY_ADDON_PDF_ODT_PATH" name="keyforuploaddir">';
195 $texte .= '<input type="submit" class="button smallpaddingimp reposition" value="'.dol_escape_htmltag($langs->trans("Upload")).'" name="upload">';
196 $texte .= '</div>';
197 $texte .= '</td>';
198
199 $texte .= '</tr>';
200
201 $texte .= '</table>';
202 $texte .= '</form>';
203
204 return $texte;
205 }
206
207 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
219 public function write_file($object, $outputlangs, $srctemplatepath = '', $hidedetails = 0, $hidedesc = 0, $hideref = 0)
220 {
221 // phpcs:enable
222 global $user, $langs, $conf, $mysoc, $hookmanager;
223 global $action;
224
225 if (empty($srctemplatepath)) {
226 dol_syslog("doc_generic_odt::write_file parameter srctemplatepath empty", LOG_WARNING);
227 return -1;
228 }
229
230 // Add odtgeneration hook
231 if (!is_object($hookmanager)) {
232 include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
233 $hookmanager = new HookManager($this->db);
234 }
235 $hookmanager->initHooks(array('odtgeneration'));
236 global $action;
237
238 if (!is_object($outputlangs)) {
239 $outputlangs = $langs;
240 }
241 $sav_charset_output = $outputlangs->charset_output;
242 $outputlangs->charset_output = 'UTF-8';
243
244 // Load translation files required by the page
245 $outputlangs->loadLangs(array("main", "dict", "companies", "projects"));
246
247 if ($conf->societe->multidir_output[$object->entity ?? $conf->entity]) {
248 $dir = $conf->societe->multidir_output[$object->entity ?? $conf->entity];
249 $objectref = dol_sanitizeFileName((string) $object->id);
250 if (!preg_match('/specimen/i', $objectref)) {
251 $dir .= "/".$objectref;
252 }
253
254 if (!file_exists($dir)) {
255 if (dol_mkdir($dir) < 0) {
256 $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir);
257 return -1;
258 }
259 }
260
261 if (file_exists($dir)) {
262 //print "srctemplatepath=".$srctemplatepath; // Src filename
263 $newfile = basename($srctemplatepath);
264 $newfiletmp = preg_replace('/\.od(s|t)/i', '', $newfile);
265 $newfiletmp = preg_replace('/template_/i', '', $newfiletmp);
266 $newfiletmp = preg_replace('/modele_/i', '', $newfiletmp);
267 // Get extension (ods or odt)
268 $newfileformat = substr($newfile, strrpos($newfile, '.') + 1);
269 if (getDolGlobalString('MAIN_DOC_USE_OBJECT_THIRDPARTY_NAME')) {
270 $newfiletmp = dol_sanitizeFileName(dol_string_nospecial($object->name)) . '-' . $newfiletmp;
271 $newfiletmp = preg_replace('/__+/', '_', $newfiletmp); // Replace repeated _ into one _ (to avoid string with substitution syntax)
272 }
273 if (getDolGlobalString('MAIN_DOC_USE_TIMING')) {
274 $format = getDolGlobalString('MAIN_DOC_USE_TIMING');
275 if ($format == '1') {
276 $format = '%Y%m%d%H%M%S';
277 }
278 $filename = $newfiletmp . '-' . dol_print_date(dol_now(), $format) . '.' . $newfileformat;
279 } else {
280 $filename = $newfiletmp . '.' . $newfileformat;
281 }
282 $file = $dir . '/' . $filename;
283 $object->builddoc_filename = $filename; // For triggers
284 $object->context['builddoc_filename'] = $filename; // For triggers
285 //print "newfileformat=".$newfileformat;
286 //print "newdir=".$dir;
287 //print "newfile=".$newfile;
288 //print "file=".$file;
289 //print "conf->societe->dir_temp=".$conf->societe->dir_temp;
290 //exit;
291
292 dol_mkdir($conf->societe->multidir_temp[$object->entity]);
293 if (!is_writable($conf->societe->multidir_temp[$object->entity])) {
294 $this->error = $langs->transnoentities("ErrorFailedToWriteInTempDirectory", $conf->societe->multidir_temp[$object->entity]);
295 dol_syslog('Error in write_file: ' . $this->error, LOG_ERR);
296 return -1;
297 }
298
299 // Open and load template
300 require_once ODTPHP_PATH.'odf.php';
301 try {
302 $odfHandler = new Odf(
303 $srctemplatepath,
304 array(
305 'PATH_TO_TMP' => $conf->societe->multidir_temp[$object->entity],
306 'ZIP_PROXY' => getDolGlobalString('MAIN_ODF_ZIP_PROXY', 'PclZipProxy'), // PhpZipProxy or PclZipProxy. Got "bad compression method" error when using PhpZipProxy.
307 'DELIMITER_LEFT' => '{',
308 'DELIMITER_RIGHT' => '}'
309 )
310 );
311 } catch (Exception $e) {
312 $this->error = $e->getMessage();
313 dol_syslog($e->getMessage(), LOG_INFO);
314 return -1;
315 }
316 //print $odfHandler->__toString()."\n";
317
318 // Replace tags of lines for contacts
319 $contact_arrray = array();
320
321 $sql = "SELECT p.rowid";
322 $sql .= " FROM ".MAIN_DB_PREFIX."socpeople as p";
323 $sql .= " WHERE p.fk_soc = ".((int) $object->id);
324
325 $result = $this->db->query($sql);
326 $num = $this->db->num_rows($result);
327 $contactstatic = null;
328
329 if ($num) {
330 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
331
332 $i = 0;
333 $contactstatic = new Contact($this->db);
334
335 while ($i < $num) {
336 $obj = $this->db->fetch_object($result);
337
338 $contact_arrray[$i] = $obj->rowid;
339 $i++;
340 }
341 }
342 if ((is_array($contact_arrray) && count($contact_arrray) > 0)) {
343 $listlines = null;
344 try {
345 $listlines = $odfHandler->setSegment('companycontacts');
346 } catch (OdfExceptionSegmentNotFound $e) {
347 // We may arrive here if tags for lines not present into template
348 $listlines = null;
349 dol_syslog($e->getMessage(), LOG_INFO);
350 }
351 if ($listlines !== null && $contactstatic !== null) {
352 foreach ($contact_arrray as $array_key => $contact_id) {
353 $res_contact = $contactstatic->fetch($contact_id);
354 if ((int) $res_contact > 0) {
355 $tmparray = $this->get_substitutionarray_contact($contactstatic, $outputlangs, 'contact');
356 foreach ($tmparray as $key => $val) {
357 try {
358 $listlines->setVars($key, $val, true, 'UTF-8');
359 } catch (SegmentException $e) {
360 dol_syslog($e->getMessage(), LOG_INFO);
361 }
362 }
363 $listlines->merge();
364 } else {
365 $this->error = $contactstatic->error;
366 dol_syslog($this->error, LOG_WARNING);
367 }
368 }
369 try {
370 $odfHandler->mergeSegment($listlines);
371 } catch (OdfException $e) {
372 $this->error = $e->getMessage();
373 dol_syslog($this->error, LOG_WARNING);
374 //return -1;
375 }
376 }
377 }
378
379 // Make substitutions into odt
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($object, $outputlangs);
383 $array_other = $this->get_substitutionarray_other($outputlangs);
384
385 $tmparray = array_merge($array_user, $array_soc, $array_thirdparty, $array_other);
386
387 complete_substitutions_array($tmparray, $outputlangs, $object);
388
389 // Call the ODTSubstitution hook
390 $parameters = array('odfHandler' => &$odfHandler, 'file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$tmparray);
391 $reshook = $hookmanager->executeHooks('ODTSubstitution', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
392
393 // retrieve the constant to apply a ratio for image size or set the ratio to 1
394 if (getDolGlobalString('MAIN_DOC_ODT_IMAGE_RATIO')) {
395 $ratio = (float) getDolGlobalString('MAIN_DOC_ODT_IMAGE_RATIO');
396 } else {
397 $ratio = 1;
398 }
399
400 // Replace variables into document
401 foreach ($tmparray as $key => $value) {
402 try {
403 if (preg_match('/logo$/', $key)) { // Image
404 if (file_exists($value)) {
405 $odfHandler->setImage($key, $value, $ratio);
406 } else {
407 $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8');
408 }
409 } else { // Text
410 $odfHandler->setVars($key, $value, true, 'UTF-8');
411 }
412 } catch (OdfException $e) {
413 // setVars failed, probably because key not found
414 dol_syslog($e->getMessage(), LOG_INFO);
415 }
416 }
417
418 // Replace labels translated
419 $tmparray = $outputlangs->get_translations_for_substitutions();
420 foreach ($tmparray as $key => $value) {
421 try {
422 $odfHandler->setVars($key, $value, true, 'UTF-8');
423 } catch (OdfException $e) {
424 dol_syslog($e->getMessage(), LOG_INFO);
425 }
426 }
427
428 // Call the beforeODTSave hook
429 $parameters = array('odfHandler' => &$odfHandler, 'file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$tmparray);
430 $reshook = $hookmanager->executeHooks('beforeODTSave', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
431
432 // Write new file
433 if (getDolGlobalString('MAIN_ODT_AS_PDF')) {
434 try {
435 $odfHandler->exportAsAttachedPDF($file);
436 } catch (Exception $e) {
437 $this->error = $e->getMessage();
438 dol_syslog($e->getMessage(), LOG_INFO);
439 return -1;
440 }
441 } else {
442 try {
443 $odfHandler->creator = $user->getFullName($outputlangs);
444 $odfHandler->title = $object->builddoc_filename;
445 $odfHandler->subject = $object->builddoc_filename;
446
447 if (getDolGlobalString('ODT_ADD_DOLIBARR_ID')) {
448 $odfHandler->userdefined['dol_id'] = $object->id;
449 $odfHandler->userdefined['dol_element'] = $object->element;
450 }
451
452 $odfHandler->saveToDisk($file);
453 } catch (Exception $e) {
454 $this->error = $e->getMessage();
455 dol_syslog($e->getMessage(), LOG_INFO);
456 return -1;
457 }
458 }
459 $parameters = array('odfHandler' => &$odfHandler, 'file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$tmparray);
460 $reshook = $hookmanager->executeHooks('afterODTCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
461
462 dolChmod($file);
463
464 $odfHandler = null; // Destroy object
465
466 $this->result = array('fullpath' => $file);
467
468 return 1; // Success
469 } else {
470 $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir);
471 return -1;
472 }
473 }
474
475 $this->error = 'UnknownError';
476 return -1;
477 }
478}
$propal type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
Definition propal.php:281
Class to manage generation of HTML components Only common components must be here.
Parent class for third parties models of doc generators.
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.
__construct($db)
Constructor.
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