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';
43 public $version =
'dolibarr';
56 $langs->loadLangs(array(
"main",
"companies"));
59 $this->
name =
"ODT templates";
60 $this->
description = $langs->trans(
"DocumentModelOdt");
61 $this->scandir =
'COMPANY_ADDON_PDF_ODT_PATH';
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;
73 $this->option_logo = 1;
74 $this->option_freetext = 0;
75 $this->option_draft_watermark = 0;
84 if (!$this->emetteur->country_code) {
85 $this->emetteur->country_code = substr($langs->defaultlang, -2);
96 public function info($langs)
101 $langs->loadLangs(array(
"companies",
"errors"));
103 $form =
new Form($this->db);
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">';
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);
123 unset($listofdir[$key]);
126 if (!is_dir($tmpdir)) {
127 $texttitle .= img_warning($langs->trans(
"ErrorDirNotFound", $tmpdir),
'');
129 $tmpfiles =
dol_dir_list($tmpdir,
'files', 0,
'\.od(s|t)$',
'',
'name', SORT_ASC, 0, 1);
130 if (count($tmpfiles)) {
131 $listoffiles = array_merge($listoffiles, $tmpfiles);
135 $texthelp = $langs->trans(
"ListOfDirectoriesForModelGenODT");
136 $texthelp .=
'<br><br><span class="opacitymedium">'.$langs->trans(
"ExampleOfDirectoriesForModelGen").
'</span>';
138 $texthelp .=
'<br>'.$langs->trans(
"FollowingSubstitutionKeysCanBeUsed").
'<br>';
139 $texthelp .= $langs->transnoentitiesnoconv(
"FullListOnOnlineDocumentation");
142 $nbofiles = count($listoffiles);
144 $texte .=
'<span class="opacitylow">'.$langs->trans(
"NumberOfModelFilesFound").
': <b>';
148 $texte .=
'</b></span><br>';
152 $texte .=
'<div id="div_'.get_class($this).
'" class="hiddenx opacitylow">';
154 foreach ($listoffiles as $file) {
155 $texte .=
'- '.$file[
'name'].
' <a class="reposition" href="'.DOL_URL_ROOT.
'/document.php?modulepart=doctemplates&file=thirdparties/'.urlencode(basename($file[
'name'])).
'">'.img_picto(
'',
'listlight').
'</a>';
156 $texte .=
' <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>';
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>';
173 //$texte .= '<td class="center
"> ';
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")).'">';
178 //$texte .= '</table>';
179 $texte .= '</div></div>';
182 $texte .= '<input type="hidden
" name="value1
" value="COMPANY_ADDON_PDF_ODT_PATH
">';
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'];
191 $texte .= '<input type="hidden
" name="MAX_FILE_SIZE
" value="'.($maxmin * 1024).'">'; // MAX_FILE_SIZE must precede the field type=file
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
">';
201 $texte .= '</table>';
207 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
219 public function write_file($object, $outputlangs, $srctemplatepath = '', $hidedetails = 0, $hidedesc = 0, $hideref = 0)
222 global $user, $langs, $conf, $mysoc, $hookmanager;
225 if (empty($srctemplatepath)) {
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);
235 $hookmanager->initHooks(array('odtgeneration'));
238 if (!is_object($outputlangs)) {
239 $outputlangs = $langs;
241 $sav_charset_output = $outputlangs->charset_output;
242 $outputlangs->charset_output = 'UTF-8';
244 // Load translation files required by the page
245 $outputlangs->loadLangs(array("main
", "dict
", "companies
", "projects
"));
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;
254 if (!file_exists($dir)) {
255 if (dol_mkdir($dir) < 0) {
256 $this->error = $langs->transnoentities("ErrorCanNotCreateDir
", $dir);
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)
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';
278 $filename = $newfiletmp . '-' . dol_print_date(dol_now(), $format) . '.' . $newfileformat;
280 $filename = $newfiletmp . '.' . $newfileformat;
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;
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);
299 // Open and load template
300 require_once ODTPHP_PATH.'odf.php';
302 $odfHandler = new Odf(
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' => '}'
311 } catch (Exception $e) {
312 $this->error = $e->getMessage();
313 dol_syslog($e->getMessage(), LOG_INFO);
316 //print $odfHandler->__toString()."\n
";
318 // Replace tags of lines for contacts
319 $contact_arrray = array();
321 $sql = "SELECT p.rowid
";
322 $sql .= " FROM
".MAIN_DB_PREFIX."socpeople as p
";
323 $sql .= " WHERE p.fk_soc =
".((int) $object->id);
325 $result = $this->db->query($sql);
326 $num = $this->db->num_rows($result);
327 $contactstatic = null;
330 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
333 $contactstatic = new Contact($this->db);
336 $obj = $this->db->fetch_object($result);
338 $contact_arrray[$i] = $obj->rowid;
342 if ((is_array($contact_arrray) && count($contact_arrray) > 0)) {
345 $listlines = $odfHandler->setSegment('companycontacts');
346 } catch (OdfExceptionSegmentNotFound $e) {
347 // We may arrive here if tags for lines not present into template
349 dol_syslog($e->getMessage(), LOG_INFO);
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) {
358 $listlines->setVars($key, $val, true, 'UTF-8');
359 } catch (SegmentException $e) {
360 dol_syslog($e->getMessage(), LOG_INFO);
365 $this->error = $contactstatic->error;
366 dol_syslog($this->error, LOG_WARNING);
370 $odfHandler->mergeSegment($listlines);
371 } catch (OdfException $e) {
372 $this->error = $e->getMessage();
373 dol_syslog($this->error, LOG_WARNING);
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);
385 $tmparray = array_merge($array_user, $array_soc, $array_thirdparty, $array_other);
387 complete_substitutions_array($tmparray, $outputlangs, $object);
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
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');
400 // Replace variables into document
401 foreach ($tmparray as $key => $value) {
403 if (preg_match('/logo$/', $key)) { // Image
404 if (file_exists($value)) {
405 $odfHandler->setImage($key, $value, $ratio);
407 $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8');
410 $odfHandler->setVars($key, $value, true, 'UTF-8');
412 } catch (OdfException $e) {
413 // setVars failed, probably because key not found
414 dol_syslog($e->getMessage(), LOG_INFO);
418 // Replace labels translated
419 $tmparray = $outputlangs->get_translations_for_substitutions();
420 foreach ($tmparray as $key => $value) {
422 $odfHandler->setVars($key, $value, true, 'UTF-8');
423 } catch (OdfException $e) {
424 dol_syslog($e->getMessage(), LOG_INFO);
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
433 if (getDolGlobalString('MAIN_ODT_AS_PDF')) {
435 $odfHandler->exportAsAttachedPDF($file);
436 } catch (Exception $e) {
437 $this->error = $e->getMessage();
438 dol_syslog($e->getMessage(), LOG_INFO);
443 $odfHandler->creator = $user->getFullName($outputlangs);
444 $odfHandler->title = $object->builddoc_filename;
445 $odfHandler->subject = $object->builddoc_filename;
447 if (getDolGlobalString('ODT_ADD_DOLIBARR_ID')) {
448 $odfHandler->userdefined['dol_id'] = $object->id;
449 $odfHandler->userdefined['dol_element'] = $object->element;
452 $odfHandler->saveToDisk($file);
453 } catch (Exception $e) {
454 $this->error = $e->getMessage();
455 dol_syslog($e->getMessage(), LOG_INFO);
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
464 $odfHandler = null; // Destroy object
466 $this->result = array('fullpath' => $file);
470 $this->error = $langs->transnoentities("ErrorCanNotCreateDir
", $dir);
475 $this->error = 'UnknownError';
$propal type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
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.
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