dolibarr 25.0.0-alpha
doc_generic_user_odt.modules.php
Go to the documentation of this file.
1<?php
2
3/* Copyright (C) 2010-2012 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2012 Juanjo Menent <jmenent@2byte.es>
5 * Copyright (C) 2018-2025 Frédéric France <frederic.france@free.fr>
6 * Copyright (C) 2024-2025 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/user/modules_user.class.php';
30require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
31require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
32require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
33require_once DOL_DOCUMENT_ROOT.'/core/lib/doc.lib.php';
34
35
40{
45 public $version = 'dolibarr';
46
47
53 public function __construct($db)
54 {
55 global $langs, $mysoc;
56
57 // Load translation files required by the page
58 $langs->loadLangs(array("main", "companies"));
59
60 $this->db = $db;
61 $this->name = "ODT templates";
62 $this->description = $langs->trans("DocumentModelOdt");
63 $this->scandir = 'USER_ADDON_PDF_ODT_PATH'; // Name of constant that is used to save list of directories to scan
64
65 // Page size for A4 format
66 $this->type = 'odt';
67 $this->page_largeur = 0;
68 $this->page_hauteur = 0;
69 $this->format = array($this->page_largeur, $this->page_hauteur);
70 $this->marge_gauche = 0;
71 $this->marge_droite = 0;
72 $this->marge_haute = 0;
73 $this->marge_basse = 0;
74
75 $this->option_logo = 1; // Display logo
76 $this->option_tva = 0; // Manage the vat option USER_TVAOPTION
77 $this->option_modereg = 0; // Display payment mode
78 $this->option_condreg = 0; // Display payment terms
79 $this->option_multilang = 1; // Available in several languages
80 $this->option_escompte = 0; // Displays if there has been a discount
81 $this->option_credit_note = 0; // Support credit notes
82 $this->option_freetext = 1; // Support add of a personalised text
83 $this->option_draft_watermark = 0; // Support add of a watermark on drafts
84
85 if ($mysoc === null) {
86 dol_syslog(get_class($this).'::__construct() Global $mysoc should not be null.'. getCallerInfoString(), LOG_ERR);
87 return;
88 }
89
90 // Get source company
91 $this->emetteur = $mysoc;
92 if (!$this->emetteur->country_code) {
93 $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default if not defined
94 }
95 }
96
97
104 public function info($langs)
105 {
106 global $langs;
107
108 // Load translation files required by the page
109 $langs->loadLangs(array('companies', 'errors'));
110
111 $form = new Form($this->db);
112
113 $odtChosen = getDolGlobalInt('MAIN_PROPAL_CHOOSE_ODT_DOCUMENT') > 0;
114 $odtPath = trim(getDolGlobalString('USER_ADDON_PDF_ODT_PATH'));
115
116 $out = $this->description.".<br>\n";
117 $out .= '<form action="'.$_SERVER["PHP_SELF"].'" method="POST" enctype="multipart/form-data">';
118 $out .= '<input type="hidden" name="token" value="'.newToken().'">';
119 $out .= '<input type="hidden" name="page_y" value="">';
120 $out .= '<input type="hidden" name="action" value="setModuleOptions">';
121 $out .= '<input type="hidden" name="param1" value="USER_ADDON_PDF_ODT_PATH">';
122 if ($odtChosen) {
123 $out .= '<input type="hidden" name="param2" value="USER_ADDON_PDF_ODT_DEFAULT">';
124 $out .= '<input type="hidden" name="param3" value="USER_ADDON_PDF_ODT_TOBILL">';
125 $out .= '<input type="hidden" name="param4" value="USER_ADDON_PDF_ODT_CLOSED">';
126 }
127 $out .= '<table class="nobordernopadding centpercent">';
128
129 // List of directories area
130 $out .= '<tr><td>';
131 $texttitle = $langs->trans("ListOfDirectories");
132 $listofdir = explode(',', preg_replace('/[\r\n]+/', ',', $odtPath));
133 $listoffiles = array();
134 foreach ($listofdir as $key => $tmpdir) {
135 $tmpdir = trim($tmpdir);
136 $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
137 if (!$tmpdir) {
138 unset($listofdir[$key]);
139 continue;
140 }
141 if (!is_dir($tmpdir)) {
142 $texttitle .= img_warning($langs->trans("ErrorDirNotFound", $tmpdir), '');
143 } else {
144 $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.(ods|odt)');
145 if (count($tmpfiles)) {
146 $listoffiles = array_merge($listoffiles, $tmpfiles);
147 }
148 }
149 }
150 $texthelp = $langs->trans("ListOfDirectoriesForModelGenODT");
151 $texthelp .= '<br><br><span class="opacitymedium">'.$langs->trans("ExampleOfDirectoriesForModelGen").'</span>';
152 // Add list of substitution keys
153 $texthelp .= '<br>'.$langs->trans("FollowingSubstitutionKeysCanBeUsed").'<br>';
154 $texthelp .= $langs->transnoentitiesnoconv("FullListOnOnlineDocumentation"); // This contains an url, we don't modify it
155
156 // Scan directories
157 if (count($listofdir)) {
158 $out .= '<span class="opacitylow">'.$langs->trans("NumberOfModelFilesFound").': <b>'.count($listoffiles).'</b></span><br>';
159
160 if ($odtChosen) {
161 // Model for creation
162 $list = ModelePDFUser::liste_modeles($this->db);
163 $out .= '<table width="50%;">';
164 $out .= '<tr>';
165 $out .= '<td width="60%;">'.$langs->trans("DefaultModelPropalCreate").'</td>';
166 $out .= '<td colspan="">';
167 $out .= $form->selectarray('value2', $list, getDolGlobalString('USER_ADDON_PDF_ODT_DEFAULT'));
168 $out .= "</td></tr>";
169
170 $out .= '<tr>';
171 $out .= '<td width="60%;">'.$langs->trans("DefaultModelPropalToBill").'</td>';
172 $out .= '<td colspan="">';
173 $out .= $form->selectarray('value3', $list, getDolGlobalString('USER_ADDON_PDF_ODT_TOBILL'));
174 $out .= "</td></tr>";
175 $out .= '<tr>';
176
177 $out .= '<td width="60%;">'.$langs->trans("DefaultModelPropalClosed").'</td>';
178 $out .= '<td colspan="">';
179 $out .= $form->selectarray('value4', $list, getDolGlobalString('USER_ADDON_PDF_ODT_CLOSED'));
180 $out .= "</td></tr>";
181 $out .= '</table>';
182 }
183 $out .= '<div id="div_'.get_class($this).'" class="hiddenx opacitylow">';
184 // Show list of found files
185 foreach ($listoffiles as $file) {
186 $filetooltip = dol_print_date(dol_filemtime($file['fullname']), 'dayhour', 'tzserver');
187 $out .= '- <span title="'.dolPrintHTMLForAttribute($filetooltip).'">'.$file['name'].'</span> <a href="'.dolBuildUrl(DOL_URL_ROOT.'/document.php', ['modulepart' => 'doctemplates', 'file' => 'users/'.basename($file['name'])]).'">'.img_picto('', 'listlight').'</a>';
188 $out .= ' &nbsp; <a class="reposition" href="'.dolBuildUrl($_SERVER["PHP_SELF"], ['modulepart' => 'doctemplates', 'keyforuploaddir' => 'USER_ADDON_PDF_ODT_PATH', 'action' => 'deletefile', 'file' => basename($file['name'])], true).'">'.img_picto('', 'delete').'</a>';
189 $out .= '<br>';
190 }
191 $out .= '</div>';
192 }
193
194 $out .= '<br>';
195 // Link to show/hide the area to manage directories of ODT models and template files
196 $out .= '<span class="classlink cursorpointer" onclick="javascript: jQuery(\'.div_odtmodelsof'.get_class($this).'\').toggle();">'.img_picto('', 'add').' '.$langs->trans("UploadNewTemplate").'...</span>';
197 $out .= '<div class="div_odtmodelsof'.get_class($this).'" style="display: none; margin-top: 6px;">';
198 $out .= $form->textwithpicto($texttitle, $texthelp, 1, 'help', '', 1, 3, $this->name);
199 $out .= '<div><div style="display: inline-block; min-width: 100px; vertical-align: middle;">';
200 $out .= '<textarea class="flat textareafordir" spellcheck="false" cols="60" name="value1">';
201 $out .= $odtPath;
202 $out .= '</textarea>';
203 $out .= '</div><div style="display: inline-block; vertical-align: middle;">';
204 $out .= '<input type="submit" class="button button-edit reposition smallpaddingimp" name="modify" value="'.dol_escape_htmltag($langs->trans("Modify")).'">';
205 $out .= '<br></div></div>';
206
207 // Add input to upload a new template file.
208 $out .= '<div>';
209 $maxfilesizearray = getMaxFileSizeArray();
210 $maxmin = $maxfilesizearray['maxmin'];
211 if ($maxmin > 0) {
212 $out .= '<input type="hidden" name="MAX_FILE_SIZE" value="'.($maxmin * 1024).'">'; // MAX_FILE_SIZE must precede the field type=file
213 }
214 $out .= ' <input type="file" name="uploadfile">';
215 $out .= '<input type="hidden" value="USER_ADDON_PDF_ODT_PATH" name="keyforuploaddir">';
216 $out .= '<input type="submit" class="button smallpaddingimp reposition" value="'.dol_escape_htmltag($langs->trans("Upload")).'" name="upload">';
217 $out .= '</div>';
218 $out .= '</div>';
219
220 $out .= '</td>';
221
222 $out .= '</tr>';
223
224 $out .= '</table>';
225 $out .= '</form>';
226
227 return $out;
228 }
229
230 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
242 public function write_file($object, $outputlangs, $srctemplatepath = '', $hidedetails = 0, $hidedesc = 0, $hideref = 0)
243 {
244 // phpcs:enable
245 global $langs, $conf, $mysoc, $hookmanager;
246
247 if (empty($srctemplatepath)) {
248 dol_syslog("doc_generic_odt::write_file parameter srctemplatepath empty", LOG_WARNING);
249 return -1;
250 }
251
252 // Add odtgeneration hook
253 if (!is_object($hookmanager)) {
254 include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
255 $hookmanager = new HookManager($this->db);
256 }
257 $hookmanager->initHooks(array('odtgeneration'));
258 global $action;
259
260 if (!is_object($outputlangs)) {
261 $outputlangs = $langs;
262 }
263 $sav_charset_output = $outputlangs->charset_output;
264 $outputlangs->charset_output = 'UTF-8';
265
266 // Load translation files required by the page
267 $outputlangs->loadLangs(array("main", "companies", "bills", "dict"));
268
269 if ($conf->user->dir_output) {
270 // If $object is id instead of object
271 if (!is_object($object)) {
272 $id = $object;
273 $object = new User($this->db);
274 $result = $object->fetch($id);
275 if ($result < 0) {
276 dol_print_error($this->db, $object->error);
277 return -1;
278 }
279 }
280
281 $object->fetch_thirdparty();
282
283 $dir = $conf->user->dir_output;
284 $objectref = dol_sanitizeFileName($object->ref);
285 if (!preg_match('/specimen/i', $objectref)) {
286 $dir .= "/".$objectref;
287 }
288 $file = $dir."/".$objectref.".odt";
289
290 if (!file_exists($dir)) {
291 if (dol_mkdir($dir) < 0) {
292 $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir);
293 return -1;
294 }
295 }
296
297 if (file_exists($dir)) {
298 //print "srctemplatepath=".$srctemplatepath; // Src filename
299 $newfile = basename($srctemplatepath);
300 $newfiletmp = preg_replace('/\.od[ts]/i', '', $newfile);
301 $newfiletmp = preg_replace('/template_/i', '', $newfiletmp);
302 $newfiletmp = preg_replace('/modele_/i', '', $newfiletmp);
303
304 $newfiletmp = $objectref . '_' . $newfiletmp;
305
306 // Get extension (ods or odt)
307 $newfileformat = substr($newfile, strrpos($newfile, '.') + 1);
308 if (getDolGlobalString('MAIN_DOC_USE_TIMING')) {
309 $format = getDolGlobalString('MAIN_DOC_USE_TIMING');
310 if ($format == '1') {
311 $format = '%Y%m%d%H%M%S';
312 }
313 $filename = $newfiletmp . '-' . dol_print_date(dol_now(), $format) . '.' . $newfileformat;
314 } else {
315 $filename = $newfiletmp . '.' . $newfileformat;
316 }
317 $file = $dir . '/' . $filename;
318 //print "newdir=".$dir;
319 //print "newfile=".$newfile;
320 //print "file=".$file;
321 //print "conf->user->dir_temp=".$conf->user->dir_temp;
322
323 dol_mkdir($conf->user->dir_temp);
324 if (!is_writable($conf->user->dir_temp)) {
325 $this->error = $langs->transnoentities("ErrorFailedToWriteInTempDirectory", $conf->user->dir_temp);
326 dol_syslog('Error in write_file: ' . $this->error, LOG_ERR);
327 return -1;
328 }
329
330 // If CUSTOMER contact defined on user, we use it
331 $usecontact = false;
332 $arrayidcontact = $object->getIdContact('external', 'CUSTOMER');
333 if (count($arrayidcontact) > 0) {
334 $usecontact = true;
335 $result = $object->fetch_contact($arrayidcontact[0]);
336 }
337
338 $contactobject = null;
339 // Recipient name
340 if (!empty($usecontact)) {
341 if ($object->contact->socid != $object->thirdparty->id && (!isset($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT) || getDolGlobalString('MAIN_USE_COMPANY_NAME_OF_CONTACT'))) {
342 $socobject = $object->contact;
343 } else {
344 $socobject = $object->thirdparty;
345 // if we have a CUSTOMER contact and we don't use it as recipient we store the contact object for later use
346 $contactobject = $object->contact;
347 }
348 } else {
349 $socobject = $object->thirdparty;
350 }
351
352 // Open and load template
353 require_once ODTPHP_PATH.'odf.php';
354 try {
355 $odfHandler = new Odf(
356 $srctemplatepath,
357 array(
358 'PATH_TO_TMP' => $conf->user->dir_temp,
359 'ZIP_PROXY' => getDolGlobalString('MAIN_ODF_ZIP_PROXY', 'PclZipProxy'), // PhpZipProxy or PclZipProxy. Got "bad compression method" error when using PhpZipProxy.
360 'DELIMITER_LEFT' => '{',
361 'DELIMITER_RIGHT' => '}'
362 )
363 );
364 } catch (Exception $e) {
365 $this->error = $e->getMessage();
366 dol_syslog($e->getMessage(), LOG_WARNING);
367 return -1;
368 }
369
370 // Make substitutions into odt
371 $array_user = $this->get_substitutionarray_user($object, $outputlangs);
372 $array_soc = $this->get_substitutionarray_mysoc($mysoc, $outputlangs);
373 $array_thirdparty = $this->get_substitutionarray_thirdparty($socobject, $outputlangs);
374 $array_other = $this->get_substitutionarray_other($outputlangs);
375 // retrieve contact information for use in object as contact_xxx tags
376 $array_thirdparty_contact = array();
377 if ($usecontact && is_object($contactobject)) {
378 $array_thirdparty_contact = $this->get_substitutionarray_contact($contactobject, $outputlangs, 'contact');
379 }
380
381 $tmparray = array_merge($array_user, $array_soc, $array_thirdparty, $array_other, $array_thirdparty_contact);
382 complete_substitutions_array($tmparray, $outputlangs, $object);
383 $object->fetch_optionals();
384 // Call the ODTSubstitution hook
385 $parameters = array('file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$tmparray);
386 $reshook = $hookmanager->executeHooks('ODTSubstitution', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
387
388 // retrieve the constant to apply a ratio for image size or set the ratio to 1
389 if (getDolGlobalString('MAIN_DOC_ODT_IMAGE_RATIO')) {
390 $ratio = (float) getDolGlobalString('MAIN_DOC_ODT_IMAGE_RATIO');
391 } else {
392 $ratio = 1;
393 }
394
395 foreach ($tmparray as $key => $value) {
396 try {
397 if (preg_match('/logo$/', $key)) { // Image
398 if (file_exists($value)) {
399 $odfHandler->setImage($key, $value, $ratio);
400 } else {
401 $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8');
402 }
403 } else { // Text
404 $odfHandler->setVars($key, $value, true, 'UTF-8');
405 }
406 } catch (OdfException $e) {
407 dol_syslog($e->getMessage(), LOG_WARNING);
408 }
409 }
410
411 // Replace labels translated
412 $tmparray = $outputlangs->get_translations_for_substitutions();
413 foreach ($tmparray as $key => $value) {
414 try {
415 $odfHandler->setVars($key, $value, true, 'UTF-8');
416 } catch (OdfException $e) {
417 dol_syslog($e->getMessage(), LOG_WARNING);
418 }
419 }
420
421 // Call the beforeODTSave hook
422 $parameters = array('odfHandler' => &$odfHandler, 'file' => $file, 'object' => $object, 'outputlangs' => $outputlangs);
423 $reshook = $hookmanager->executeHooks('beforeODTSave', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
424
425 // Write new file
426 if (getDolGlobalString('MAIN_ODT_AS_PDF')) {
427 try {
428 $odfHandler->exportAsAttachedPDF($file);
429 } catch (Exception $e) {
430 $this->error = $e->getMessage();
431 dol_syslog($e->getMessage(), LOG_WARNING);
432 return -1;
433 }
434 } else {
435 try {
436 $odfHandler->saveToDisk($file);
437 } catch (Exception $e) {
438 $this->error = $e->getMessage();
439 dol_syslog($e->getMessage(), LOG_WARNING);
440 return -1;
441 }
442 }
443
444 $reshook = $hookmanager->executeHooks('afterODTCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
445
446 dolChmod($file);
447
448 $odfHandler = null; // Destroy object
449
450 $this->result = array('fullpath' => $file);
451
452 return 1; // Success
453 } else {
454 $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir);
455 return -1;
456 }
457 }
458
459 return -1;
460 }
461
462 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
471 public function get_substitutionarray_object($object, $outputlangs, $array_key = 'object')
472 {
473 // phpcs:enable
474 if (!$object instanceof User) {
475 dol_syslog("Expected User object, got ".gettype($object), LOG_ERR);
476 return array();
477 }
478
479 $array_other = array();
480 foreach ($object as $key => $value) {
481 if (!is_array($value) && !is_object($value)) {
482 $array_other[$array_key.'_'.$key] = $value;
483 }
484 }
485
486 return $array_other;
487 }
488}
$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 to manage intervention document templates.
static liste_modeles($db, $maxfilenamelength=0)
Return list of active generation modules.
Class to manage Dolibarr users.
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_filemtime($pathoffile)
Return time of a file.
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.
dolBuildUrl($url, $params=[], $addtoken=false, $anchor='')
Return path of url.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
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