dolibarr 25.0.0-alpha
doc_generic_task_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) 2013 Florian Henry <florian.henry@ope-concept.pro>
6 * Copyright (C) 2016 Charlie Benke <charlie@patas-monkey.com>
7 * Copyright (C) 2018-2026 Frédéric France <frederic.france@free.fr>
8 * Copyright (C) 2023 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
9 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <https://www.gnu.org/licenses/>.
23 * or see https://www.gnu.org/
24 */
25
32require_once DOL_DOCUMENT_ROOT.'/core/modules/project/modules_project.php';
33require_once DOL_DOCUMENT_ROOT.'/core/modules/project/task/modules_task.php';
34require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
35require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
36require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
37require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
38require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
39require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
40require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
41require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
42require_once DOL_DOCUMENT_ROOT.'/core/lib/doc.lib.php';
43require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
44if (isModEnabled("propal")) {
45 require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
46}
47if (isModEnabled('invoice')) {
48 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
49}
50if (isModEnabled('invoice')) {
51 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php';
52}
53if (isModEnabled('order')) {
54 require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
55}
56if (isModEnabled("supplier_invoice")) {
57 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
58}
59if (isModEnabled("supplier_order")) {
60 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
61}
62if (isModEnabled('contract')) {
63 require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php';
64}
65if (isModEnabled('intervention')) {
66 require_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php';
67}
68if (isModEnabled('agenda')) {
69 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
70}
71
72
77{
82 public $version = 'dolibarr';
83
84
90 public function __construct($db)
91 {
92 global $langs, $mysoc;
93
94 // Load translation files required by the page
95 $langs->loadLangs(array("main", "companies"));
96
97 $this->db = $db;
98 $this->name = "ODT templates";
99 $this->description = $langs->trans("DocumentModelOdt");
100 $this->scandir = 'PROJECT_TASK_ADDON_PDF_ODT_PATH'; // Name of constant that is used to save list of directories to scan
101
102 // Page size for A4 format
103 $this->type = 'odt';
104 $this->page_largeur = 0;
105 $this->page_hauteur = 0;
106 $this->format = array($this->page_largeur, $this->page_hauteur);
107 $this->marge_gauche = 0;
108 $this->marge_droite = 0;
109 $this->marge_haute = 0;
110 $this->marge_basse = 0;
111
112 $this->option_logo = 1; // Display logo
113 $this->option_tva = 0; // Manage the vat option COMMANDE_TVAOPTION
114 $this->option_modereg = 0; // Display payment mode
115 $this->option_condreg = 0; // Display payment terms
116 $this->option_multilang = 0; // Available in several languages
117 $this->option_escompte = 0; // Displays if there has been a discount
118 $this->option_credit_note = 0; // Support credit notes
119 $this->option_freetext = 1; // Support add of a personalised text
120 $this->option_draft_watermark = 0; // Support add of a watermark on drafts
121
122 if ($mysoc === null) {
123 dol_syslog(get_class($this).'::__construct() Global $mysoc should not be null.'. getCallerInfoString(), LOG_ERR);
124 return;
125 }
126
127 // Get source company
128 $this->emetteur = $mysoc;
129 if (!$this->emetteur->country_code) {
130 $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default, if was not defined
131 }
132 }
133
134
135 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
144 public function get_substitutionarray_object($object, $outputlangs, $array_key = 'object')
145 {
146 // phpcs:enable
147 global $extrafields;
148
149 if (!$object instanceof Project) {
150 dol_syslog("Expected Project object, got ".gettype($object), LOG_ERR);
151 return array();
152 }
153
154 $resarray = array(
155 $array_key.'_id' => $object->id,
156 $array_key.'_ref' => $object->ref,
157 $array_key.'_title' => $object->title,
158 $array_key.'_description' => $object->description,
159 $array_key.'_date_creation' => dol_print_date($object->date_c, 'day'),
160 $array_key.'_date_modification' => dol_print_date($object->date_m, 'day'),
161 $array_key.'_date_start' => dol_print_date($object->date_start, 'day'),
162 $array_key.'_date_end' => dol_print_date($object->date_end, 'day'),
163 $array_key.'_note_private' => $object->note_private,
164 $array_key.'_note_public' => $object->note_public,
165 $array_key.'_public' => $object->public,
166 $array_key.'_statut' => $object->getLibStatut()
167 );
168
169 // Retrieve extrafields
170 if (is_array($object->array_options) && count($object->array_options)) {
171 $object->fetch_optionals();
172
173 $resarray = $this->fill_substitutionarray_with_extrafields($object, $resarray, $extrafields, $array_key, $outputlangs);
174 }
175
176 return $resarray;
177 }
178
179 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
188 public function get_substitutionarray_tasks($task, $outputlangs, $array_key = 'task')
189 {
190 // phpcs:enable
191 global $extrafields;
192
193 $resarray = array(
194 'task_ref' => $task->ref,
195 'task_fk_project' => $task->fk_project,
196 'task_projectref' => $task->projectref,
197 'task_projectlabel' => $task->projectlabel,
198 'task_label' => $task->label,
199 'task_description' => $task->description,
200 'task_fk_parent' => $task->fk_task_parent,
201 'task_duration' => $task->duration_effective,
202 'task_duration_formated' => convertSecondToTime($task->duration_effective, 'allhourmin'),
203 'task_planned_workload' => $task->planned_workload,
204 'task_planned_workload_formated' => convertSecondToTime($task->planned_workload, 'allhourmin'),
205 'task_progress' => $task->progress,
206 'task_public' => $task->public,
207 'task_date_start' => dol_print_date($task->date_start, 'day'),
208 'task_date_end' => dol_print_date($task->date_end, 'day'),
209 'task_note_private' => (string) $task->note_private,
210 'task_note_public' => (string) $task->note_public
211 );
212
213 // Retrieve extrafields
214 if (is_array($task->array_options) && count($task->array_options)) {
215 $task->fetch_optionals();
216
217 $resarray = $this->fill_substitutionarray_with_extrafields($task, $resarray, $extrafields, $array_key, $outputlangs);
218 }
219
220 return $resarray;
221 }
222
223 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
231 public function get_substitutionarray_project_contacts($contact, $outputlangs)
232 {
233 // phpcs:enable
234 return array(
235 'projcontacts_id' => $contact['id'],
236 'projcontacts_rowid' => $contact['rowid'],
237 'projcontacts_role' => $contact['libelle'],
238 'projcontacts_lastname' => $contact['lastname'],
239 'projcontacts_firstname' => $contact['firstname'],
240 'projcontacts_fullcivname' => $contact['fullname'],
241 'projcontacts_socname' => $contact['socname'],
242 'projcontacts_email' => $contact['email']
243 );
244 }
245
246 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
254 public function get_substitutionarray_project_file($file, $outputlangs)
255 {
256 // phpcs:enable
257 return array(
258 'projfile_name' => $file['name'],
259 'projfile_date' => dol_print_date($file['date'], 'day'),
260 'projfile_size' => $file['size']
261 );
262 }
263
264 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
272 public function get_substitutionarray_project_reference($refdetail, $outputlangs)
273 {
274 // phpcs:enable
275 return array(
276 'projref_type' => (string) $refdetail['type'],
277 'projref_ref' => (string) $refdetail['ref'],
278 'projref_date' => dol_print_date($refdetail['date'], 'day'),
279 'projref_socname' => (string) $refdetail['socname'],
280 'projref_amountht' => price($refdetail['amountht'], 0, $outputlangs),
281 'projref_amountttc' => price($refdetail['amountttc'], 0, $outputlangs),
282 'projref_status' => (int) $refdetail['status']
283 );
284 }
285
286 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
294 public function get_substitutionarray_tasksressource($taskresource, $outputlangs)
295 {
296 // phpcs:enable
297
298 //dol_syslog(get_class($this).'::get_substitutionarray_tasksressource taskressource='.var_export($taskressource,true),LOG_DEBUG);
299 return array(
300 'taskressource_rowid' => $taskresource['rowid'],
301 'taskressource_role' => $taskresource['libelle'],
302 'taskressource_lastname' => $taskresource['lastname'],
303 'taskressource_firstname' => $taskresource['firstname'],
304 'taskressource_fullcivname' => $taskresource['fullname'],
305 'taskressource_socname' => $taskresource['socname'],
306 'taskressource_email' => $taskresource['email']
307 );
308 }
309
310 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
318 public function get_substitutionarray_taskstime($tasktime, $outputlangs)
319 {
320 // phpcs:enable
321 global $conf;
322
323 return array(
324 'tasktime_rowid' => $tasktime['rowid'],
325 'tasktime_task_date' => dol_print_date($tasktime['task_date'], 'day'),
326 'tasktime_task_duration' => convertSecondToTime($tasktime['task_duration'], 'all'),
327 'tasktime_note' => $tasktime['note'],
328 'tasktime_fk_user' => $tasktime['fk_user'],
329 'tasktime_user_name' => $tasktime['lastname'],
330 'tasktime_user_first' => $tasktime['firstname'],
331 'tasktime_fullcivname' => $tasktime['fullcivname']
332 );
333 }
334
335 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
343 public function get_substitutionarray_task_file($file, $outputlangs)
344 {
345 // phpcs:enable
346 return array(
347 'tasksfile_name' => $file['name'],
348 'tasksfile_date' => dol_print_date($file['date'], 'day'),
349 'tasksfile_size' => $file['size']
350 );
351 }
352
353
360 public function info($langs)
361 {
362 global $conf, $langs;
363
364 // Load translation files required by the page
365 $langs->loadLangs(array("errors", "companies"));
366
367 $form = new Form($this->db);
368
369 $texte = $this->description.".<br>\n";
370 $texte .= '<form action="'.$_SERVER["PHP_SELF"].'" method="POST" enctype="multipart/form-data">';
371 $texte .= '<input type="hidden" name="token" value="'.newToken().'">';
372 $texte .= '<input type="hidden" name="page_y" value="">';
373 $texte .= '<input type="hidden" name="action" value="setModuleOptions">';
374 $texte .= '<input type="hidden" name="param1" value="PROJECT_TASK_ADDON_PDF_ODT_PATH">';
375 $texte .= '<table class="nobordernopadding centpercent">';
376
377 // List of directories area
378 $texte .= '<tr><td>';
379 $texttitle = $langs->trans("ListOfDirectories");
380 $listofdir = explode(',', preg_replace('/[\r\n]+/', ',', trim($conf->global->PROJECT_TASK_ADDON_PDF_ODT_PATH)));
381 $listoffiles = array();
382 foreach ($listofdir as $key => $tmpdir) {
383 $tmpdir = trim($tmpdir);
384 $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
385 if (!$tmpdir) {
386 unset($listofdir[$key]);
387 continue;
388 }
389 if (!is_dir($tmpdir)) {
390 $texttitle .= img_warning($langs->trans("ErrorDirNotFound", $tmpdir), '');
391 } else {
392 $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.(ods|odt)');
393 if (count($tmpfiles)) {
394 $listoffiles = array_merge($listoffiles, $tmpfiles);
395 }
396 }
397 }
398 $texthelp = $langs->trans("ListOfDirectoriesForModelGenODT");
399 $texthelp .= '<br><br><span class="opacitymedium">'.$langs->trans("ExampleOfDirectoriesForModelGen").'</span>';
400 // Add list of substitution keys
401 $texthelp .= '<br>'.$langs->trans("FollowingSubstitutionKeysCanBeUsed").'<br>';
402 $texthelp .= $langs->transnoentitiesnoconv("FullListOnOnlineDocumentation"); // This contains an url, we don't modify it
403
404 // Scan directories
405 $nbofiles = count($listoffiles);
406 if (getDolGlobalString('PROJECT_TASK_ADDON_PDF_ODT_PATH')) {
407 $texte .= '<span class="opacitylow">'.$langs->trans("NumberOfModelFilesFound").': <b>';
408 //$texte.=$nbofiles?'<a id="a_'.get_class($this).'" href="#">':'';
409 $texte .= $nbofiles;
410 //$texte.=$nbofiles?'</a>':'';
411 $texte .= '</b></span><br>';
412 }
413
414 if ($nbofiles) {
415 $texte .= '<div id="div_'.get_class($this).'" class="hiddenx opacitylow">';
416 // Show list of found files
417 foreach ($listoffiles as $file) {
418 $texte .= '- '.$file['name'].' <a href="'.DOL_URL_ROOT.'/document.php?modulepart=doctemplates&file=tasks/'.urlencode(basename($file['name'])).'">'.img_picto('', 'listlight').'</a>';
419 $texte .= ' &nbsp; <a class="reposition" href="'.$_SERVER["PHP_SELF"].'?modulepart=doctemplates&keyforuploaddir=PROJECT_TASK_ADDON_PDF_ODT_PATH&action=deletefile&token='.newToken().'&file='.urlencode(basename($file['name'])).'">'.img_picto('', 'delete').'</a>';
420 $texte .= '<br>';
421 }
422 $texte .= '</div>';
423 }
424 $texte .= '<br>';
425 // Link to show/hide the area to manage directories of ODT models and template files
426 $texte .= '<span class="classlink cursorpointer" onclick="javascript: jQuery(\'.div_odtmodelsof'.get_class($this).'\').toggle();">'.img_picto('', 'add').' '.$langs->trans("UploadNewTemplate").'...</span>';
427 $texte .= '<div class="div_odtmodelsof'.get_class($this).'" style="display: none; margin-top: 6px;">';
428 $texte .= $form->textwithpicto($texttitle, $texthelp, 1, 'help', '', 1, 3, $this->name);
429 $texte .= '<div><div style="display: inline-block; min-width: 100px; vertical-align: middle;">';
430 $texte .= '<textarea class="flat textareafordir" spellcheck="false" cols="60" name="value1">';
431 $texte .= getDolGlobalString('PROJECT_TASK_ADDON_PDF_ODT_PATH');
432 $texte .= '</textarea>';
433 $texte .= '</div><div style="display: inline-block; vertical-align: middle;">';
434 $texte .= '<input type="submit" class="button button-edit reposition smallpaddingimp" name="modify" value="'.dol_escape_htmltag($langs->trans("Modify")).'">';
435 $texte .= '<br></div></div>';
436 $texte .= '</div>';
437
438 // Add input to upload a new template file.
439 $texte .= '<div class="div_odtmodelsof'.get_class($this).'" style="display: none;">';
440 $maxfilesizearray = getMaxFileSizeArray();
441 $maxmin = $maxfilesizearray['maxmin'];
442 if ($maxmin > 0) {
443 $texte .= '<input type="hidden" name="MAX_FILE_SIZE" value="'.($maxmin * 1024).'">'; // MAX_FILE_SIZE must precede the field type=file
444 }
445 $texte .= ' <input type="file" name="uploadfile">';
446 $texte .= '<input type="hidden" value="PROJECT_TASK_ADDON_PDF_ODT_PATH" name="keyforuploaddir">';
447 $texte .= '<input type="submit" class="button smallpaddingimp reposition" value="'.dol_escape_htmltag($langs->trans("Upload")).'" name="upload">';
448 $texte .= '</div>';
449 $texte .= '</td>';
450
451 $texte .= '</tr>';
452
453 $texte .= '</table>';
454 $texte .= '</form>';
455
456 return $texte;
457 }
458
459 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
471 public function write_file($object, $outputlangs, $srctemplatepath = '', $hidedetails = 0, $hidedesc = 0, $hideref = 0)
472 {
473 // phpcs:enable
474 global $user, $langs, $conf, $mysoc, $hookmanager;
475
476 if (empty($srctemplatepath)) {
477 dol_syslog("doc_generic_odt::write_file parameter srctemplatepath empty", LOG_WARNING);
478 return -1;
479 }
480
481 // Add odtgeneration hook
482 if (!is_object($hookmanager)) {
483 include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
484 $hookmanager = new HookManager($this->db);
485 }
486 $hookmanager->initHooks(array('odtgeneration'));
487 global $action;
488
489 if (!is_object($outputlangs)) {
490 $outputlangs = $langs;
491 }
492 $sav_charset_output = $outputlangs->charset_output;
493 $outputlangs->charset_output = 'UTF-8';
494
495 // Load translation files required by the page
496 $outputlangs->loadLangs(array("main", "dict", "companies", "projects"));
497
498 if ($conf->project->dir_output) {
499 // If $object is id instead of object
500 if (!is_object($object)) {
501 $id = $object;
502 $object = new Task($this->db);
503 $result = $object->fetch($id);
504 if ($result < 0) {
505 dol_print_error($this->db, $object->error);
506 return -1;
507 }
508 }
509 $project = new Project($this->db);
510 $project->fetch((int) $object->fk_project);
511 $project->fetch_thirdparty();
512
513 $dir = $conf->project->dir_output."/".$project->ref."/";
514 $objectref = dol_sanitizeFileName($object->ref);
515 if (!preg_match('/specimen/i', $objectref)) {
516 $dir .= "/".$objectref;
517 }
518 $file = $dir."/".$objectref.".odt";
519
520 if (!file_exists($dir)) {
521 if (dol_mkdir($dir) < 0) {
522 $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir);
523 return -1;
524 }
525 }
526
527
528 if (file_exists($dir)) {
529 //print "srctemplatepath=".$srctemplatepath; // Src filename
530 $newfile = basename($srctemplatepath);
531 $newfiletmp = preg_replace('/\.(ods|odt)/i', '', $newfile);
532 $newfiletmp = preg_replace('/template_/i', '', $newfiletmp);
533 $newfiletmp = preg_replace('/modele_/i', '', $newfiletmp);
534 $newfiletmp = $objectref . '_' . $newfiletmp;
535 //$file=$dir.'/'.$newfiletmp.'.'.dol_print_date(dol_now(),'%Y%m%d%H%M%S').'.odt';
536 $file = $dir . '/' . $newfiletmp . '.odt';
537 //print "newdir=".$dir;
538 //print "newfile=".$newfile;
539 //print "file=".$file;
540 //print "conf->societe->dir_temp=".$conf->societe->dir_temp;
541
542 dol_mkdir($conf->project->dir_temp);
543 if (!is_writable($conf->project->dir_temp)) {
544 $this->error = $langs->transnoentities("ErrorFailedToWriteInTempDirectory", $conf->project->dir_temp);
545 dol_syslog('Error in write_file: ' . $this->error, LOG_ERR);
546 return -1;
547 }
548
549 $socobject = $project->thirdparty;
550
551 // Make substitution
552 $substitutionarray = array(
553 '__FROM_NAME__' => $this->emetteur->name,
554 '__FROM_EMAIL__' => $this->emetteur->email,
555 );
556 complete_substitutions_array($substitutionarray, $langs, $object);
557 // Call the ODTSubstitution hook
558 $tmparray = array();
559 $action = '';
560 $parameters = array('file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$tmparray);
561 $reshook = $hookmanager->executeHooks('ODTSubstitution', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
562
563 // Open and load template
564 require_once ODTPHP_PATH.'odf.php';
565 try {
566 $odfHandler = new Odf(
567 $srctemplatepath,
568 array(
569 'PATH_TO_TMP' => $conf->project->dir_temp,
570 'ZIP_PROXY' => getDolGlobalString('MAIN_ODF_ZIP_PROXY', 'PclZipProxy'), // PhpZipProxy or PclZipProxy. Got "bad compression method" error when using PhpZipProxy.
571 'DELIMITER_LEFT' => '{',
572 'DELIMITER_RIGHT' => '}'
573 )
574 );
575 } catch (Exception $e) {
576 $this->error = $e->getMessage();
577 return -1;
578 }
579 // After construction $odfHandler->contentXml contains content and
580 // [!-- BEGIN row.lines --]*[!-- END row.lines --] has been replaced by
581 // [!-- BEGIN lines --]*[!-- END lines --]
582 //print html_entity_decode($odfHandler->__toString());
583 //print exit;
584
585
586 // Define substitution array
587 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object);
588 $array_object_from_properties = $this->get_substitutionarray_each_var_object($object, $outputlangs);
589 $array_objet = $this->get_substitutionarray_object($project, $outputlangs);
590 $array_user = $this->get_substitutionarray_user($user, $outputlangs);
591 $array_soc = $this->get_substitutionarray_mysoc($mysoc, $outputlangs);
592 $array_thirdparty = $this->get_substitutionarray_thirdparty($socobject, $outputlangs);
593 $array_other = $this->get_substitutionarray_other($outputlangs);
594
595 $tmparray = array_merge($substitutionarray, $array_object_from_properties, $array_user, $array_soc, $array_thirdparty, $array_objet, $array_other);
596 complete_substitutions_array($tmparray, $outputlangs, $object);
597
598 // retrieve the constant to apply a ratio for image size or set the ratio to 1
599 if (getDolGlobalString('MAIN_DOC_ODT_IMAGE_RATIO')) {
600 $ratio = (float) getDolGlobalString('MAIN_DOC_ODT_IMAGE_RATIO');
601 } else {
602 $ratio = 1;
603 }
604
605 foreach ($tmparray as $key => $value) {
606 try {
607 if (preg_match('/logo$/', $key)) { // Image
608 if (file_exists($value)) {
609 $odfHandler->setImage($key, $value, $ratio);
610 } else {
611 $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8');
612 }
613 } else { // Text
614 $odfHandler->setVars($key, $value, true, 'UTF-8');
615 }
616 } catch (OdfException $e) {
617 dol_syslog($e->getMessage(), LOG_INFO);
618 }
619 }
620
623 // Replace tags of lines for tasks
624 try {
625 $tmparray = $this->get_substitutionarray_tasks($object, $outputlangs);
626 complete_substitutions_array($tmparray, $outputlangs, $object);
627 foreach ($tmparray as $key => $val) {
628 try {
629 $odfHandler->setVars($key, $val, true, 'UTF-8');
630 } catch (OdfException $e) {
631 dol_syslog($e->getMessage(), LOG_INFO);
632 }
633 }
634
635 // Replace tags of lines for contacts task
636 $sourcearray = array('internal', 'external');
637 $contact_array = array();
638 foreach ($sourcearray as $source) {
639 $contact_temp = $object->liste_contact(-1, $source);
640 if ((is_array($contact_temp) && count($contact_temp) > 0)) {
641 $contact_array = array_merge($contact_array, $contact_temp);
642 }
643 }
644 // Check for segment
645 $listlinestaskres = null;
646 try {
647 $listlinestaskres = $odfHandler->setSegment('tasksressources');
648 } catch (OdfExceptionSegmentNotFound $e) {
649 // We may arrive here if tags for lines not present into template
650 $listlinestaskres = null;
651 dol_syslog($e->getMessage(), LOG_INFO);
652 }
653 if ($listlinestaskres && (is_array($contact_array) && count($contact_array) > 0)) {
654 foreach ($contact_array as $contact) {
655 if ($contact['source'] == 'internal') {
656 $objectdetail = new User($this->db);
657 $objectdetail->fetch($contact['id']);
658 $contact['socname'] = $mysoc->name;
659 } elseif ($contact['source'] == 'external') {
660 $objectdetail = new Contact($this->db);
661 $objectdetail->fetch($contact['id']);
662
663 $soc = new Societe($this->db);
664 $soc->fetch($contact['socid']);
665 $contact['socname'] = $soc->name;
666 } else {
667 dol_syslog(get_class().'::'.__METHOD__.' Unexpected contact source:'.$contact['source'], LOG_WARNING);
668 $objectdetail = null;
669 }
670 $contact['fullname'] = is_object($objectdetail) ? $objectdetail->getFullName($outputlangs, 1) : null;
671
672 $tmparray = $this->get_substitutionarray_tasksressource($contact, $outputlangs);
673
674 foreach ($tmparray as $key => $val) {
675 try {
676 $listlinestaskres->setVars($key, $val, true, 'UTF-8');
677 } catch (SegmentException $e) {
678 dol_syslog($e->getMessage(), LOG_INFO);
679 }
680 }
681 $listlinestaskres->merge();
682 }
683 $odfHandler->mergeSegment($listlinestaskres);
684 }
685
686 // Check for segment
687 $listlinestasktime = null;
688 try {
689 $listlinestasktime = $odfHandler->setSegment('taskstimes');
690 } catch (OdfExceptionSegmentNotFound $e) {
691 // We may arrive here if tags for lines not present into template
692 $listlinestasktime = null;
693 dol_syslog($e->getMessage(), LOG_INFO);
694 }
695
696 // Time resources
697 $sql = "SELECT t.rowid, t.element_date as task_date, t.element_duration as task_duration, t.fk_user, t.note";
698 $sql .= ", u.lastname, u.firstname";
699 $sql .= " FROM ".MAIN_DB_PREFIX."element_time as t";
700 $sql .= " , ".MAIN_DB_PREFIX."user as u";
701 $sql .= " WHERE t.fk_element =".((int) $object->id);
702 $sql .= " AND t.elementtype = 'task'";
703 $sql .= " AND t.fk_user = u.rowid";
704 $sql .= " ORDER BY t.element_date DESC";
705
706 $resql = $this->db->query($sql);
707 if ($listlinestasktime !== null && $resql) {
708 $num = $this->db->num_rows($resql);
709 $i = 0;
710 $tasks = array();
711
712 while ($i < $num) {
713 $row = $this->db->fetch_array($resql);
714 if (!empty($row['fk_user'])) {
715 $objectdetail = new User($this->db);
716 $objectdetail->fetch($row['fk_user']);
717 // TODO Use a cache to avoid fetch for same user
718 $row['fullcivname'] = $objectdetail->getFullName($outputlangs, 1);
719 } else {
720 $row['fullcivname'] = '';
721 }
722
723 $tmparray = $this->get_substitutionarray_taskstime($row, $outputlangs);
724
725 foreach ($tmparray as $key => $val) {
726 try {
727 $listlinestasktime->setVars($key, $val, true, 'UTF-8');
728 } catch (SegmentException $e) {
729 dol_syslog($e->getMessage(), LOG_INFO);
730 }
731 }
732 $listlinestasktime->merge();
733 $i++;
734 }
735 $this->db->free($resql);
736
737 $odfHandler->mergeSegment($listlinestasktime);
738 }
739
740
741 // Replace tags of project files
742 // Check for segment
743 $listtasksfiles = null;
744 try {
745 $listtasksfiles = $odfHandler->setSegment('tasksfiles');
746 } catch (OdfExceptionSegmentNotFound $e) {
747 // We may arrive here if tags for lines not present into template
748 $listtasksfiles = null;
749 dol_syslog($e->getMessage(), LOG_INFO);
750 }
751 if ($listtasksfiles !== null) {
752 $upload_dir = $conf->project->dir_output.'/'.dol_sanitizeFileName($project->ref).'/'.dol_sanitizeFileName($object->ref);
753 $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', 'name', SORT_ASC, 1);
754
755 foreach ($filearray as $filedetail) {
756 $tmparray = $this->get_substitutionarray_task_file($filedetail, $outputlangs);
757 //dol_syslog(get_class($this).'::main $tmparray'.var_export($tmparray,true));
758 foreach ($tmparray as $key => $val) {
759 try {
760 $listtasksfiles->setVars($key, $val, true, 'UTF-8');
761 } catch (SegmentException $e) {
762 dol_syslog($e->getMessage(), LOG_INFO);
763 }
764 }
765 $listtasksfiles->merge();
766 }
767 //$listlines->merge();
768
769 $odfHandler->mergeSegment($listtasksfiles);
770 }
771 } catch (OdfException $e) {
772 $this->error = $e->getMessage();
773 dol_syslog($this->error, LOG_WARNING);
774 return -1;
775 }
776
777
778 // Replace tags of project files
779 // Check for segment
780 $listlines = null;
781 try {
782 $listlines = $odfHandler->setSegment('projectfiles');
783 } catch (OdfExceptionSegmentNotFound $e) {
784 // We may arrive here if tags for lines not present into template
785 $listlines = null;
786 dol_syslog($e->getMessage(), LOG_INFO);
787 }
788 if ($listlines !== null) {
789 try {
790 $upload_dir = $conf->project->dir_output.'/'.dol_sanitizeFileName($object->ref);
791 $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', 'name', SORT_ASC, 1);
792
793 foreach ($filearray as $filedetail) {
794 //dol_syslog(get_class($this).'::main $filedetail'.var_export($filedetail,true));
795 $tmparray = $this->get_substitutionarray_project_file($filedetail, $outputlangs);
796
797 foreach ($tmparray as $key => $val) {
798 try {
799 $listlines->setVars($key, $val, true, 'UTF-8');
800 } catch (SegmentException $e) {
801 dol_syslog($e->getMessage(), LOG_INFO);
802 }
803 }
804 $listlines->merge();
805 }
806 $odfHandler->mergeSegment($listlines);
807 } catch (OdfException $e) {
808 $this->error = $e->getMessage();
809 dol_syslog($this->error, LOG_WARNING);
810 return -1;
811 }
812 }
813
814 // Replace tags of lines for contacts
815 $sourcearray = array('internal', 'external');
816 $contact_array = array();
817 foreach ($sourcearray as $source) {
818 $contact_temp = $project->liste_contact(-1, $source);
819 if ((is_array($contact_temp) && count($contact_temp) > 0)) {
820 $contact_array = array_merge($contact_array, $contact_temp);
821 }
822 }
823 // Check for segment
824 $listlines = null;
825 try {
826 $listlines = $odfHandler->setSegment('projectcontacts');
827 } catch (OdfExceptionSegmentNotFound $e) {
828 // We may arrive here if tags for lines not present into template
829 $listlines = null;
830 dol_syslog($e->getMessage(), LOG_INFO);
831 }
832 if ($listlines !== null && (is_array($contact_array) && count($contact_array) > 0)) {
833 try {
834 foreach ($contact_array as $contact) {
835 if ($contact['source'] == 'internal') {
836 $objectdetail = new User($this->db);
837 $objectdetail->fetch($contact['id']);
838 $contact['socname'] = $mysoc->name;
839 } elseif ($contact['source'] == 'external') {
840 $objectdetail = new Contact($this->db);
841 $objectdetail->fetch($contact['id']);
842
843 $soc = new Societe($this->db);
844 $soc->fetch($contact['socid']);
845 $contact['socname'] = $soc->name;
846 } else {
847 dol_syslog(get_class().'::'.__METHOD__.' Unexpected contact source:'.$contact['source'], LOG_ERR);
848 continue;
849 }
850 $contact['fullname'] = $objectdetail->getFullName($outputlangs, 1);
851
852 $tmparray = $this->get_substitutionarray_project_contacts($contact, $outputlangs);
853
854 foreach ($tmparray as $key => $val) {
855 try {
856 $listlines->setVars($key, $val, true, 'UTF-8');
857 } catch (SegmentException $e) {
858 dol_syslog($e->getMessage(), LOG_INFO);
859 }
860 }
861 $listlines->merge();
862 }
863 $odfHandler->mergeSegment($listlines);
864 } catch (OdfException $e) {
865 $this->error = $e->getMessage();
866 dol_syslog($this->error, LOG_WARNING);
867 return -1;
868 }
869 }
870
871
872 // Call the beforeODTSave hook
873 $parameters = array('odfHandler' => &$odfHandler, 'file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$tmparray);
874 $reshook = $hookmanager->executeHooks('beforeODTSave', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
875
876
877 // Write new file
878 if (getDolGlobalString('MAIN_ODT_AS_PDF')) {
879 try {
880 $odfHandler->exportAsAttachedPDF($file);
881 } catch (Exception $e) {
882 $this->error = $e->getMessage();
883 dol_syslog($e->getMessage(), LOG_INFO);
884 return -1;
885 }
886 } else {
887 try {
888 $odfHandler->saveToDisk($file);
889 } catch (Exception $e) {
890 $this->error = $e->getMessage();
891 dol_syslog($e->getMessage(), LOG_INFO);
892 return -1;
893 }
894 }
895 $parameters = array('odfHandler' => &$odfHandler, 'file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$tmparray);
896 $reshook = $hookmanager->executeHooks('afterODTCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
897
898 dolChmod($file);
899
900 $odfHandler = null; // Destroy object
901
902 $this->result = array('fullpath' => $file);
903
904 return 1; // Success
905 } else {
906 $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir);
907 return -1;
908 }
909 }
910
911 return -1;
912 }
913}
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
$propal type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
Definition propal.php:281
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
fill_substitutionarray_with_extrafields($object, $array_to_fill, $extrafields, $array_key, $outputlangs)
Fill array with couple extrafield key => extrafield value Note that vars into substitutions array are...
Class to manage generation of HTML components Only common components must be here.
Parent class for task models.
Class to manage projects.
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.
get_substitutionarray_task_file($file, $outputlangs)
Define array with couple substitution key => substitution value.
get_substitutionarray_taskstime($tasktime, $outputlangs)
Define array with couple substitution key => substitution value.
get_substitutionarray_tasks($task, $outputlangs, $array_key='task')
Define array with couple substitution key => substitution value.
get_substitutionarray_object($object, $outputlangs, $array_key='object')
Define array with couple substitution key => substitution value.
get_substitutionarray_project_contacts($contact, $outputlangs)
Define array with couple substitution key => substitution value.
get_substitutionarray_project_file($file, $outputlangs)
Define array with couple substitution key => substitution value.
info($langs)
Return description of a module.
get_substitutionarray_project_reference($refdetail, $outputlangs)
Define array with couple substitution key => substitution value.
get_substitutionarray_tasksressource($taskresource, $outputlangs)
Define array with couple substitution key => substitution value.
global $mysoc
convertSecondToTime($iSecond, $format='all', $lengthOfDay=86400, $lengthOfWeek=7)
Return, in clear text, value of a number of seconds in days, hours and minutes.
Definition date.lib.php:263
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.
Definition files.lib.php:66
getCallerInfoString()
Get caller info as a string that can be appended to a log message.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
newToken()
Return the value of token currently saved into session with name 'newtoken'.
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.
isModEnabled($module)
Is Dolibarr module enabled.
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 user
Active Directory does not allow anonymous connections.
Definition repair.php:166
$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