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';
45 public $version =
'dolibarr';
58 $langs->loadLangs(array(
"main",
"companies"));
61 $this->
name =
"ODT templates";
62 $this->
description = $langs->trans(
"DocumentModelOdt");
63 $this->scandir =
'USER_ADDON_PDF_ODT_PATH';
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;
75 $this->option_logo = 1;
76 $this->option_tva = 0;
77 $this->option_modereg = 0;
78 $this->option_condreg = 0;
79 $this->option_multilang = 1;
80 $this->option_escompte = 0;
81 $this->option_credit_note = 0;
82 $this->option_freetext = 1;
83 $this->option_draft_watermark = 0;
92 if (!$this->emetteur->country_code) {
93 $this->emetteur->country_code = substr($langs->defaultlang, -2);
109 $langs->loadLangs(array(
'companies',
'errors'));
111 $form =
new Form($this->db);
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">';
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">';
127 $out .=
'<table class="nobordernopadding centpercent">';
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);
138 unset($listofdir[$key]);
141 if (!is_dir($tmpdir)) {
142 $texttitle .= img_warning($langs->trans(
"ErrorDirNotFound", $tmpdir),
'');
144 $tmpfiles =
dol_dir_list($tmpdir,
'files', 0,
'\.(ods|odt)');
145 if (count($tmpfiles)) {
146 $listoffiles = array_merge($listoffiles, $tmpfiles);
150 $texthelp = $langs->trans(
"ListOfDirectoriesForModelGenODT");
151 $texthelp .=
'<br><br><span class="opacitymedium">'.$langs->trans(
"ExampleOfDirectoriesForModelGen").
'</span>';
153 $texthelp .=
'<br>'.$langs->trans(
"FollowingSubstitutionKeysCanBeUsed").
'<br>';
154 $texthelp .= $langs->transnoentitiesnoconv(
"FullListOnOnlineDocumentation");
157 if (count($listofdir)) {
158 $out .=
'<span class="opacitylow">'.$langs->trans(
"NumberOfModelFilesFound").
': <b>'.count($listoffiles).
'</b></span><br>';
163 $out .=
'<table width="50%;">';
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>";
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>";
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>";
183 $out .=
'<div id="div_'.get_class($this).
'" class="hiddenx opacitylow">';
185 foreach ($listoffiles as $file) {
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 .=
' <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>';
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
">';
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>';
207 // Add input to upload a new template file.
209 $maxfilesizearray = getMaxFileSizeArray();
210 $maxmin = $maxfilesizearray['maxmin'];
212 $out .= '<input type="hidden
" name="MAX_FILE_SIZE
" value="'.($maxmin * 1024).'">'; // MAX_FILE_SIZE must precede the field type=file
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
">';
230 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
242 public function write_file($object, $outputlangs, $srctemplatepath = '', $hidedetails = 0, $hidedesc = 0, $hideref = 0)
245 global $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 User($this->db);
274 $result = $object->fetch($id);
276 dol_print_error($this->db, $object->error);
281 $object->fetch_thirdparty();
283 $dir = $conf->user->dir_output;
284 $objectref = dol_sanitizeFileName($object->ref);
285 if (!preg_match('/specimen/i', $objectref)) {
286 $dir .= "/
".$objectref;
288 $file = $dir."/
".$objectref.".odt
";
290 if (!file_exists($dir)) {
291 if (dol_mkdir($dir) < 0) {
292 $this->error = $langs->transnoentities("ErrorCanNotCreateDir
", $dir);
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);
304 $newfiletmp = $objectref . '_' . $newfiletmp;
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';
313 $filename = $newfiletmp . '-' . dol_print_date(dol_now(), $format) . '.' . $newfileformat;
315 $filename = $newfiletmp . '.' . $newfileformat;
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;
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);
330 // If CUSTOMER contact defined on user, we use it
332 $arrayidcontact = $object->getIdContact('external', 'CUSTOMER');
333 if (count($arrayidcontact) > 0) {
335 $result = $object->fetch_contact($arrayidcontact[0]);
338 $contactobject = null;
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;
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;
349 $socobject = $object->thirdparty;
352 // Open and load template
353 require_once ODTPHP_PATH.'odf.php';
355 $odfHandler = new Odf(
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' => '}'
364 } catch (Exception $e) {
365 $this->error = $e->getMessage();
366 dol_syslog($e->getMessage(), LOG_WARNING);
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');
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
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');
395 foreach ($tmparray as $key => $value) {
397 if (preg_match('/logo$/', $key)) { // Image
398 if (file_exists($value)) {
399 $odfHandler->setImage($key, $value, $ratio);
401 $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8');
404 $odfHandler->setVars($key, $value, true, 'UTF-8');
406 } catch (OdfException $e) {
407 dol_syslog($e->getMessage(), LOG_WARNING);
411 // Replace labels translated
412 $tmparray = $outputlangs->get_translations_for_substitutions();
413 foreach ($tmparray as $key => $value) {
415 $odfHandler->setVars($key, $value, true, 'UTF-8');
416 } catch (OdfException $e) {
417 dol_syslog($e->getMessage(), LOG_WARNING);
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
426 if (getDolGlobalString('MAIN_ODT_AS_PDF')) {
428 $odfHandler->exportAsAttachedPDF($file);
429 } catch (Exception $e) {
430 $this->error = $e->getMessage();
431 dol_syslog($e->getMessage(), LOG_WARNING);
436 $odfHandler->saveToDisk($file);
437 } catch (Exception $e) {
438 $this->error = $e->getMessage();
439 dol_syslog($e->getMessage(), LOG_WARNING);
444 $reshook = $hookmanager->executeHooks('afterODTCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
448 $odfHandler = null; // Destroy object
450 $this->result = array('fullpath' => $file);
454 $this->error = $langs->transnoentities("ErrorCanNotCreateDir
", $dir);
462 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
471 public function get_substitutionarray_object($object, $outputlangs, $array_key = 'object')
474 if (!$object instanceof User) {
475 dol_syslog("Expected
User object, got
".gettype($object), LOG_ERR);
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;
$propal type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
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.
__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_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.
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)
$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