31require_once DOL_DOCUMENT_ROOT.
'/core/modules/facture/modules_facture.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';
48 public $version =
'dolibarr';
53 public $position = 70;
66 $langs->loadLangs(array(
"main",
"companies"));
69 $this->
name =
"ODT/ODS templates";
70 $this->
description = $langs->trans(
"DocumentModelOdt");
71 $this->update_main_doc_field = 1;
72 $this->scandir =
'FACTURE_ADDON_PDF_ODT_PATH';
76 $this->page_largeur = 0;
77 $this->page_hauteur = 0;
78 $this->format = array($this->page_largeur, $this->page_hauteur);
79 $this->marge_gauche = 0;
80 $this->marge_droite = 0;
81 $this->marge_haute = 0;
82 $this->marge_basse = 0;
84 $this->option_logo = 1;
85 $this->option_tva = 0;
86 $this->option_modereg = 1;
87 $this->option_condreg = 1;
88 $this->option_multilang = 1;
89 $this->option_escompte = 0;
90 $this->option_credit_note = 0;
91 $this->option_freetext = 1;
92 $this->option_draft_watermark = 0;
101 if (!$this->emetteur->country_code) {
102 $this->emetteur->country_code = substr($langs->defaultlang, -2);
115 global
$conf, $langs;
118 $langs->loadLangs(array(
"errors",
"companies"));
120 $form =
new Form($this->db);
123 $texte .=
'<form action="'.$_SERVER[
"PHP_SELF"].
'" method="POST" enctype="multipart/form-data">';
124 $texte .=
'<input type="hidden" name="token" value="'.newToken().
'">';
125 $texte .=
'<input type="hidden" name="page_y" value="">';
126 $texte .=
'<input type="hidden" name="action" value="setModuleOptions">';
127 $texte .=
'<input type="hidden" name="param1" value="FACTURE_ADDON_PDF_ODT_PATH">';
128 $texte .=
'<table class="nobordernopadding" width="100%">';
131 $texte .=
'<tr><td valign="middle">';
132 $texttitle = $langs->trans(
"ListOfDirectories");
133 $listofdir = explode(
',', preg_replace(
'/[\r\n]+/',
',', trim(
$conf->global->FACTURE_ADDON_PDF_ODT_PATH)));
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 $nbofiles = count($listoffiles);
160 $texte .=
'<span class="opacitylow">'.$langs->trans(
"NumberOfModelFilesFound").
': <b>';
162 $texte .= count($listoffiles);
164 $texte .=
'</b></span><br>';
167 $texte .=
'<div id="div_'.get_class($this).
'" class="hiddenx opacitylow">';
169 foreach ($listoffiles as $file) {
170 $texte .=
'- '.$file[
'name'].
' <a href="'.DOL_URL_ROOT.
'/document.php?modulepart=doctemplates&file=invoices/'.urlencode(basename($file[
'name'])).
'">'.img_picto(
'',
'listlight').
'</a>';
171 $texte .=
' <a class="reposition" href="'.$_SERVER[
"PHP_SELF"].
'?modulepart=doctemplates&keyforuploaddir=FACTURE_ADDON_PDF_ODT_PATH&action=deletefile&token='.
newToken().
'&file='.urlencode(basename($file[
'name'])).
'">'.img_picto(
'',
'delete').
'</a>';
178 $texte .=
'<span class="classlink cursorpointer" onclick="javascript: jQuery(\'.div_odtmodelsof'.get_class($this).
'\').toggle();
">'.img_picto('', 'add').' '.$langs->trans("UploadNewTemplate
").'...</span>';
179 $texte .= '<div class="div_odtmodelsof
'.get_class($this).'" style="display: none; margin-top: 6px;
">';
180 $texte .= $form->textwithpicto($texttitle, $texthelp, 1, 'help', '', 1, 3, $this->name);
181 $texte .= '<div><div style="display:
inline-block; min-width: 100px; vertical-align: middle;
">';
182 $texte .= '<textarea class="flat textareafordir
" spellcheck="false" cols="60
" name="value1
">';
183 $texte .= getDolGlobalString('FACTURE_ADDON_PDF_ODT_PATH');
184 $texte .= '</textarea>';
185 $texte .= '</div><div style="display:
inline-block; vertical-align: middle;
">';
186 $texte .= '<input type="submit
" class="button button-edit reposition smallpaddingimp
" name="modify
" value="'.dol_escape_htmltag($langs->trans("Modify")).'">';
187 $texte .= '<br></div></div>';
190 // Add input to upload a new template file.
191 $texte .= '<div class="div_odtmodelsof
'.get_class($this).'" style="display: none;
">';
192 $maxfilesizearray = getMaxFileSizeArray();
193 $maxmin = $maxfilesizearray['maxmin'];
195 $texte .= '<input type="hidden
" name="MAX_FILE_SIZE
" value="'.($maxmin * 1024).'">'; // MAX_FILE_SIZE must precede the field type=file
197 $texte .= ' <input type="file
" name="uploadfile
">';
198 $texte .= '<input type="hidden
" value="FACTURE_ADDON_PDF_ODT_PATH
" name="keyforuploaddir
">';
199 $texte .= '<input type="submit
" class="button smallpaddingimp reposition
" value="'.dol_escape_htmltag($langs->trans("Upload")).'" name="upload
">';
205 $texte .= '</table>';
211 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
223 public function write_file($object, $outputlangs, $srctemplatepath = '', $hidedetails = 0, $hidedesc = 0, $hideref = 0)
226 global $user, $langs, $conf, $mysoc, $hookmanager;
228 if (empty($srctemplatepath)) {
233 // Add odtgeneration hook
234 if (!is_object($hookmanager)) {
235 include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
236 $hookmanager = new HookManager($this->db);
238 $hookmanager->initHooks(array('odtgeneration'));
241 if (!is_object($outputlangs)) {
242 $outputlangs = $langs;
244 $sav_charset_output = $outputlangs->charset_output;
245 $outputlangs->charset_output = 'UTF-8';
247 // Load translation files required by the page
248 $outputlangs->loadLangs(array("main
", "dict
", "companies
", "bills
"));
250 if ($conf->facture->dir_output) {
251 // If $object is id instead of object
252 if (!is_object($object)) {
254 $object = new Facture($this->db);
255 $result = $object->fetch($id);
257 dol_print_error($this->db, $object->error);
262 $object->fetch_thirdparty();
264 $dir = empty($conf->facture->multidir_output[$object->entity ?? $conf->entity]) ? $conf->facture->dir_output : $conf->facture->multidir_output[$object->entity ?? $conf->entity];
265 $objectref = dol_sanitizeFileName($object->ref);
266 if (!preg_match('/specimen/i', $objectref)) {
267 $dir .= "/
".$objectref;
269 $file = $dir."/
".$objectref.".odt
";
271 if (!file_exists($dir)) {
272 if (dol_mkdir($dir) < 0) {
273 $this->error = $langs->transnoentities("ErrorCanNotCreateDir
", $dir);
278 if (file_exists($dir)) {
279 //print "srctemplatepath=
".$srctemplatepath; // Src filename
280 $newfile = basename($srctemplatepath);
281 $newfiletmp = preg_replace('/\.od[ts]/i', '', $newfile);
282 $newfiletmp = preg_replace('/template_/i', '', $newfiletmp);
283 $newfiletmp = preg_replace('/modele_/i', '', $newfiletmp);
285 if (getDolGlobalString('MAIN_ODT_AS_PDF_OMIT_TEMPLATE_NAME')) {
286 $newfiletmp = $objectref;
288 $newfiletmp = $objectref . '_' . $newfiletmp;
291 // Get extension (ods or odt)
292 $newfileformat = substr($newfile, strrpos($newfile, '.') + 1);
293 if (getDolGlobalString('MAIN_DOC_USE_TIMING')) {
294 $format = getDolGlobalString('MAIN_DOC_USE_TIMING');
295 if ($format == '1') {
296 $format = '%Y%m%d%H%M%S';
298 $filename = $newfiletmp . '-' . dol_print_date(dol_now(), $format) . '.' . $newfileformat;
300 $filename = $newfiletmp . '.' . $newfileformat;
302 $file = $dir . '/' . $filename;
303 //$file=$dir.'/'.$newfiletmp.'.'.dol_print_date(dol_now(),'%Y%m%d%H%M%S').'.odt';
304 //print "newdir=
".$dir;
305 //print "newfile=
".$newfile;
306 //print "file=
".$file;
307 //print "conf->societe->dir_temp=
".$conf->societe->dir_temp;
309 dol_mkdir($conf->facture->dir_temp);
310 if (!is_writable($conf->facture->dir_temp)) {
311 $this->error = $langs->transnoentities("ErrorFailedToWriteInTempDirectory
", $conf->facture->dir_temp);
312 dol_syslog('Error in write_file: ' . $this->error, LOG_ERR);
316 // If BILLING contact defined on invoice, we use it
318 $arrayidcontact = $object->getIdContact('external', 'BILLING');
319 if (count($arrayidcontact) > 0) {
321 $result = $object->fetch_contact($arrayidcontact[0]);
325 $contactobject = null;
326 if (!empty($usecontact)) {
327 // We can use the company of contact instead of thirdparty company
328 if ($object->contact->socid != $object->thirdparty->id && (!isset($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT) || getDolGlobalString('MAIN_USE_COMPANY_NAME_OF_CONTACT'))) {
329 $object->contact->fetch_thirdparty();
330 $socobject = $object->contact->thirdparty;
331 $contactobject = $object->contact;
333 $socobject = $object->thirdparty;
334 // if we have a BILLING contact and we don't use it as thirdparty recipient we store the contact object for later use
335 $contactobject = $object->contact;
338 $socobject = $object->thirdparty;
341 // Fetch info for linked propal
342 $object->fetchObjectLinked(0, '', null, '');
343 //print_r($object->linkedObjects['propal']); exit;
345 $propal_object = null;
346 if (!empty($object->linkedObjects['propal'])) {
347 $array_propal_object = $object->linkedObjects['propal'];
348 if (is_array($array_propal_object) && count($array_propal_object) > 0) {
349 $tmparrayofvalue = array_values($array_propal_object);
350 $propal_object = $tmparrayofvalue[0];
354 // and determine category of operation
355 $categoryOfOperation = 0;
358 foreach ($object->lines as $line) {
359 // If DEPOSIT, this line is completely ignored for calculations.
360 if ($line->isDepositLine()) {
364 // determine category of operation
365 if ($categoryOfOperation < 2) {
366 $lineProductType = $line->product_type;
367 if ($lineProductType == Product::TYPE_PRODUCT) {
369 } elseif ($lineProductType == Product::TYPE_SERVICE) {
372 if ($nbProduct > 0 && $nbService > 0) {
373 // mixed products and services
374 $categoryOfOperation = 2;
379 // determine category of operation
380 if ($categoryOfOperation <= 0) {
382 if ($nbProduct == 0 && $nbService > 0) {
383 $categoryOfOperation = 1;
388 $substitutionarray = array(
389 '__FROM_NAME__' => $this->emetteur->name,
390 '__FROM_EMAIL__' => $this->emetteur->email,
391 '__TOTAL_TTC__' => $object->total_ttc,
392 '__TOTAL_HT__' => $object->total_ht,
393 '__TOTAL_VAT__' => $object->total_tva
395 complete_substitutions_array($substitutionarray, $langs, $object);
396 // Call the ODTSubstitution hook
397 $parameters = array('file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$substitutionarray);
398 $reshook = $hookmanager->executeHooks('ODTSubstitution', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
402 $paramfreetext = 'INVOICE_FREE_TEXT';
403 if (getDolGlobalString($paramfreetext)) {
404 $newfreetext = make_substitutions(getDolGlobalString($paramfreetext), $substitutionarray);
407 // Open and load template
408 require_once ODTPHP_PATH.'odf.php';
410 $odfHandler = new Odf(
413 'PATH_TO_TMP' => $conf->facture->dir_temp,
414 'ZIP_PROXY' => getDolGlobalString('MAIN_ODF_ZIP_PROXY', 'PclZipProxy'), // PhpZipProxy or PclZipProxy. Got "bad compression method
" error when using PhpZipProxy.
415 'DELIMITER_LEFT' => '{',
416 'DELIMITER_RIGHT' => '}'
419 } catch (Exception $e) {
420 $this->error = $e->getMessage();
421 dol_syslog($e->getMessage(), LOG_INFO);
424 // After construction $odfHandler->contentXml contains content and
425 // [!-- BEGIN row.lines --]*[!-- END row.lines --] has been replaced by
426 // [!-- BEGIN lines --]*[!-- END lines --]
427 //print html_entity_decode($odfHandler->__toString());
431 // Make substitutions into odt of freetext
433 $odfHandler->setVars('free_text', $newfreetext, true, 'UTF-8');
434 } catch (OdfException $e) {
435 dol_syslog($e->getMessage(), LOG_INFO);
438 // Define substitution array
439 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object); // Set tags __...__
440 $array_object_from_properties = $this->get_substitutionarray_each_var_object($object, $outputlangs);
441 $array_objet = $this->get_substitutionarray_object($object, $outputlangs); // Set tags object_...
442 $array_user = $this->get_substitutionarray_user($user, $outputlangs); // Set tags myuser_...
443 $array_soc = $this->get_substitutionarray_mysoc($mysoc, $outputlangs);
444 $array_thirdparty = $this->get_substitutionarray_thirdparty($socobject, $outputlangs);
445 $array_propal = is_object($propal_object) ? $this->get_substitutionarray_object($propal_object, $outputlangs, 'propal') : array();
446 $array_other = $this->get_substitutionarray_other($outputlangs);
447 // retrieve contact information for use in object as contact_xxx tags
448 $array_thirdparty_contact = array();
449 if ($usecontact && is_object($contactobject)) {
450 $array_thirdparty_contact = $this->get_substitutionarray_contact($contactobject, $outputlangs, 'contact');
453 $tmparray = array_merge($substitutionarray, $array_object_from_properties, $array_user, $array_soc, $array_thirdparty, $array_objet, $array_propal, $array_other, $array_thirdparty_contact);
454 complete_substitutions_array($tmparray, $outputlangs, $object);
456 // Complete also with substitution from keys directly found into template
457 // TODO Search all tags {object_...:xxxx} into template then loop on this found tags to analyze them and the the corresponding
458 // property of object and use the xxxx to know how to format it.
459 // Before that, we hard code this substitution as if we have found them into the template.
461 $tmparray['object_PREVIOUS_MONTH'] = dol_print_date(dol_time_plus_duree($object->date, -1, 'm'), '%m');
462 $tmparray['object_MONTH'] = dol_print_date($object->date, '%m');
463 $tmparray['object_NEXT_MONTH'] = dol_print_date(dol_time_plus_duree($object->date, 1, 'm'), '%m');
464 $tmparray['object_PREVIOUS_MONTH_TEXT'] = dol_print_date(dol_time_plus_duree($object->date, -1, 'm'), '%B');
465 $tmparray['object_MONTH_TEXT'] = dol_print_date($object->date, '%B');
466 $tmparray['object_NEXT_MONTH_TEXT'] = dol_print_date(dol_time_plus_duree($object->date, 1, 'm'), '%B');
467 $tmparray['object_PREVIOUS_YEAR'] = dol_print_date(dol_time_plus_duree($object->date, -1, 'y'), '%Y');
468 $tmparray['object_YEAR'] = dol_print_date($object->date, '%Y');
469 $tmparray['object_NEXT_YEAR'] = dol_print_date(dol_time_plus_duree($object->date, 1, 'y'), '%Y');
470 $tmparray['object_productorservice_operation'] = $outputlangs->transnoentities("MentionCategoryOfOperations
" . $categoryOfOperation);
473 // Call the ODTSubstitution hook
474 $parameters = array('odfHandler' => &$odfHandler, 'file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$tmparray);
475 $reshook = $hookmanager->executeHooks('ODTSubstitution', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
477 // retrieve the constant to apply a ratio for image size or set the ratio to 1
478 if (getDolGlobalString('MAIN_DOC_ODT_IMAGE_RATIO')) {
479 $ratio = (float) getDolGlobalString('MAIN_DOC_ODT_IMAGE_RATIO');
484 //var_dump($tmparray); exit;
485 foreach ($tmparray as $key => $value) {
487 if (preg_match('/logo$/', $key)) { // Image
488 //var_dump($value);exit;
489 if (file_exists($value)) {
490 $odfHandler->setImage($key, $value, $ratio);
492 $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8');
496 $odfHandler->setVars($key, $value, true, 'UTF-8');
498 } catch (OdfException $e) {
499 dol_syslog($e->getMessage(), LOG_INFO);
502 // Replace tags of lines
503 $foundtagforlines = 1;
505 $listlines = $odfHandler->setSegment('lines');
506 } catch (OdfExceptionSegmentNotFound $e) {
507 // We may arrive here if tags for lines not present into template
508 $foundtagforlines = 0;
509 dol_syslog($e->getMessage(), LOG_INFO);
511 if ($foundtagforlines) {
513 foreach ($object->lines as $line) {
516 $tmparray = $this->get_substitutionarray_lines($line, $outputlangs, $linenumber);
517 complete_substitutions_array($tmparray, $outputlangs, $object, $line, "completesubstitutionarray_lines
");
518 // Call the ODTSubstitutionLine hook
519 $parameters = array('odfHandler' => &$odfHandler, 'file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$tmparray, 'line' => $line);
520 $reshook = $hookmanager->executeHooks('ODTSubstitutionLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
521 foreach ($tmparray as $key => $val) {
523 $listlines->setVars($key, $val, true, 'UTF-8');
524 } catch (SegmentException $e) {
525 dol_syslog($e->getMessage(), LOG_INFO);
531 $odfHandler->mergeSegment($listlines);
532 } catch (OdfException $e) {
533 $this->error = $e->getMessage();
534 dol_syslog($this->error, LOG_WARNING);
539 // Replace labels translated
540 $tmparray = $outputlangs->get_translations_for_substitutions();
541 foreach ($tmparray as $key => $value) {
543 $odfHandler->setVars($key, $value, true, 'UTF-8');
544 } catch (OdfException $e) {
545 dol_syslog($e->getMessage(), LOG_INFO);
549 // Call the beforeODTSave hook
550 $parameters = array('odfHandler' => &$odfHandler, 'file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$tmparray);
551 $reshook = $hookmanager->executeHooks('beforeODTSave', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
554 if (getDolGlobalString('MAIN_ODT_AS_PDF')) {
556 $odfHandler->exportAsAttachedPDF($file);
557 } catch (Exception $e) {
558 $this->error = $e->getMessage();
559 dol_syslog($e->getMessage(), LOG_INFO);
564 $odfHandler->saveToDisk($file);
565 } catch (Exception $e) {
566 $this->error = $e->getMessage();
567 dol_syslog($e->getMessage(), LOG_INFO);
571 $parameters = array('odfHandler' => &$odfHandler, 'file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$tmparray);
572 $reshook = $hookmanager->executeHooks('afterODTCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
576 $odfHandler = null; // Destroy object
578 $this->result = array('fullpath' => $file);
582 $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 of invoice document generators.
Class to build documents using ODF templates generator.
info($langs)
Return description of a module.
__construct($db)
Constructor.
write_file($object, $outputlangs, $srctemplatepath='', $hidedetails=0, $hidedesc=0, $hideref=0)
Function to build a document on disk using the generic odt 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.
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