28require_once DOL_DOCUMENT_ROOT.
'/core/modules/usergroup/modules_usergroup.class.php';
29require_once DOL_DOCUMENT_ROOT.
'/user/class/user.class.php';
30require_once DOL_DOCUMENT_ROOT.
'/user/class/usergroup.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';
46 public $version =
'dolibarr';
59 $langs->loadLangs(array(
"main",
"companies"));
62 $this->
name =
"ODT templates";
63 $this->
description = $langs->trans(
"DocumentModelOdt");
64 $this->scandir =
'USERGROUP_ADDON_PDF_ODT_PATH';
68 $this->page_largeur = 0;
69 $this->page_hauteur = 0;
70 $this->format = array($this->page_largeur, $this->page_hauteur);
71 $this->marge_gauche = 0;
72 $this->marge_droite = 0;
73 $this->marge_haute = 0;
74 $this->marge_basse = 0;
76 $this->option_logo = 1;
77 $this->option_tva = 0;
78 $this->option_modereg = 0;
79 $this->option_condreg = 0;
80 $this->option_multilang = 1;
81 $this->option_escompte = 0;
82 $this->option_credit_note = 0;
83 $this->option_freetext = 1;
84 $this->option_draft_watermark = 0;
93 if (!$this->emetteur->country_code) {
94 $this->emetteur->country_code = substr($langs->defaultlang, -2);
107 global
$conf, $langs;
110 $langs->loadLangs(array(
"errors",
"companies"));
112 $form =
new Form($this->db);
118 $texte .=
'<form action="'.$_SERVER[
"PHP_SELF"].
'" method="POST" enctype="multipart/form-data">';
119 $texte .=
'<input type="hidden" name="token" value="'.newToken().
'">';
120 $texte .=
'<input type="hidden" name="page_y" value="">';
121 $texte .=
'<input type="hidden" name="action" value="setModuleOptions">';
122 $texte .=
'<input type="hidden" name="param1" value="USERGROUP_ADDON_PDF_ODT_PATH">';
124 $texte .=
'<input type="hidden" name="param2" value="USERGROUP_ADDON_PDF_ODT_DEFAULT">';
125 $texte .=
'<input type="hidden" name="param3" value="USERGROUP_ADDON_PDF_ODT_TOBILL">';
126 $texte .=
'<input type="hidden" name="param4" value="USERGROUP_ADDON_PDF_ODT_CLOSED">';
128 $texte .=
'<table class="nobordernopadding" width="100%">';
131 $texte .=
'<tr><td>';
132 $texttitle = $langs->trans(
"ListOfDirectories");
133 $listofdir = explode(
',', preg_replace(
'/[\r\n]+/',
',', $odtPath));
134 $listoffiles = array();
135 foreach ($listofdir as $key => $tmpdir) {
136 $tmpdir = trim($tmpdir);
137 $tmpdir = preg_replace(
'/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
139 unset($listofdir[$key]);
142 if (!is_dir($tmpdir)) {
143 $texttitle .= img_warning($langs->trans(
"ErrorDirNotFound", $tmpdir),
'');
145 $tmpfiles =
dol_dir_list($tmpdir,
'files', 0,
'\.(ods|odt)');
146 if (count($tmpfiles)) {
147 $listoffiles = array_merge($listoffiles, $tmpfiles);
151 $texthelp = $langs->trans(
"ListOfDirectoriesForModelGenODT");
152 $texthelp .=
'<br><br><span class="opacitymedium">'.$langs->trans(
"ExampleOfDirectoriesForModelGen").
'</span>';
154 $texthelp .=
'<br>'.$langs->trans(
"FollowingSubstitutionKeysCanBeUsed").
'<br>';
155 $texthelp .= $langs->transnoentitiesnoconv(
"FullListOnOnlineDocumentation");
158 if (count($listofdir)) {
159 $texte .=
'<span class="opacitylow">'.$langs->trans(
"NumberOfModelFilesFound").
': <b>'.count($listoffiles).
'</b></span><br>';
164 $texte .=
'<table width="50%;">';
166 $texte .=
'<td width="60%;">'.$langs->trans(
"DefaultModelPropalCreate").
'</td>';
167 $texte .=
'<td colspan="">';
168 $texte .= $form->selectarray(
'value2', $list,
getDolGlobalString(
'USERGROUP_ADDON_PDF_ODT_DEFAULT'));
169 $texte .=
"</td></tr>";
172 $texte .=
'<td width="60%;">'.$langs->trans(
"DefaultModelPropalToBill").
'</td>';
173 $texte .=
'<td colspan="">';
174 $texte .= $form->selectarray(
'value3', $list,
getDolGlobalString(
'USERGROUP_ADDON_PDF_ODT_TOBILL'));
175 $texte .=
"</td></tr>";
178 $texte .=
'<td width="60%;">'.$langs->trans(
"DefaultModelPropalClosed").
'</td>';
179 $texte .=
'<td colspan="">';
180 $texte .= $form->selectarray(
'value4', $list,
getDolGlobalString(
'USERGROUP_ADDON_PDF_ODT_CLOSED'));
181 $texte .=
"</td></tr>";
182 $texte .=
'</table>';
184 $texte .=
'<div id="div_'.get_class($this).
'" class="hiddenx opacitylow">';
186 foreach ($listoffiles as $file) {
187 $texte .=
'- '.$file[
'name'].
' <a href="'.DOL_URL_ROOT.
'/document.php?modulepart=doctemplates&file=usergroups/'.urlencode(basename($file[
'name'])).
'">'.img_picto(
'',
'listlight').
'</a>';
188 $texte .=
' <a class="reposition" href="'.$_SERVER[
"PHP_SELF"].
'?modulepart=doctemplates&keyforuploaddir=USERGROUP_ADDON_PDF_ODT_PATH&action=deletefile&token='.
newToken().
'&file='.urlencode(basename($file[
'name'])).
'">'.img_picto(
'',
'delete').
'</a>';
196 $texte .=
'<span class="classlink cursorpointer" onclick="javascript: jQuery(\'.div_odtmodelsof'.get_class($this).
'\').toggle();
">'.img_picto('', 'add').' '.$langs->trans("UploadNewTemplate
").'...</span>';
197 $texte .= '<div class="div_odtmodelsof
'.get_class($this).'" style="display: none; margin-top: 6px;
">';
198 $texte .= $form->textwithpicto($texttitle, $texthelp, 1, 'help', '', 1, 3, $this->name);
199 $texte .= '<div><div style="display:
inline-block; min-width: 100px; vertical-align: middle;
">';
200 $texte .= '<textarea class="flat textareafordir
" spellcheck="false" cols="60
" name="value1
">';
202 $texte .= '</textarea>';
203 $texte .= '</div><div style="display:
inline-block; vertical-align: middle;
">';
204 $texte .= '<input type="submit
" class="button button-edit reposition smallpaddingimp
" name="modify
" value="'.dol_escape_htmltag($langs->trans("Modify")).'">';
205 $texte .= '<br></div></div>';
207 // Add input to upload a new template file.
209 $maxfilesizearray = getMaxFileSizeArray();
210 $maxmin = $maxfilesizearray['maxmin'];
212 $texte .= '<input type="hidden
" name="MAX_FILE_SIZE
" value="'.($maxmin * 1024).'">'; // MAX_FILE_SIZE must precede the field type=file
214 $texte .= ' <input type="file
" name="uploadfile
">';
215 $texte .= '<input type="hidden
" value="USERGROUP_ADDON_PDF_ODT_PATH
" name="keyforuploaddir
">';
216 $texte .= '<input type="submit
" class="button smallpaddingimp reposition
" value="'.dol_escape_htmltag($langs->trans("Upload")).'" name="upload
">';
224 $texte .= '</table>';
230 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
242 public function write_file($object, $outputlangs, $srctemplatepath = '', $hidedetails = 0, $hidedesc = 0, $hideref = 0)
245 global $user, $langs, $conf, $mysoc, $hookmanager;
247 if (empty($srctemplatepath)) {
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);
257 $hookmanager->initHooks(array('odtgeneration'));
260 if (!is_object($outputlangs)) {
261 $outputlangs = $langs;
263 $sav_charset_output = $outputlangs->charset_output;
264 $outputlangs->charset_output = 'UTF-8';
266 // Load translation files required by the page
267 $outputlangs->loadLangs(array("main
", "companies
", "bills
", "dict
"));
269 if ($conf->user->dir_output) {
270 // If $object is id instead of object
271 if (!is_object($object)) {
273 $object = new UserGroup($this->db);
274 $result = $object->fetch($id);
276 dol_print_error($this->db, $object->error);
281 $dir = $conf->user->dir_output.'/usergroups';
282 $objectref = dol_sanitizeFileName($object->ref);
283 if (!preg_match('/specimen/i', $objectref)) {
284 $dir .= "/
".$objectref;
286 $file = $dir."/
".$objectref.".odt
";
288 if (!file_exists($dir)) {
289 if (dol_mkdir($dir) < 0) {
290 $this->error = $langs->transnoentities("ErrorCanNotCreateDir
", $dir);
295 if (file_exists($dir)) {
296 //print "srctemplatepath=
".$srctemplatepath; // Src filename
297 $newfile = basename($srctemplatepath);
298 $newfiletmp = preg_replace('/\.od[ts]/i', '', $newfile);
299 $newfiletmp = preg_replace('/template_/i', '', $newfiletmp);
300 $newfiletmp = preg_replace('/modele_/i', '', $newfiletmp);
302 $newfiletmp = $objectref . '_' . $newfiletmp;
304 // Get extension (ods or odt)
305 $newfileformat = substr($newfile, strrpos($newfile, '.') + 1);
306 if (getDolGlobalString('MAIN_DOC_USE_TIMING')) {
307 $format = getDolGlobalString('MAIN_DOC_USE_TIMING');
308 if ($format == '1') {
309 $format = '%Y%m%d%H%M%S';
311 $filename = $newfiletmp . '-' . dol_print_date(dol_now(), $format) . '.' . $newfileformat;
313 $filename = $newfiletmp . '.' . $newfileformat;
315 $file = $dir . '/' . $filename;
316 //print "newdir=
".$dir;
317 //print "newfile=
".$newfile;
318 //print "file=
".$file;
319 //print "conf->user->dir_temp=
".$conf->user->dir_temp;
321 dol_mkdir($conf->user->dir_temp);
322 if (!is_writable($conf->user->dir_temp)) {
323 $this->error = $langs->transnoentities("ErrorFailedToWriteInTempDirectory
", $conf->user->dir_temp);
324 dol_syslog('Error in write_file: ' . $this->error, LOG_ERR);
328 // If CUSTOMER contact defined on user, we use it
330 $arrayidcontact = $object->getIdContact('external', 'CUSTOMER');
331 if (count($arrayidcontact) > 0) {
333 $result = $object->fetch_contact($arrayidcontact[0]);
336 $contactobject = null;
338 if (!empty($usecontact)) {
339 // We can use the company of contact instead of thirdparty company
340 if ($object->contact->socid != $object->thirdparty->id && (!isset($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT) || getDolGlobalString('MAIN_USE_COMPANY_NAME_OF_CONTACT'))) {
341 $object->contact->fetch_thirdparty();
342 $socobject = $object->contact->thirdparty;
343 $contactobject = $object->contact;
345 $socobject = $object->thirdparty;
346 // if we have a CUSTOMER contact and we don't use it as thirdparty recipient we store the contact object for later use
347 $contactobject = $object->contact;
350 $socobject = $object->thirdparty;
353 $substitutionarray = array(
354 '__FROM_NAME__' => $this->emetteur->name,
355 '__FROM_EMAIL__' => $this->emetteur->email,
356 '__TOTAL_TTC__' => $object->total_ttc,
357 '__TOTAL_HT__' => $object->total_ht,
358 '__TOTAL_VAT__' => $object->total_tva
360 complete_substitutions_array($substitutionarray, $langs, $object);
361 // Call the ODTSubstitution hook
362 $parameters = array('file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$substitutionarray);
363 $reshook = $hookmanager->executeHooks('ODTSubstitution', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
367 $paramfreetext = 'user_FREE_TEXT';
368 if (getDolGlobalString($paramfreetext)) {
369 $newfreetext = make_substitutions(getDolGlobalString($paramfreetext), $substitutionarray);
372 // Open and load template
373 require_once ODTPHP_PATH.'odf.php';
375 $odfHandler = new Odf(
378 'PATH_TO_TMP' => $conf->user->dir_temp,
379 'ZIP_PROXY' => getDolGlobalString('MAIN_ODF_ZIP_PROXY', 'PclZipProxy'), // PhpZipProxy or PclZipProxy. Got "bad compression method
" error when using PhpZipProxy.
380 'DELIMITER_LEFT' => '{',
381 'DELIMITER_RIGHT' => '}'
384 } catch (Exception $e) {
385 $this->error = $e->getMessage();
386 dol_syslog($e->getMessage(), LOG_WARNING);
389 // After construction $odfHandler->contentXml contains content and
390 // [!-- BEGIN row.lines --]*[!-- END row.lines --] has been replaced by
391 // [!-- BEGIN lines --]*[!-- END lines --]
392 //print html_entity_decode($odfHandler->__toString());
396 // Make substitutions into odt of freetext
398 $odfHandler->setVars('free_text', $newfreetext, true, 'UTF-8');
399 } catch (OdfException $e) {
400 dol_syslog($e->getMessage(), LOG_WARNING);
403 // Make substitutions into odt
404 $array_user = $this->get_substitutionarray_user($user, $outputlangs);
405 $array_global = $this->get_substitutionarray_each_var_object($object, $outputlangs);
406 $array_soc = $this->get_substitutionarray_mysoc($mysoc, $outputlangs);
407 $array_thirdparty = $this->get_substitutionarray_thirdparty($socobject, $outputlangs);
408 $array_objet = $this->get_substitutionarray_each_var_object($object, $outputlangs);
409 $array_other = $this->get_substitutionarray_other($outputlangs);
410 // retrieve contact information for use in object as contact_xxx tags
411 $array_thirdparty_contact = array();
412 if ($usecontact && is_object($contactobject)) {
413 $array_thirdparty_contact = $this->get_substitutionarray_contact($contactobject, $outputlangs, 'contact');
416 $tmparray = array_merge($array_global, $array_user, $array_soc, $array_thirdparty, $array_objet, $array_other, $array_thirdparty_contact);
417 complete_substitutions_array($tmparray, $outputlangs, $object);
418 $object->fetch_optionals();
419 // Call the ODTSubstitution hook
420 $parameters = array('file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$tmparray);
421 $reshook = $hookmanager->executeHooks('ODTSubstitution', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
423 // retrieve the constant to apply a ratio for image size or set the ratio to 1
424 if (getDolGlobalString('MAIN_DOC_ODT_IMAGE_RATIO')) {
425 $ratio = (float) getDolGlobalString('MAIN_DOC_ODT_IMAGE_RATIO');
430 foreach ($tmparray as $key => $value) {
432 if (preg_match('/logo$/', $key)) { // Image
433 if (file_exists($value)) {
434 $odfHandler->setImage($key, $value, $ratio);
436 $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8');
439 $odfHandler->setVars($key, $value, true, 'UTF-8');
441 } catch (OdfException $e) {
442 dol_syslog($e->getMessage(), LOG_WARNING);
445 // Replace tags of lines
446 $foundtagforlines = 1;
448 $listlines = $odfHandler->setSegment('lines');
449 } catch (OdfExceptionSegmentNotFound $e) {
450 // We may arrive here if tags for lines not present into template
451 $foundtagforlines = 0;
452 dol_syslog($e->getMessage(), LOG_INFO);
454 if ($foundtagforlines) {
455 foreach ($object->members as $u) {
456 $tmparray = $this->get_substitutionarray_each_var_object($u, $outputlangs);
457 unset($tmparray['object_pass']);
458 unset($tmparray['object_pass_indatabase']);
459 complete_substitutions_array($tmparray, $outputlangs, $object, $user, "completesubstitutionarray_users
");
460 // Call the ODTSubstitutionLine hook
461 $parameters = array('odfHandler' => &$odfHandler, 'file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$tmparray, 'line' => $u);
462 $reshook = $hookmanager->executeHooks('ODTSubstitutionLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
463 foreach ($tmparray as $key => $val) {
465 if (!is_array($val)) { // @phpstan-ignore-line
466 $listlines->setVars($key, $val, true, 'UTF-8');
468 } catch (SegmentException $e) {
469 dol_syslog($e->getMessage(), LOG_WARNING);
475 $odfHandler->mergeSegment($listlines);
476 } catch (OdfException $e) {
477 $this->error = $e->getMessage();
478 dol_syslog($this->error, LOG_WARNING);
483 // Replace labels translated
484 $tmparray = $outputlangs->get_translations_for_substitutions();
485 foreach ($tmparray as $key => $value) {
487 $odfHandler->setVars($key, $value, true, 'UTF-8');
488 } catch (OdfException $e) {
489 dol_syslog($e->getMessage(), LOG_WARNING);
493 // Call the beforeODTSave hook
494 $parameters = array('odfHandler' => &$odfHandler, 'file' => $file, 'object' => $object, 'outputlangs' => $outputlangs);
495 $reshook = $hookmanager->executeHooks('beforeODTSave', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
498 if (getDolGlobalString('MAIN_ODT_AS_PDF')) {
500 $odfHandler->exportAsAttachedPDF($file);
501 } catch (Exception $e) {
502 $this->error = $e->getMessage();
503 dol_syslog($e->getMessage(), LOG_WARNING);
508 $odfHandler->saveToDisk($file);
509 } catch (Exception $e) {
510 $this->error = $e->getMessage();
511 dol_syslog($e->getMessage(), LOG_WARNING);
516 $reshook = $hookmanager->executeHooks('afterODTCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
520 $odfHandler = null; // Destroy object
522 $this->result = array('fullpath' => $file);
526 $this->error = $langs->transnoentities("ErrorCanNotCreateDir
", $dir);
$propal type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Parent class to manage intervention document templates.
static liste_modeles($db, $maxfilenamelength=0)
Return list of active generation modules.
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.
__construct($db)
Constructor.
info($langs)
Return description of a module.
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.
getCallerInfoString()
Get caller info as a string that can be appended to a log message.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
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)
$conf db name
Only used if Module[ID]Name translation string is not found.
multi select button
0 = Do not include form tag and submit button -1 = Do not include form tag but include submit button