Passed
Push — EXTRACT_CLASSES ( d4f850...56e940 )
by Rafael
41:39
created

get_substitutionarray_project_reference()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 9
nc 1
nop 2
dl 0
loc 13
rs 9.9666
c 0
b 0
f 0
1
<?php
2
3
/* Copyright (C) 2010-2012  Laurent Destailleur <[email protected]>
4
 * Copyright (C) 2012		Juanjo Menent		<[email protected]>
5
 * Copyright (C) 2013		Florian Henry		<[email protected]>
6
 * Copyright (C) 2016-2023	Charlene Benke		<[email protected]>
7
 * Copyright (C) 2018-2024  Frédéric France     <[email protected]>
8
 * Copyright (C) 2023      	Gauthier VERDOL     <[email protected]>
9
 * Copyright (C) 2024		MDW							<[email protected]>
10
 * Copyright (C) 2024       Rafael San José             <[email protected]>
11
 *
12
 * This program is free software; you can redistribute it and/or modify
13
 * it under the terms of the GNU General Public License as published by
14
 * the Free Software Foundation; either version 3 of the License, or
15
 * (at your option) any later version.
16
 *
17
 * This program is distributed in the hope that it will be useful,
18
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
 * GNU General Public License for more details.
21
 *
22
 * You should have received a copy of the GNU General Public License
23
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
24
 * or see https://www.gnu.org/
25
 */
26
27
/**
28
 *  \file       htdocs/core/modules/project/doc/doc_generic_project_odt.modules.php
29
 *  \ingroup    project
30
 *  \brief      File of class to build ODT documents for third parties
31
 */
32
33
require_once constant('DOL_DOCUMENT_ROOT') . '/core/modules/project/modules_project.php';
34
35
require_once constant('DOL_DOCUMENT_ROOT') . '/core/lib/company.lib.php';
36
require_once constant('DOL_DOCUMENT_ROOT') . '/core/lib/functions2.lib.php';
37
require_once constant('DOL_DOCUMENT_ROOT') . '/core/lib/files.lib.php';
38
require_once constant('DOL_DOCUMENT_ROOT') . '/core/lib/doc.lib.php';
39
require_once constant('DOL_DOCUMENT_ROOT') . '/core/lib/date.lib.php';
40
if (isModEnabled("propal")) {
41
}
42
if (isModEnabled('invoice')) {
43
}
44
if (isModEnabled('invoice')) {
45
    require_once constant('DOL_DOCUMENT_ROOT') . '/compta/facture/class/facture-rec.class.php';
46
}
47
if (isModEnabled('deplacement')) {
48
    require_once constant('DOL_DOCUMENT_ROOT') . '/compta/deplacement/class/deplacement.class.php';
49
}
50
if (isModEnabled('shipping')) {
51
    require_once constant('DOL_DOCUMENT_ROOT') . '/expedition/class/expedition.class.php';
52
}
53
54
/**
55
 *  Class to build documents using ODF templates generator
56
 */
57
class doc_generic_project_odt extends ModelePDFProjects
58
{
59
    /**
60
     * Dolibarr version of the loaded document
61
     * @var string
62
     */
63
    public $version = 'dolibarr';
64
65
66
    /**
67
     *  Constructor
68
     *
69
     *  @param      DoliDB      $db      Database handler
70
     */
71
    public function __construct($db)
72
    {
73
        global $langs, $mysoc;
74
75
        // Load traductions files required by page
76
        $langs->loadLangs(array("companies", "main"));
77
78
        $this->db = $db;
79
        $this->name = "ODT templates";
80
        $this->description = $langs->trans("DocumentModelOdt");
81
        $this->scandir = 'PROJECT_ADDON_PDF_ODT_PATH'; // Name of constant that is used to save list of directories to scan
82
83
        // Page size for A4 format
84
        $this->type = 'odt';
85
        $this->page_largeur = 0;
86
        $this->page_hauteur = 0;
87
        $this->format = array($this->page_largeur, $this->page_hauteur);
88
        $this->marge_gauche = 0;
89
        $this->marge_droite = 0;
90
        $this->marge_haute = 0;
91
        $this->marge_basse = 0;
92
93
        $this->option_logo = 1; // Display logo
94
        $this->option_tva = 0; // Manage the vat option COMMANDE_TVAOPTION
95
        $this->option_modereg = 0; // Display payment mode
96
        $this->option_condreg = 0; // Display payment terms
97
        $this->option_multilang = 1; // Available in several languages
98
        $this->option_escompte = 0; // Displays if there has been a discount
99
        $this->option_credit_note = 0; // Support credit notes
100
        $this->option_freetext = 1; // Support add of a personalised text
101
        $this->option_draft_watermark = 0; // Support add of a watermark on drafts
102
103
        // Get source company
104
        $this->emetteur = $mysoc;
105
        if (!$this->emetteur->country_code) {
106
            $this->emetteur->country_code = substr($langs->defaultlang, -2); // Par default, si n'etait pas defini
107
        }
108
    }
109
110
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
111
    /**
112
     * Define array with couple substitution key => substitution value
113
     *
114
     * @param   CommonObject    $object             Main object to use as data source
115
     * @param   Translate       $outputlangs        Lang object to use for output
116
     * @param   string          $array_key          Name of the key for return array
117
     * @return  array                               Array of substitution
118
     */
119
    public function get_substitutionarray_object($object, $outputlangs, $array_key = 'object')
120
    {
121
		// phpcs:enable
122
        if (!$object instanceof Project) {
123
            dol_syslog("Expected Project object, got " . gettype($object), LOG_ERR);
124
            return array();
125
        }
126
127
        $resarray = array(
128
            $array_key . '_id' => $object->id,
129
            $array_key . '_ref' => $object->ref,
130
            $array_key . '_title' => $object->title,
131
            $array_key . '_description' => $object->description,
132
            $array_key . '_date_creation' => dol_print_date($object->date_c, 'day'),
133
            $array_key . '_date_modification' => dol_print_date($object->date_m, 'day'),
134
            $array_key . '_date_start' => dol_print_date($object->date_start, 'day'),
135
            $array_key . '_date_end' => dol_print_date($object->date_end, 'day'),
136
            $array_key . '_note_private' => $object->note_private,
137
            $array_key . '_note_public' => $object->note_public,
138
            $array_key . '_public' => $object->public,
139
            $array_key . '_statut' => $object->getLibStatut()
140
        );
141
142
        $extrafields = new ExtraFields($this->db);
143
        $extrafields->fetch_name_optionals_label($object->table_element, true);
144
        $object->fetch_optionals();
145
146
        $resarray = $this->fill_substitutionarray_with_extrafields($object, $resarray, $extrafields, $array_key, $outputlangs);
147
148
        return $resarray;
149
    }
150
151
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
152
    /**
153
     *  Define array with couple substitution key => substitution value
154
     *
155
     *  @param  Task            $task               Task Object
156
     *  @param  Translate       $outputlangs        Lang object to use for output
157
     *  @return array                               Return a substitution array
158
     */
159
    public function get_substitutionarray_tasks(Task $task, $outputlangs)
160
    {
161
		// phpcs:enable
162
        $resarray = array(
163
            'task_ref' => $task->ref,
164
            'task_fk_project' => $task->fk_project,
165
            'task_projectref' => $task->projectref,
166
            'task_projectlabel' => $task->projectlabel,
167
            'task_label' => $task->label,
168
            'task_description' => $task->description,
169
            'task_fk_parent' => $task->fk_task_parent,
170
            'task_duration' => $task->duration,
171
            'task_duration_hour' => convertSecondToTime($task->duration, 'all'),
172
            'task_planned_workload' => $task->planned_workload,
173
            'task_planned_workload_hour' => convertSecondToTime($task->planned_workload, 'all'),
174
            'task_progress' => $task->progress,
175
            'task_public' => $task->public,
176
            'task_date_start' => dol_print_date($task->date_start, 'day'),
177
            'task_date_end' => dol_print_date($task->date_end, 'day'),
178
            'task_note_private' => $task->note_private,
179
            'task_note_public' => $task->note_public
180
        );
181
182
        $extrafields = new ExtraFields($this->db);
183
        $extrafields->fetch_name_optionals_label($task->table_element, true);
184
        $task->fetch_optionals();
185
186
        $resarray = $this->fill_substitutionarray_with_extrafields($task, $resarray, $extrafields, 'task', $outputlangs);
187
188
        return $resarray;
189
    }
190
191
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
192
    /**
193
     *  Define array with couple substitution key => substitution value
194
     *
195
     *  @param  array           $contact            Contact array
196
     *  @param  Translate       $outputlangs        Lang object to use for output
197
     *  @return array                               Return a substitution array
198
     */
199
    public function get_substitutionarray_project_contacts($contact, $outputlangs)
200
    {
201
		// phpcs:enable
202
        $pc = 'projcontacts_'; // prefix to avoid typos
203
204
        $ret = array(
205
            $pc . 'id' => $contact['id'],
206
            $pc . 'rowid' => $contact['rowid'],
207
            $pc . 'role' => $contact['libelle'],
208
            $pc . 'lastname' => $contact['lastname'],
209
            $pc . 'firstname' => $contact['firstname'],
210
            $pc . 'civility' => $contact['civility'],
211
            $pc . 'fullcivname' => $contact['fullname'],
212
            $pc . 'socname' => $contact['socname'],
213
            $pc . 'email' => $contact['email']
214
            );
215
216
        if ($contact['source'] == 'external') {
217
            $ret[$pc . 'isInternal'] = ''; // not internal
218
219
            $ct = new Contact($this->db);
220
            $ct->fetch($contact['id']);
221
            $ret[$pc . 'phone_pro'] = $ct->phone_pro;
222
            $ret[$pc . 'phone_perso'] = $ct->phone_perso;
223
            $ret[$pc . 'phone_mobile'] = $ct->phone_mobile;
224
225
            // fetch external user extrafields
226
            $extrafields = new ExtraFields($this->db);
227
            $extrafields->fetch_name_optionals_label($ct->table_element, true);
228
            $extrafields_num = $ct->fetch_optionals();
229
            //dol_syslog(get_class($this)."::get_substitutionarray_project_contacts: ===== Number of Extrafields found: ".$extrafields_num, LOG_DEBUG);
230
            foreach ($ct->array_options as $efkey => $efval) {
231
                dol_syslog(get_class($this) . "::get_substitutionarray_project_contacts: +++++ Extrafield " . $efkey . " => " . $efval, LOG_DEBUG);
232
                $ret[$pc . $efkey] = $efval; // add nothing else because it already comes as 'options_XX'
233
            }
234
        } elseif ($contact['source'] == 'internal') {
235
            $ret[$pc . 'isInternal'] = '1'; // this is an internal user
236
237
            $ct = new User($this->db);
238
            $ct->fetch($contact['id']);
239
            $ret[$pc . 'phone_pro'] = $ct->office_phone;
240
            $ret[$pc . 'phone_perso'] = '';
241
            $ret[$pc . 'phone_mobile'] = $ct->user_mobile;
242
            // do internal users have extrafields ?
243
        }
244
        return $ret;
245
    }
246
247
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
248
    /**
249
     *  Define array with couple substitution key => substitution value
250
     *
251
     *  @param  array           $file               file array
252
     *  @param  Translate       $outputlangs        Lang object to use for output
253
     *  @return array                               Return a substitution array
254
     */
255
    public function get_substitutionarray_project_file($file, $outputlangs)
256
    {
257
		// phpcs:enable
258
        return array(
259
            'projfile_name' => $file['name'],
260
            'projfile_date' => dol_print_date($file['date'], 'day'),
261
            'projfile_size' => $file['size']
262
        );
263
    }
264
265
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
266
    /**
267
     *  Define array with couple substitution key => substitution value
268
     *
269
     *  @param  array           $refdetail          Reference array
270
     *  @param  Translate       $outputlangs        Lang object to use for output
271
     *  @return array                               Return a substitution array
272
     */
273
    public function get_substitutionarray_project_reference($refdetail, $outputlangs)
274
    {
275
		// phpcs:enable
276
        global $conf;
277
278
        return array(
279
            'projref_type' => $refdetail['type'],
280
            'projref_ref' => $refdetail['ref'],
281
            'projref_date' => dol_print_date($refdetail['date'], 'day'),
282
            'projref_socname' => $refdetail['socname'],
283
            'projref_amountht' => price($refdetail['amountht'], 0, $outputlangs),
284
            'projref_amountttc' => price($refdetail['amountttc'], 0, $outputlangs),
285
            'projref_status' => $refdetail['status']
286
        );
287
    }
288
289
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
290
    /**
291
     *  Define array with couple substitution key => substitution value
292
     *
293
     *  @param  array           $taskresource           Reference array
294
     *  @param  Translate       $outputlangs            Lang object to use for output
295
     *  @return array                                   Return a substitution array
296
     */
297
    public function get_substitutionarray_tasksressource($taskresource, $outputlangs)
298
    {
299
		// phpcs:enable
300
301
        //dol_syslog(get_class($this).'::get_substitutionarray_tasksressource taskressource='.var_export($taskressource,true),LOG_DEBUG);
302
        return array(
303
            'taskressource_rowid' => $taskresource['rowid'],
304
            'taskressource_role' => $taskresource['libelle'],
305
            'taskressource_lastname' => $taskresource['lastname'],
306
            'taskressource_firstname' => $taskresource['firstname'],
307
            'taskressource_fullcivname' => $taskresource['fullname'],
308
            'taskressource_socname' => $taskresource['socname'],
309
            'taskressource_email' => $taskresource['email']
310
        );
311
    }
312
313
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
314
    /**
315
     *  Define array with couple substitution key => substitution value
316
     *
317
     *  @param  array           $tasktime           Array of times object
318
     *  @param  Translate       $outputlangs        Lang object to use for output
319
     *  @return array                               Return a substitution array
320
     */
321
    public function get_substitutionarray_taskstime($tasktime, $outputlangs)
322
    {
323
		// phpcs:enable
324
        return array(
325
            'tasktime_rowid' => $tasktime['rowid'],
326
            'tasktime_task_date' => dol_print_date($tasktime['task_date'], 'day'),
327
            'tasktime_task_duration_sec' => $tasktime['task_duration'],
328
            'tasktime_task_duration' => convertSecondToTime($tasktime['task_duration'], 'all'),
329
            'tasktime_note' => $tasktime['note'],
330
            'tasktime_fk_user' => $tasktime['fk_user'],
331
            'tasktime_user_name' => $tasktime['name'],
332
            'tasktime_user_first' => $tasktime['firstname'],
333
            'tasktime_fullcivname' => $tasktime['fullcivname'],
334
            'tasktime_amountht' => $tasktime['amountht'],
335
            'tasktime_amountttc' => $tasktime['amountttc'],
336
            'tasktime_thm' => $tasktime['thm'],
337
        );
338
    }
339
340
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
341
    /**
342
     *  Define array with couple substitution key => substitution value
343
     *
344
     *  @param  array           $file               file array
345
     *  @param  Translate       $outputlangs        Lang object to use for output
346
     *  @return array                               Return a substitution array
347
     */
348
    public function get_substitutionarray_task_file($file, $outputlangs)
349
    {
350
		// phpcs:enable
351
        return array(
352
            'tasksfile_name' => $file['name'],
353
            'tasksfile_date' => dol_print_date($file['date'], 'day'),
354
            'tasksfile_size' => $file['size']
355
        );
356
    }
357
358
359
    /**
360
     *  Return description of a module
361
     *
362
     *  @param  Translate   $langs      Lang object to use for output
363
     *  @return string                  Description
364
     */
365
    public function info($langs)
366
    {
367
        global $conf, $langs;
368
369
        // Load translation files required by the page
370
        $langs->loadLangs(array("companies", "errors"));
371
372
        $form = new Form($this->db);
373
374
        $texte = $this->description . ".<br>\n";
375
        $texte .= '<form action="' . $_SERVER["PHP_SELF"] . '" method="POST" enctype="multipart/form-data">';
376
        $texte .= '<input type="hidden" name="token" value="' . newToken() . '">';
377
        $texte .= '<input type="hidden" name="page_y" value="">';
378
        $texte .= '<input type="hidden" name="action" value="setModuleOptions">';
379
        $texte .= '<input type="hidden" name="param1" value="PROJECT_ADDON_PDF_ODT_PATH">';
380
        $texte .= '<table class="nobordernopadding centpercent">';
381
382
        // List of directories area
383
        $texte .= '<tr><td>';
384
        $texttitle = $langs->trans("ListOfDirectories");
385
        $listofdir = explode(',', preg_replace('/[\r\n]+/', ',', trim($conf->global->PROJECT_ADDON_PDF_ODT_PATH)));
386
        $listoffiles = array();
387
        foreach ($listofdir as $key => $tmpdir) {
388
            $tmpdir = trim($tmpdir);
389
            $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
390
            if (!$tmpdir) {
391
                unset($listofdir[$key]);
392
                continue;
393
            }
394
            if (!is_dir($tmpdir)) {
395
                $texttitle .= img_warning($langs->trans("ErrorDirNotFound", $tmpdir), 0);
396
            } else {
397
                $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.(ods|odt)');
398
                if (count($tmpfiles)) {
399
                    $listoffiles = array_merge($listoffiles, $tmpfiles);
400
                }
401
            }
402
        }
403
        $texthelp = $langs->trans("ListOfDirectoriesForModelGenODT");
404
        $texthelp .= '<br><br><span class="opacitymedium">' . $langs->trans("ExampleOfDirectoriesForModelGen") . '</span>';
405
        // Add list of substitution keys
406
        $texthelp .= '<br>' . $langs->trans("FollowingSubstitutionKeysCanBeUsed") . '<br>';
407
        $texthelp .= $langs->transnoentitiesnoconv("FullListOnOnlineDocumentation"); // This contains an url, we don't modify it
408
409
        $texte .= $form->textwithpicto($texttitle, $texthelp, 1, 'help', '', 1, 3, $this->name);
410
        $texte .= '<div><div style="display: inline-block; min-width: 100px; vertical-align: middle;">';
411
        $texte .= '<textarea class="flat" cols="60" name="value1">';
412
        $texte .= getDolGlobalString('PROJECT_ADDON_PDF_ODT_PATH');
413
        $texte .= '</textarea>';
414
        $texte .= '</div><div style="display: inline-block; vertical-align: middle;">';
415
        $texte .= '<input type="submit" class="button button-edit reposition smallpaddingimp" name="modify" value="' . dol_escape_htmltag($langs->trans("Modify")) . '">';
416
        $texte .= '<br></div></div>';
417
418
        // Scan directories
419
        $nbofiles = count($listoffiles);
420
        if (getDolGlobalString('PROJECT_ADDON_PDF_ODT_PATH')) {
421
            $texte .= $langs->trans("NumberOfModelFilesFound") . ': <b>';
422
            //$texte.=$nbofiles?'<a id="a_'.get_class($this).'" href="#">':'';
423
            $texte .= $nbofiles;
424
            //$texte.=$nbofiles?'</a>':'';
425
            $texte .= '</b>';
426
        }
427
428
        if ($nbofiles) {
429
            $texte .= '<div id="div_' . get_class($this) . '" class="hiddenx">';
430
            // Show list of found files
431
            foreach ($listoffiles as $file) {
432
                $texte .= '- ' . $file['name'] . ' <a href="' . constant('BASE_URL') . '/document.php?modulepart=doctemplates&file=projects/' . urlencode(basename($file['name'])) . '">' . img_picto('', 'listlight') . '</a>';
433
                $texte .= ' &nbsp; <a class="reposition" href="' . $_SERVER["PHP_SELF"] . '?modulepart=doctemplates&keyforuploaddir=PROJECT_ADDON_PDF_ODT_PATH&action=deletefile&token=' . newToken() . '&file=' . urlencode(basename($file['name'])) . '">' . img_picto('', 'delete') . '</a>';
434
                $texte .= '<br>';
435
            }
436
            $texte .= '</div>';
437
        }
438
        // Add input to upload a new template file.
439
        $texte .= '<div>' . $langs->trans("UploadNewTemplate");
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_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
460
    /**
461
     *  Function to build a document on disk using the generic odt module.
462
     *
463
     *  @param  Project     $object                 Object source to build document
464
     *  @param  Translate   $outputlangs            Lang output object
465
     *  @param  string      $srctemplatepath        Full path of source filename for generator using a template file
466
     *  @return int                                 1 if OK, <=0 if KO
467
     */
468
    public function write_file($object, $outputlangs, $srctemplatepath)
469
    {
470
		// phpcs:enable
471
        global $user, $langs, $conf, $mysoc, $hookmanager;
472
473
        if (empty($srctemplatepath)) {
474
            dol_syslog("doc_generic_odt::write_file parameter srctemplatepath empty", LOG_WARNING);
475
            return -1;
476
        }
477
478
        // Add odtgeneration hook
479
        if (!is_object($hookmanager)) {
480
            $hookmanager = new HookManager($this->db);
481
        }
482
        $hookmanager->initHooks(array('odtgeneration'));
483
        global $action;
484
485
        if (!is_object($outputlangs)) {
486
            $outputlangs = $langs;
487
        }
488
        $sav_charset_output = $outputlangs->charset_output;
489
        $outputlangs->charset_output = 'UTF-8';
490
491
        // Load translation files required by the page
492
        $outputlangs->loadLangs(array("main", "dict", "companies", "projects"));
493
494
        if ($conf->project->dir_output) {
495
            // If $object is id instead of object
496
            if (!is_object($object)) {
497
                $id = $object;
498
                $object = new Project($this->db);
499
                $result = $object->fetch($id);
500
                if ($result < 0) {
501
                    dol_print_error($this->db, $object->error);
502
                    return -1;
503
                }
504
            }
505
506
            $object->fetch_thirdparty();
507
508
            $dir = $conf->project->dir_output;
509
            $objectref = dol_sanitizeFileName($object->ref);
510
            if (!preg_match('/specimen/i', $objectref)) {
511
                $dir .= "/" . $objectref;
512
            }
513
            $file = $dir . "/" . $objectref . ".odt";
514
515
            if (!file_exists($dir)) {
516
                if (dol_mkdir($dir) < 0) {
517
                    $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir);
518
                    return -1;
519
                }
520
            }
521
522
            if (file_exists($dir)) {
523
                //print "srctemplatepath=".$srctemplatepath;    // Src filename
524
                $newfile = basename($srctemplatepath);
525
                $newfiletmp = preg_replace('/\.od[ts]/i', '', $newfile);
526
                $newfiletmp = preg_replace('/template_/i', '', $newfiletmp);
527
                $newfiletmp = preg_replace('/modele_/i', '', $newfiletmp);
528
                $newfiletmp = $objectref . '_' . $newfiletmp;
529
                //$file=$dir.'/'.$newfiletmp.'.'.dol_print_date(dol_now(),'%Y%m%d%H%M%S').'.odt';
530
                // Get extension (ods or odt)
531
                $newfileformat = substr($newfile, strrpos($newfile, '.') + 1);
532
                if (getDolGlobalString('MAIN_DOC_USE_TIMING')) {
533
                    $format = getDolGlobalString('MAIN_DOC_USE_TIMING');
534
                    if ($format == '1') {
535
                        $format = '%Y%m%d%H%M%S';
536
                    }
537
                    $filename = $newfiletmp . '-' . dol_print_date(dol_now(), $format) . '.' . $newfileformat;
538
                } else {
539
                    $filename = $newfiletmp . '.' . $newfileformat;
540
                }
541
                $file = $dir . '/' . $filename;
542
                //print "newdir=".$dir;
543
                //print "newfile=".$newfile;
544
                //print "file=".$file;
545
                //print "conf->societe->dir_temp=".$conf->societe->dir_temp;
546
547
                dol_mkdir($conf->project->dir_temp);
548
                if (!is_writable($conf->project->dir_temp)) {
549
                    $this->error = $langs->transnoentities("ErrorFailedToWriteInTempDirectory", $conf->project->dir_temp);
550
                    dol_syslog('Error in write_file: ' . $this->error, LOG_ERR);
551
                    return -1;
552
                }
553
554
                // If PROJECTLEADER contact defined on project, we use it
555
                $usecontact = false;
556
                $arrayidcontact = $object->getIdContact('external', 'PROJECTLEADER');
557
                if (count($arrayidcontact) > 0) {
558
                    $usecontact = true;
559
                    $result = $object->fetch_contact($arrayidcontact[0]);
560
                }
561
562
                // Recipient name
563
                $contactobject = null;
564
                if (!empty($usecontact)) {
565
                    // if we have a PROJECTLEADER contact and we don't use it as recipient we store the contact object for later use
566
                    $contactobject = $object->contact;
567
                }
568
569
                $socobject = $object->thirdparty;
570
571
                // Make substitution
572
                $substitutionarray = array(
573
                    '__FROM_NAME__' => $this->emetteur->name,
574
                    '__FROM_EMAIL__' => $this->emetteur->email,
575
                );
576
                complete_substitutions_array($substitutionarray, $langs, $object);
577
                // Call the ODTSubstitution hook
578
                $parameters = array('file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$substitutionarray);
579
                $reshook = $hookmanager->executeHooks('ODTSubstitution', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
580
581
                // Open and load template
582
                require_once ODTPHP_PATH . 'odf.php';
583
                try {
584
                    $odfHandler = new Odf(
585
                        $srctemplatepath,
586
                        array(
587
                            'PATH_TO_TMP'     => $conf->project->dir_temp,
588
                            'ZIP_PROXY'       => 'PclZipProxy', // PhpZipProxy or PclZipProxy. Got "bad compression method" error when using PhpZipProxy.
589
                            'DELIMITER_LEFT'  => '{',
590
                            'DELIMITER_RIGHT' => '}'
591
                        )
592
                    );
593
                } catch (Exception $e) {
594
                    $this->error = $e->getMessage();
595
                    dol_syslog($e->getMessage(), LOG_INFO);
596
                    return -1;
597
                }
598
                // After construction $odfHandler->contentXml contains content and
599
                // [!-- BEGIN row.lines --]*[!-- END row.lines --] has been replaced by
600
                // [!-- BEGIN lines --]*[!-- END lines --]
601
602
                // Define substitution array
603
                $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object);
604
                $array_object_from_properties = $this->get_substitutionarray_each_var_object($object, $outputlangs);
605
                $array_objet = $this->get_substitutionarray_object($object, $outputlangs);
606
                $array_user = $this->get_substitutionarray_user($user, $outputlangs);
607
                $array_soc = $this->get_substitutionarray_mysoc($mysoc, $outputlangs);
608
                $array_thirdparty = $this->get_substitutionarray_thirdparty($socobject, $outputlangs);
609
                $array_other = $this->get_substitutionarray_other($outputlangs);
610
                // retrieve contact information for use in object as contact_xxx tags
611
                $array_project_contact = array();
612
                if ($usecontact && is_object($contactobject)) {
613
                    $array_project_contact = $this->get_substitutionarray_contact($contactobject, $outputlangs, 'contact');
614
                }
615
616
                $tmparray = array_merge($substitutionarray, $array_object_from_properties, $array_user, $array_soc, $array_thirdparty, $array_objet, $array_other, $array_project_contact);
617
                complete_substitutions_array($tmparray, $outputlangs, $object);
618
619
                // Call the ODTSubstitution hook
620
                $parameters = array('odfHandler' => &$odfHandler, 'file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$tmparray);
621
                $reshook = $hookmanager->executeHooks('ODTSubstitution', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
622
623
                foreach ($tmparray as $key => $value) {
624
                    try {
625
                        if (preg_match('/logo$/', $key)) { // Image
626
                            if (file_exists($value)) {
627
                                $odfHandler->setImage($key, $value);
628
                            } else {
629
                                $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8');
630
                            }
631
                        } else { // Text
632
                            $odfHandler->setVars($key, $value, true, 'UTF-8');
633
                        }
634
                    } catch (OdfException $e) {
635
                        dol_syslog($e->getMessage(), LOG_INFO);
636
                    }
637
                }
638
639
                // Replace tags of lines for tasks
640
                try {
641
                    $listlines = $odfHandler->setSegment('tasks');
642
643
                    $taskstatic = new Task($this->db);
644
645
                    // Security check
646
                    $socid = 0;
647
                    if (!empty($object->fk_soc)) {
648
                        $socid = $object->fk_soc;
649
                    }
650
651
                    $tasksarray = $taskstatic->getTasksArray(0, 0, $object->id, $socid, 0);
652
653
654
                    foreach ($tasksarray as $task) {
655
                        $tmparray = $this->get_substitutionarray_tasks($task, $outputlangs);
656
                        //complete_substitutions_array($tmparray, $outputlangs, $object, $task, "completesubstitutionarray_lines");
657
                        foreach ($tmparray as $key => $val) {
658
                            try {
659
                                $listlines->setVars($key, $val, true, 'UTF-8');
660
                            } catch (SegmentException $e) {
661
                                dol_syslog($e->getMessage(), LOG_INFO);
662
                            }
663
                        }
664
665
                        $taskobj = new Task($this->db);
666
                        $taskobj->fetch($task->id);
667
668
                        // Replace tags of lines for contacts task
669
                        $sourcearray = array('internal', 'external');
670
                        $contact_arrray = array();
671
                        foreach ($sourcearray as $source) {
672
                            $contact_temp = $taskobj->liste_contact(-1, $source);
673
                            if ((is_array($contact_temp) && count($contact_temp) > 0)) {
674
                                $contact_arrray = array_merge($contact_arrray, $contact_temp);
675
                            }
676
                        }
677
                        if ((is_array($contact_arrray) && count($contact_arrray) > 0)) {
678
                            $listlinestaskres = $listlines->__get('tasksressources');
679
680
                            foreach ($contact_arrray as $contact) {
681
                                if ($contact['source'] == 'internal') {
682
                                    $objectdetail = new User($this->db);
683
                                    $objectdetail->fetch($contact['id']);
684
                                    $contact['socname'] = $mysoc->name;
685
                                } elseif ($contact['source'] == 'external') {
686
                                    $objectdetail = new Contact($this->db);
687
                                    $objectdetail->fetch($contact['id']);
688
689
                                    $soc = new Societe($this->db);
690
                                    $soc->fetch($contact['socid']);
691
                                    $contact['socname'] = $soc->name;
692
                                }
693
                                $contact['fullname'] = $objectdetail->getFullName($outputlangs, 1);
694
695
                                $tmparray = $this->get_substitutionarray_tasksressource($contact, $outputlangs);
696
697
                                foreach ($tmparray as $key => $val) {
698
                                    try {
699
                                        $listlinestaskres->setVars($key, $val, true, 'UTF-8');
700
                                    } catch (SegmentException $e) {
701
                                        dol_syslog($e->getMessage(), LOG_INFO);
702
                                    }
703
                                }
704
                                $listlinestaskres->merge();
705
                            }
706
                        }
707
708
                        //Time resources
709
                        $sql = "SELECT t.rowid, t.element_date as task_date, t.element_duration as task_duration, t.fk_user, t.note";
710
                        $sql .= ", u.lastname, u.firstname, t.thm";
711
                        $sql .= " FROM " . MAIN_DB_PREFIX . "element_time as t";
712
                        $sql .= " , " . MAIN_DB_PREFIX . "user as u";
713
                        $sql .= " WHERE t.fk_element =" . ((int) $task->id);
714
                        $sql .= " AND t.elementtype = 'task'";
715
                        $sql .= " AND t.fk_user = u.rowid";
716
                        $sql .= " ORDER BY t.element_date DESC";
717
718
                        $resql = $this->db->query($sql);
719
                        if ($resql) {
720
                            $num = $this->db->num_rows($resql);
721
                            $i = 0;
722
                            $tasks = array();
723
                            $row = array();
724
                            $listlinestasktime = $listlines->__get('taskstimes');
725
                            if (empty($num)) {
726
                                $row['rowid'] = '';
727
                                $row['task_date'] = '';
728
                                $row['task_duration'] = '';
729
                                $row['$tasktime'] = '';
730
                                $row['note'] = '';
731
                                $row['fk_user'] = '';
732
                                $row['name'] = '';
733
                                $row['firstname'] = '';
734
                                $row['fullcivname'] = '';
735
                                $row['amountht'] = '';
736
                                $row['amountttc'] = '';
737
                                $row['thm'] = '';
738
                                $tmparray = $this->get_substitutionarray_taskstime($row, $outputlangs);
739
                                foreach ($tmparray as $key => $val) {
740
                                    try {
741
                                        $listlinestasktime->setVars($key, $val, true, 'UTF-8');
742
                                    } catch (SegmentException $e) {
743
                                        dol_syslog($e->getMessage(), LOG_INFO);
744
                                    }
745
                                }
746
                                $listlinestasktime->merge();
747
                            }
748
                            while ($i < $num) {
749
                                $row = $this->db->fetch_array($resql);
750
                                if (!empty($row['fk_user'])) {
751
                                    $objectdetail = new User($this->db);
752
                                    $objectdetail->fetch($row['fk_user']);
753
                                    $row['fullcivname'] = $objectdetail->getFullName($outputlangs, 1);
754
                                } else {
755
                                    $row['fullcivname'] = '';
756
                                }
757
758
                                if (!empty($row['thm'])) {
759
                                    $row['amountht'] = ($row['task_duration'] / 3600) * $row['thm'];
760
                                    $defaultvat = get_default_tva($mysoc, $mysoc);
761
                                    $row['amountttc'] = price2num($row['amountht'] * (1 + ($defaultvat / 100)), 'MT');
762
                                } else {
763
                                    $row['amountht'] = 0;
764
                                    $row['amountttc'] = 0;
765
                                    $row['thm'] = 0;
766
                                }
767
768
                                $tmparray = $this->get_substitutionarray_taskstime($row, $outputlangs);
769
770
                                foreach ($tmparray as $key => $val) {
771
                                    try {
772
                                        $listlinestasktime->setVars($key, $val, true, 'UTF-8');
773
                                    } catch (SegmentException $e) {
774
                                        dol_syslog($e->getMessage(), LOG_INFO);
775
                                    }
776
                                }
777
                                $listlinestasktime->merge();
778
                                $i++;
779
                            }
780
                            $this->db->free($resql);
781
                        }
782
783
784
                        // Replace tags of project files
785
                        $listtasksfiles = $listlines->__get('tasksfiles');
786
787
                        $upload_dir = $conf->project->dir_output . '/' . dol_sanitizeFileName($object->ref) . '/' . dol_sanitizeFileName($task->ref);
788
                        $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', 'name', SORT_ASC, 1);
789
790
791
                        foreach ($filearray as $filedetail) {
792
                            $tmparray = $this->get_substitutionarray_task_file($filedetail, $outputlangs);
793
                            //dol_syslog(get_class($this).'::main $tmparray'.var_export($tmparray,true));
794
                            foreach ($tmparray as $key => $val) {
795
                                try {
796
                                    $listtasksfiles->setVars($key, $val, true, 'UTF-8');
797
                                } catch (SegmentException $e) {
798
                                    dol_syslog($e->getMessage(), LOG_INFO);
799
                                }
800
                            }
801
                            $listtasksfiles->merge();
802
                        }
803
                        $listlines->merge();
804
                    }
805
                    $odfHandler->mergeSegment($listlines);
806
                } catch (OdfException $e) {
807
                    $ExceptionTrace = $e->getTrace();
808
                    // no segment defined on ODT is not an error
809
                    if ($ExceptionTrace[0]['function'] != 'setSegment') {
810
                        $this->error = $e->getMessage();
811
                        dol_syslog($this->error, LOG_WARNING);
812
                        return -1;
813
                    }
814
                }
815
816
                // Replace tags of project files
817
                try {
818
                    $listlines = $odfHandler->setSegment('projectfiles');
819
820
                    $upload_dir = $conf->project->dir_output . '/' . dol_sanitizeFileName($object->ref);
821
                    $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', 'name', SORT_ASC, 1);
822
823
                    foreach ($filearray as $filedetail) {
824
                        //dol_syslog(get_class($this).'::main $filedetail'.var_export($filedetail,true));
825
                        $tmparray = $this->get_substitutionarray_project_file($filedetail, $outputlangs);
826
827
                        foreach ($tmparray as $key => $val) {
828
                            try {
829
                                $listlines->setVars($key, $val, true, 'UTF-8');
830
                            } catch (SegmentException $e) {
831
                                dol_syslog($e->getMessage(), LOG_INFO);
832
                            }
833
                        }
834
                        $listlines->merge();
835
                    }
836
                    $odfHandler->mergeSegment($listlines);
837
                } catch (OdfException $e) {
838
                    $this->error = $e->getMessage();
839
                    dol_syslog($this->error, LOG_WARNING);
840
                    return -1;
841
                }
842
843
                // Replace tags of lines for contacts
844
                $sourcearray = array('internal', 'external');
845
                $contact_arrray = array();
846
                foreach ($sourcearray as $source) {
847
                    $contact_temp = $object->liste_contact(-1, $source);
848
                    if ((is_array($contact_temp) && count($contact_temp) > 0)) {
849
                        $contact_arrray = array_merge($contact_arrray, $contact_temp);
850
                    }
851
                }
852
                if ((is_array($contact_arrray) && count($contact_arrray) > 0)) {
853
                    try {
854
                        $listlines = $odfHandler->setSegment('projectcontacts');
855
856
                        foreach ($contact_arrray as $contact) {
857
                            if ($contact['source'] == 'internal') {
858
                                $objectdetail = new User($this->db);
859
                                $objectdetail->fetch($contact['id']);
860
                                $contact['socname'] = $mysoc->name;
861
                            } elseif ($contact['source'] == 'external') {
862
                                $objectdetail = new Contact($this->db);
863
                                $objectdetail->fetch($contact['id']);
864
865
                                $soc = new Societe($this->db);
866
                                $soc->fetch($contact['socid']);
867
                                $contact['socname'] = $soc->name;
868
                            }
869
                            $contact['fullname'] = $objectdetail->getFullName($outputlangs, 1);
870
871
                            $tmparray = $this->get_substitutionarray_project_contacts($contact, $outputlangs);
872
                            foreach ($tmparray as $key => $val) {
873
                                try {
874
                                    $listlines->setVars($key, $val, true, 'UTF-8');
875
                                } catch (SegmentException $e) {
876
                                    dol_syslog($e->getMessage(), LOG_INFO);
877
                                }
878
                            }
879
                            $listlines->merge();
880
                        }
881
                        $odfHandler->mergeSegment($listlines);
882
                    } catch (OdfException $e) {
883
                        $this->error = $e->getMessage();
884
                        dol_syslog($this->error, LOG_WARNING);
885
                        return -1;
886
                    }
887
                }
888
889
                //List of referent
890
891
                $listofreferent = array(
892
                    'propal' => array(
893
                        'title' => "ListProposalsAssociatedProject",
894
                        'class' => 'Propal',
895
                        'table' => 'propal',
896
                        'test' => isModEnabled('propal') && $user->hasRight('propal', 'lire')
897
                    ),
898
                    'order' => array(
899
                        'title' => "ListOrdersAssociatedProject",
900
                        'class' => 'Commande',
901
                        'table' => 'commande',
902
                        'test' => isModEnabled('order') && $user->hasRight('commande', 'lire')
903
                    ),
904
                    'invoice' => array(
905
                        'title' => "ListInvoicesAssociatedProject",
906
                        'class' => 'Facture',
907
                        'table' => 'facture',
908
                        'test' => isModEnabled('invoice') && $user->hasRight('facture', 'lire')
909
                    ),
910
                    'invoice_predefined' => array(
911
                        'title' => "ListPredefinedInvoicesAssociatedProject",
912
                        'class' => 'FactureRec',
913
                        'table' => 'facture_rec',
914
                        'test' => isModEnabled('invoice') && $user->hasRight('facture', 'lire')
915
                    ),
916
                    'proposal_supplier' => array(
917
                        'title' => "ListSupplierProposalsAssociatedProject",
918
                        'class' => 'SupplierProposal',
919
                        'table' => 'supplier_proposal',
920
                        'test' => isModEnabled('supplier_proposal') && $user->hasRight('supplier_proposal', 'lire')
921
                    ),
922
                    'order_supplier' => array(
923
                        'title' => "ListSupplierOrdersAssociatedProject",
924
                        'table' => 'commande_fournisseur',
925
                        'class' => 'CommandeFournisseur',
926
                        'test' => (isModEnabled("fournisseur") && !getDolGlobalString('MAIN_USE_NEW_SUPPLIERMOD') && $user->hasRight('fournisseur', 'commande', 'lire')) || (isModEnabled("supplier_order") && $user->hasRight('supplier_order', 'lire'))
927
                    ),
928
                    'invoice_supplier' => array(
929
                        'title' => "ListSupplierInvoicesAssociatedProject",
930
                        'table' => 'facture_fourn',
931
                        'class' => 'FactureFournisseur',
932
                        'test' => (isModEnabled("fournisseur") && !getDolGlobalString('MAIN_USE_NEW_SUPPLIERMOD') && $user->hasRight('fournisseur', 'facture', 'lire')) || (isModEnabled("supplier_invoice") && $user->hasRight('supplier_invoice', 'lire'))
933
                    ),
934
                    'contract' => array(
935
                        'title' => "ListContractAssociatedProject",
936
                        'class' => 'Contrat',
937
                        'table' => 'contrat',
938
                        'test' => isModEnabled('contract') && $user->hasRight('contrat', 'lire')
939
                    ),
940
                    'intervention' => array(
941
                        'title' => "ListFichinterAssociatedProject",
942
                        'class' => 'Fichinter',
943
                        'table' => 'fichinter',
944
                        'disableamount' => 1,
945
                        'test' => isModEnabled('intervention') && $user->hasRight('ficheinter', 'lire')
946
                    ),
947
                    'shipping' => array(
948
                        'title' => "ListShippingAssociatedProject",
949
                        'class' => 'Expedition',
950
                        'table' => 'expedition',
951
                        'disableamount' => 1,
952
                        'test' => isModEnabled('shipping') && $user->hasRight('expedition', 'lire')
953
                    ),
954
                    'trip' => array(
955
                        'title' => "ListTripAssociatedProject",
956
                        'class' => 'Deplacement',
957
                        'table' => 'deplacement',
958
                        'disableamount' => 1,
959
                        'test' => isModEnabled('deplacement') && $user->hasRight('deplacement', 'lire')
960
                    ),
961
                    'expensereport' => array(
962
                        'title' => "ListExpenseReportsAssociatedProject",
963
                        'class' => 'ExpenseReportLine',
964
                        'table' => 'expensereport_det',
965
                        'test' => isModEnabled('expensereport') && $user->hasRight('expensereport', 'lire')
966
                    ),
967
                    'donation' => array(
968
                        'title' => "ListDonationsAssociatedProject",
969
                        'class' => 'Don',
970
                        'table' => 'don',
971
                        'test' => isModEnabled('don') && $user->hasRight('don', 'lire')
972
                    ),
973
                    'loan' => array(
974
                        'title' => "ListLoanAssociatedProject",
975
                        'class' => 'Loan',
976
                        'table' => 'loan',
977
                        'test' => isModEnabled('loan') && $user->hasRight('loan', 'read')
978
                    ),
979
                    'chargesociales' => array(
980
                        'title' => "ListSocialContributionAssociatedProject",
981
                        'class' => 'ChargeSociales',
982
                        'table' => 'chargesociales',
983
                        'urlnew' => constant('BASE_URL') . '/compta/sociales/card.php?action=create&projectid=' . $object->id,
984
                        'test' => isModEnabled('tax') && $user->hasRight('tax', 'charges', 'lire')
985
                    ),
986
                    'stock_mouvement' => array(
987
                        'title' => "ListMouvementStockProject",
988
                        'class' => 'MouvementStock',
989
                        'table' => 'stock_mouvement',
990
                        'test' => (isModEnabled('stock') && $user->hasRight('stock', 'mouvement', 'lire') && getDolGlobalString('STOCK_MOVEMENT_INTO_PROJECT_OVERVIEW'))
991
                    ),
992
                    'agenda' => array(
993
                        'title' => "ListActionsAssociatedProject",
994
                        'class' => 'ActionComm',
995
                        'table' => 'actioncomm',
996
                        'disableamount' => 1,
997
                        'test' => isModEnabled('agenda') && $user->hasRight('agenda', 'allactions', 'lire')
998
                    ),
999
                );
1000
1001
                // Insert list of objects into the project
1002
                try {
1003
                    $listlines = $odfHandler->setSegment('projectrefs');
1004
1005
                    foreach ($listofreferent as $keyref => $valueref) {
1006
                        $title = $valueref['title'];
1007
                        $tablename = $valueref['table'];
1008
                        $classname = $valueref['class'];
1009
                        $qualified = $valueref['test'];
1010
                        if ($qualified) {
1011
                            $elementarray = $object->get_element_list($keyref, $tablename);
1012
                            if (count($elementarray) > 0 && is_array($elementarray)) {
1013
                                $total_ht = 0;
1014
                                $total_ttc = 0;
1015
                                $num = count($elementarray);
1016
                                for ($i = 0; $i < $num; $i++) {
1017
                                    $ref_array = array();
1018
                                    $ref_array['type'] = $langs->trans($classname);
1019
1020
                                    $element = new $classname($this->db);
1021
                                    $element->fetch($elementarray[$i]);
1022
                                    $element->fetch_thirdparty();
1023
1024
                                    //Ref object
1025
                                    $ref_array['ref'] = $element->ref;
1026
1027
                                    //Date object
1028
                                    $dateref = $element->date;
1029
                                    if (empty($dateref)) {
1030
                                        $dateref = $element->datep;
1031
                                    }
1032
                                    if (empty($dateref)) {
1033
                                        $dateref = $element->date_contrat;
1034
                                    }
1035
                                    $ref_array['date'] = $dateref;
1036
1037
                                    //Soc object
1038
                                    if (is_object($element->thirdparty)) {
1039
                                        $ref_array['socname'] = $element->thirdparty->name;
1040
                                    } else {
1041
                                        $ref_array['socname'] = '';
1042
                                    }
1043
1044
                                    //Amount object
1045
                                    if (empty($valueref['disableamount'])) {
1046
                                        if (!empty($element->total_ht)) {
1047
                                            $ref_array['amountht'] = $element->total_ht;
1048
                                            $ref_array['amountttc'] = $element->total_ttc;
1049
                                        } else {
1050
                                            $ref_array['amountht'] = 0;
1051
                                            $ref_array['amountttc'] = 0;
1052
                                        }
1053
                                    } else {
1054
                                        $ref_array['amountht'] = '';
1055
                                        $ref_array['amountttc'] = '';
1056
                                    }
1057
1058
                                    $ref_array['status'] = $element->getLibStatut(0);
1059
1060
                                    $tmparray = $this->get_substitutionarray_project_reference($ref_array, $outputlangs);
1061
1062
                                    foreach ($tmparray as $key => $val) {
1063
                                        try {
1064
                                            $listlines->setVars($key, $val, true, 'UTF-8');
1065
                                        } catch (SegmentException $e) {
1066
                                            dol_syslog($e->getMessage(), LOG_INFO);
1067
                                        }
1068
                                    }
1069
                                    $listlines->merge();
1070
                                }
1071
                            }
1072
                        }
1073
                        $odfHandler->mergeSegment($listlines);
1074
                    }
1075
                } catch (OdfExceptionSegmentNotFound $e) {
1076
                    // Do nothing
1077
                } catch (OdfException $e) {
1078
                    $this->error = $e->getMessage();
1079
                    dol_syslog($this->error, LOG_WARNING);
1080
                    return -1;
1081
                }
1082
1083
                // Replace labels translated
1084
                $tmparray = $outputlangs->get_translations_for_substitutions();
1085
                foreach ($tmparray as $key => $value) {
1086
                    try {
1087
                        $odfHandler->setVars($key, $value, true, 'UTF-8');
1088
                    } catch (OdfException $e) {
1089
                        dol_syslog($e->getMessage(), LOG_INFO);
1090
                    }
1091
                }
1092
1093
                // Call the beforeODTSave hook
1094
                $parameters = array('odfHandler' => &$odfHandler, 'file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$tmparray);
1095
                $reshook = $hookmanager->executeHooks('beforeODTSave', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1096
1097
1098
                // Write new file
1099
                if (getDolGlobalString('MAIN_ODT_AS_PDF')) {
1100
                    try {
1101
                        $odfHandler->exportAsAttachedPDF($file);
1102
                    } catch (Exception $e) {
1103
                        $this->error = $e->getMessage();
1104
                        return -1;
1105
                    }
1106
                } else {
1107
                    try {
1108
                        $odfHandler->saveToDisk($file);
1109
                    } catch (Exception $e) {
1110
                        $this->error = $e->getMessage();
1111
                        dol_syslog($e->getMessage(), LOG_INFO);
1112
                        return -1;
1113
                    }
1114
                }
1115
                $parameters = array('odfHandler' => &$odfHandler, 'file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$tmparray);
1116
                $reshook = $hookmanager->executeHooks('afterODTCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1117
1118
                dolChmod($file);
1119
1120
                $odfHandler = null; // Destroy object
1121
1122
                $this->result = array('fullpath' => $file);
1123
1124
                return 1; // Success
1125
            } else {
1126
                $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir);
1127
                return -1;
1128
            }
1129
        }
1130
1131
        return -1;
1132
    }
1133
}
1134