Passed
Push — main ( f1540e...02d90d )
by Rafael
45:15
created

doc_generic_contract_odt   B

Complexity

Total Complexity 52

Size/Duplication

Total Lines 457
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 273
dl 0
loc 457
rs 7.44
c 0
b 0
f 0
wmc 52

3 Methods

Rating   Name   Duplication   Size   Complexity  
F write_file() 0 291 41
B info() 0 93 9
A __construct() 0 36 2

How to fix   Complexity   

Complex Class

Complex classes like doc_generic_contract_odt often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use doc_generic_contract_odt, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/* Copyright (C) 2010-2012  Laurent Destailleur <[email protected]>
4
 * Copyright (C) 2012		Juanjo Menent		<[email protected]>
5
 * Copyright (C) 2018		Ferran Marcet		<[email protected]>
6
 * Copyright (C) 2018-2019  Frédéric France         <[email protected]>
7
 *
8
* This program is free software; you can redistribute it and/or modify
9
* it under the terms of the GNU General Public License as published by
10
* the Free Software Foundation; either version 3 of the License, or
11
* (at your option) any later version.
12
*
13
* This program is distributed in the hope that it will be useful,
14
* but WITHOUT ANY WARRANTY; without even the implied warranty of
15
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
* GNU General Public License for more details.
17
*
18
* You should have received a copy of the GNU General Public License
19
* along with this program. If not, see <https://www.gnu.org/licenses/>.
20
* or see https://www.gnu.org/
21
*/
22
23
/**
24
 *  \file       htdocs/core/modules/contract/doc/doc_generic_contract_odt.modules.php
25
 *  \ingroup    societe
26
 *  \brief      File of class to build ODT documents for third parties
27
 */
28
29
require_once DOL_DOCUMENT_ROOT . '/core/modules/contract/modules_contract.php';
30
require_once BASE_PATH . '/../Dolibarr/Lib/Company.php';
31
require_once BASE_PATH . '/../Dolibarr/Lib/Functions2.php';
32
require_once BASE_PATH . '/../Dolibarr/Lib/Files.php';
33
require_once BASE_PATH . '/../Dolibarr/Lib/Doc.php';
34
35
36
/**
37
 *  Class to build documents using ODF templates generator
38
 */
39
class doc_generic_contract_odt extends ModelePDFContract
40
{
41
    /**
42
     * @var string Dolibarr version of the loaded document
43
     */
44
    public $version = 'dolibarr';
45
46
47
    /**
48
     *  Constructor
49
     *
50
     *  @param      DoliDB      $db      Database handler
51
     */
52
    public function __construct($db)
53
    {
54
        global $conf, $langs, $mysoc;
55
56
        // Load translation files required by the page
57
        $langs->loadLangs(array("main", "companies"));
58
59
        $this->db = $db;
60
        $this->name = "ODT templates";
61
        $this->description = $langs->trans("DocumentModelOdt");
62
        $this->scandir = 'CONTRACT_ADDON_PDF_ODT_PATH'; // Name of constant that is used to save list of directories to scan
63
64
        // Page size for A4 format
65
        $this->type = 'odt';
66
        $this->page_largeur = 0;
67
        $this->page_hauteur = 0;
68
        $this->format = array($this->page_largeur, $this->page_hauteur);
69
        $this->marge_gauche = 0;
70
        $this->marge_droite = 0;
71
        $this->marge_haute = 0;
72
        $this->marge_basse = 0;
73
74
        $this->option_logo = 1; // Display logo
75
        $this->option_tva = 0; // Manage the vat CONTRACT_TVAOPTION
76
        $this->option_modereg = 0; // Display payment mode
77
        $this->option_condreg = 0; // Display payment terms
78
        $this->option_multilang = 1; // Available in several languages
79
        $this->option_escompte = 0; // Displays if there has been a discount
80
        $this->option_credit_note = 0; // Support credit notes
81
        $this->option_freetext = 1; // Support add of a personalised text
82
        $this->option_draft_watermark = 0; // Support add of a watermark on drafts
83
84
        // Get source company
85
        $this->emetteur = $mysoc;
86
        if (!$this->emetteur->country_code) {
87
            $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default if not defined
88
        }
89
    }
90
91
92
    /**
93
     *  Return description of a module
94
     *
95
     *  @param  Translate   $langs      Lang object to use for output
96
     *  @return string                  Description
97
     */
98
    public function info($langs)
99
    {
100
        global $conf, $langs;
101
102
        // Load translation files required by the page
103
        $langs->loadLangs(array('companies', 'errors'));
104
105
        $form = new Form($this->db);
106
107
        $texte = $this->description . ".<br>\n";
108
        $texte .= '<form action="' . $_SERVER['PHP_SELF'] . '" method="POST" enctype="multipart/form-data">';
109
        $texte .= '<input type="hidden" name="token" value="' . newToken() . '">';
110
        $texte .= '<input type="hidden" name="page_y" value="">';
111
        $texte .= '<input type="hidden" name="action" value="setModuleOptions">';
112
        $texte .= '<input type="hidden" name="param1" value="CONTRACT_ADDON_PDF_ODT_PATH">';
113
        $texte .= '<table class="nobordernopadding centpercent">';
114
115
        // List of directories area
116
        $texte .= '<tr><td>';
117
        $texttitle = $langs->trans("ListOfDirectories");
118
        $listofdir = explode(',', preg_replace('/[\r\n]+/', ',', trim($conf->global->CONTRACT_ADDON_PDF_ODT_PATH)));
119
        $listoffiles = array();
120
        foreach ($listofdir as $key => $tmpdir) {
121
            $tmpdir = trim($tmpdir);
122
            $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
123
            if (!$tmpdir) {
124
                unset($listofdir[$key]);
125
                continue;
126
            }
127
            if (!is_dir($tmpdir)) {
128
                $texttitle .= img_warning($langs->trans("ErrorDirNotFound", $tmpdir), 0);
129
            } else {
130
                $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.(ods|odt)');
131
                if (count($tmpfiles)) {
132
                    $listoffiles = array_merge($listoffiles, $tmpfiles);
133
                }
134
            }
135
        }
136
        $texthelp = $langs->trans("ListOfDirectoriesForModelGenODT");
137
        $texthelp .= '<br><br><span class="opacitymedium">' . $langs->trans("ExampleOfDirectoriesForModelGen") . '</span>';
138
        // Add list of substitution keys
139
        $texthelp .= '<br>' . $langs->trans("FollowingSubstitutionKeysCanBeUsed") . '<br>';
140
        $texthelp .= $langs->transnoentitiesnoconv("FullListOnOnlineDocumentation"); // This contains an url, we don't modify it
141
142
        $texte .= $form->textwithpicto($texttitle, $texthelp, 1, 'help', '', 1, 3, $this->name);
143
        $texte .= '<div><div style="display: inline-block; min-width: 100px; vertical-align: middle;">';
144
        $texte .= '<textarea class="flat" cols="60" name="value1">';
145
        $texte .= getDolGlobalString('CONTRACT_ADDON_PDF_ODT_PATH');
146
        $texte .= '</textarea>';
147
        $texte .= '</div><div style="display: inline-block; vertical-align: middle;">';
148
        $texte .= '<input type="submit" class="button reposition smallpaddingimp" value="' . dol_escape_htmltag($langs->trans("Upload")) . '" name="upload">';
149
        $texte .= '<br></div></div>';
150
151
        // Scan directories
152
        $nbofiles = count($listoffiles);
153
        if (getDolGlobalString('CONTRACT_ADDON_PDF_ODT_PATH')) {
154
            $texte .= $langs->trans("NumberOfModelFilesFound") . ': <b>';
155
            //$texte.=$nbofiles?'<a id="a_'.get_class($this).'" href="#">':'';
156
            $texte .= count($listoffiles);
157
            //$texte.=$nbofiles?'</a>':'';
158
            $texte .= '</b>';
159
        }
160
161
        if ($nbofiles) {
162
            $texte .= '<div id="div_' . get_class($this) . '" class="hiddenx">';
163
            // Show list of found files
164
            foreach ($listoffiles as $file) {
165
                $texte .= '- ' . $file['name'] . ' <a href="' . DOL_URL_ROOT . '/document.php?modulepart=doctemplates&file=contracts/' . urlencode(basename($file['name'])) . '">' . img_picto('', 'listlight') . '</a>';
166
                $texte .= ' &nbsp; <a class="reposition" href="' . $_SERVER['PHP_SELF'] . '?modulepart=doctemplates&keyforuploaddir=CONTRACT_ADDON_PDF_ODT_PATH&action=deletefile&token=' . newToken() . '&file=' . urlencode(basename($file['name'])) . '">' . img_picto('', 'delete') . '</a>';
167
                $texte .= '<br>';
168
            }
169
            $texte .= '</div>';
170
        }
171
        // Add input to upload a new template file.
172
        $texte .= '<div>' . $langs->trans("UploadNewTemplate");
173
        $maxfilesizearray = getMaxFileSizeArray();
174
        $maxmin = $maxfilesizearray['maxmin'];
175
        if ($maxmin > 0) {
176
            $texte .= '<input type="hidden" name="MAX_FILE_SIZE" value="' . ($maxmin * 1024) . '">';    // MAX_FILE_SIZE must precede the field type=file
177
        }
178
        $texte .= ' <input type="file" name="uploadfile">';
179
        $texte .= '<input type="hidden" value="CONTRACT_ADDON_PDF_ODT_PATH" name="keyforuploaddir">';
180
        $texte .= '<input type="submit" class="button reposition smallpaddingimp" value="' . dol_escape_htmltag($langs->trans("Upload")) . '" name="upload">';
181
        $texte .= '</div>';
182
183
        $texte .= '</td>';
184
185
        $texte .= '</tr>';
186
187
        $texte .= '</table>';
188
        $texte .= '</form>';
189
190
        return $texte;
191
    }
192
193
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
194
    /**
195
     *  Function to build a document on disk using the generic odt module.
196
     *
197
     *  @param      Contrat     $object             Object source to build document
198
     *  @param      Translate   $outputlangs        Lang output object
199
     *  @param      string      $srctemplatepath    Full path of source filename for generator using a template file
200
     *  @param      int         $hidedetails        Do not show line details
201
     *  @param      int         $hidedesc           Do not show desc
202
     *  @param      int         $hideref            Do not show ref
203
     *  @return     int                             1 if OK, <=0 if KO
204
     */
205
    public function write_file($object, $outputlangs, $srctemplatepath, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
206
    {
207
		// phpcs:enable
208
        global $user, $langs, $conf, $mysoc, $hookmanager;
209
210
        if (empty($srctemplatepath)) {
211
            dol_syslog("doc_generic_odt::write_file parameter srctemplatepath empty", LOG_WARNING);
212
            return -1;
213
        }
214
215
        // Add odtgeneration hook
216
        if (!is_object($hookmanager)) {
217
            include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
218
            $hookmanager = new HookManager($this->db);
219
        }
220
        $hookmanager->initHooks(array('odtgeneration'));
221
        global $action;
222
223
        if (!is_object($outputlangs)) {
224
            $outputlangs = $langs;
225
        }
226
        $sav_charset_output = $outputlangs->charset_output;
227
        $outputlangs->charset_output = 'UTF-8';
228
229
        // Load translation files required by page
230
        $outputlangs->loadLangs(array("main", "dict", "companies", "bills"));
231
232
        if ($conf->contrat->multidir_output[$object->entity]) {
233
            // If $object is id instead of object
234
            if (!is_object($object)) {
235
                $id = $object;
236
                $object = new Contrat($this->db);
237
                $result = $object->fetch($id);
238
                if ($result < 0) {
239
                    dol_print_error($this->db, $object->error);
240
                    return -1;
241
                }
242
            }
243
244
            $object->fetch_thirdparty();
245
246
            $dir = $conf->contrat->multidir_output[$object->entity];
247
            $objectref = dol_sanitizeFileName($object->ref);
248
            if (!preg_match('/specimen/i', $objectref)) {
249
                $dir .= "/" . $objectref;
250
            }
251
            $file = $dir . "/" . $objectref . ".odt";
252
253
            if (!file_exists($dir)) {
254
                if (dol_mkdir($dir) < 0) {
255
                    $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir);
256
                    return -1;
257
                }
258
            }
259
260
            if (file_exists($dir)) {
261
                //print "srctemplatepath=".$srctemplatepath;    // Src filename
262
                $newfile = basename($srctemplatepath);
263
                $newfiletmp = preg_replace('/\.od[ts]/i', '', $newfile);
264
                $newfiletmp = preg_replace('/template_/i', '', $newfiletmp);
265
                $newfiletmp = preg_replace('/modele_/i', '', $newfiletmp);
266
267
                $newfiletmp = $objectref . '_' . $newfiletmp;
268
269
                // Get extension (ods or odt)
270
                $newfileformat = substr($newfile, strrpos($newfile, '.') + 1);
271
                if (getDolGlobalString('MAIN_DOC_USE_TIMING')) {
272
                    $format = getDolGlobalString('MAIN_DOC_USE_TIMING');
273
                    if ($format == '1') {
274
                        $format = '%Y%m%d%H%M%S';
275
                    }
276
                    $filename = $newfiletmp . '-' . dol_print_date(dol_now(), $format) . '.' . $newfileformat;
277
                } else {
278
                    $filename = $newfiletmp . '.' . $newfileformat;
279
                }
280
                $file = $dir . '/' . $filename;
281
                //print "newdir=".$dir;
282
                //print "newfile=".$newfile;
283
                //print "file=".$file;
284
                //print "conf->contrat->dir_temp=".$conf->contrat->dir_temp;
285
286
                dol_mkdir($conf->contrat->dir_temp);
287
                if (!is_writable($conf->contrat->dir_temp)) {
288
                    $this->error = $langs->transnoentities("ErrorFailedToWriteInTempDirectory", $conf->contrat->dir_temp);
289
                    dol_syslog('Error in write_file: ' . $this->error, LOG_ERR);
290
                    return -1;
291
                }
292
293
                // If CUSTOMER contact defined on contract, we use it
294
                $usecontact = false;
295
                $arrayidcontact = $object->getIdContact('external', 'CUSTOMER');
296
                if (count($arrayidcontact) > 0) {
297
                    $usecontact = true;
298
                    $result = $object->fetch_contact($arrayidcontact[0]);
299
                }
300
301
                // Recipient name
302
                $contactobject = null;
303
                if (!empty($usecontact)) {
304
                    // We can use the company of contact instead of thirdparty company
305
                    if ($object->contact->socid != $object->thirdparty->id && (!isset($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT) || getDolGlobalString('MAIN_USE_COMPANY_NAME_OF_CONTACT'))) {
306
                        $object->contact->fetch_thirdparty();
307
                        $socobject = $object->contact->thirdparty;
308
                        $contactobject = $object->contact;
309
                    } else {
310
                        $socobject = $object->thirdparty;
311
                        // if we have a CUSTOMER contact and we don't use it as thirdparty recipient we store the contact object for later use
312
                        $contactobject = $object->contact;
313
                    }
314
                } else {
315
                    $socobject = $object->thirdparty;
316
                }
317
318
                $object->fetch_optionals();
319
320
321
                // Define substitution array
322
                $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object);
323
                $array_object_from_properties = $this->get_substitutionarray_each_var_object($object, $outputlangs);
324
                $array_objet = $this->get_substitutionarray_object($object, $outputlangs); // complete with vars not set as properties by get_substitutionarray_each_var_object
325
                $array_user = $this->get_substitutionarray_user($user, $outputlangs);
326
                $array_soc = $this->get_substitutionarray_mysoc($mysoc, $outputlangs);
327
                $array_thirdparty = $this->get_substitutionarray_thirdparty($socobject, $outputlangs);
328
                $array_other = $this->get_substitutionarray_other($outputlangs);
329
                // retrieve contact information for use in order as contact_xxx tags
330
                $array_thirdparty_contact = array();
331
                if ($usecontact && is_object($contactobject)) {
332
                    $array_thirdparty_contact = $this->get_substitutionarray_contact($contactobject, $outputlangs, 'contact');
333
                }
334
335
                $substitutionarray = array_merge($substitutionarray, $array_object_from_properties, $array_user, $array_soc, $array_thirdparty, $array_objet, $array_other, $array_thirdparty_contact);
336
                complete_substitutions_array($substitutionarray, $outputlangs, $object);
337
338
                $tmparray = $substitutionarray;
339
340
                // Call the ODTSubstitution hook
341
                $parameters = array('file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$tmparray);
342
                $reshook = $hookmanager->executeHooks('ODTSubstitution', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
343
344
                // Line of free text
345
                $newfreetext = '';
346
                $paramfreetext = 'CONTRACT_FREE_TEXT';
347
                if (!empty($conf->global->$paramfreetext)) {
348
                    $newfreetext = make_substitutions(getDolGlobalString($paramfreetext), $tmparray);
349
                }
350
351
352
                // Open and load template
353
                require_once ODTPHP_PATH . 'odf.php';
0 ignored issues
show
Bug introduced by
The constant ODTPHP_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
354
                try {
355
                    $odfHandler = new Odf(
356
                        $srctemplatepath,
357
                        array(
358
                        'PATH_TO_TMP'     => $conf->contrat->dir_temp,
359
                        'ZIP_PROXY'       => 'PclZipProxy', // PhpZipProxy or PclZipProxy. Got "bad compression method" error when using PhpZipProxy.
360
                        'DELIMITER_LEFT'  => '{',
361
                        'DELIMITER_RIGHT' => '}'
362
                        )
363
                    );
364
                } catch (Exception $e) {
365
                    $this->error = $e->getMessage();
366
                    dol_syslog($e->getMessage(), LOG_INFO);
367
                    return -1;
368
                }
369
                // After construction $odfHandler->contentXml contains content and
370
                // [!-- BEGIN row.lines --]*[!-- END row.lines --] has been replaced by
371
                // [!-- BEGIN lines --]*[!-- END lines --]
372
                //print html_entity_decode($odfHandler->__toString());
373
                //print exit;
374
375
376
                // Make substitutions into odt of freetext
377
                try {
378
                    $odfHandler->setVars('free_text', $newfreetext, true, 'UTF-8');
379
                } catch (OdfException $e) {
380
                    dol_syslog($e->getMessage(), LOG_INFO);
381
                }
382
383
                // Call the ODTSubstitution hook
384
                $parameters = array('odfHandler' => &$odfHandler, 'file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$tmparray);
385
                $reshook = $hookmanager->executeHooks('ODTSubstitution', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
386
387
                foreach ($tmparray as $key => $value) {
388
                    try {
389
                        if (preg_match('/logo$/', $key)) {
390
                            // Image
391
                            if (file_exists($value)) {
392
                                $odfHandler->setImage($key, $value);
393
                            } else {
394
                                $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8');
395
                            }
396
                        } else {
397
                            // Text
398
                            $odfHandler->setVars($key, $value, true, 'UTF-8');
399
                        }
400
                    } catch (OdfException $e) {
401
                        dol_syslog($e->getMessage(), LOG_INFO);
402
                    }
403
                }
404
405
                // Replace tags of lines
406
                try {
407
                    $foundtagforlines = 1;
408
                    try {
409
                        $listlines = $odfHandler->setSegment('lines');
410
                    } catch (OdfExceptionSegmentNotFound $e) {
411
                        // We may arrive here if tags for lines not present into template
412
                        $foundtagforlines = 0;
413
                        dol_syslog($e->getMessage(), LOG_INFO);
414
                    } catch (OdfException $e) {
415
                        $foundtagforlines = 0;
416
                        dol_syslog($e->getMessage(), LOG_INFO);
417
                    }
418
                    if ($foundtagforlines) {
419
                        $linenumber = 0;
420
                        foreach ($object->lines as $line) {
421
                            $linenumber++;
422
                            $tmparray = $this->get_substitutionarray_lines($line, $outputlangs, $linenumber);
423
                            complete_substitutions_array($tmparray, $outputlangs, $object, $line, "completesubstitutionarray_lines");
424
                            // Call the ODTSubstitutionLine hook
425
                            $parameters = array('odfHandler' => &$odfHandler, 'file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$tmparray, 'line' => $line);
426
                            $reshook = $hookmanager->executeHooks('ODTSubstitutionLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
427
                            foreach ($tmparray as $key => $val) {
428
                                try {
429
                                    $listlines->setVars($key, $val, true, 'UTF-8');
430
                                } catch (OdfException $e) {
431
                                    dol_syslog($e->getMessage(), LOG_INFO);
432
                                } catch (SegmentException $e) {
433
                                    dol_syslog($e->getMessage(), LOG_INFO);
434
                                }
435
                            }
436
                            $listlines->merge();
437
                        }
438
                        $odfHandler->mergeSegment($listlines);
439
                    }
440
                } catch (OdfException $e) {
441
                    $this->error = $e->getMessage();
442
                    dol_syslog($this->error, LOG_WARNING);
443
                    return -1;
444
                }
445
446
                // Replace labels translated
447
                $tmparray = $outputlangs->get_translations_for_substitutions();
448
                foreach ($tmparray as $key => $value) {
449
                    try {
450
                        $odfHandler->setVars($key, $value, true, 'UTF-8');
451
                    } catch (OdfException $e) {
452
                        dol_syslog($e->getMessage(), LOG_INFO);
453
                    }
454
                }
455
456
                // Call the beforeODTSave hook
457
                $parameters = array('odfHandler' => &$odfHandler, 'file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$tmparray);
458
                $reshook = $hookmanager->executeHooks('beforeODTSave', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
459
460
                // Write new file
461
                if (getDolGlobalString('MAIN_ODT_AS_PDF')) {
462
                    try {
463
                        $odfHandler->exportAsAttachedPDF($file);
464
                    } catch (Exception $e) {
465
                        $this->error = $e->getMessage();
466
                        dol_syslog($e->getMessage(), LOG_INFO);
467
                        return -1;
468
                    }
469
                } else {
470
                    try {
471
                        $odfHandler->saveToDisk($file);
472
                    } catch (Exception $e) {
473
                        $this->error = $e->getMessage();
474
                        dol_syslog($e->getMessage(), LOG_INFO);
475
                        return -1;
476
                    }
477
                }
478
479
                $parameters = array('odfHandler' => &$odfHandler, 'file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$tmparray);
480
                $reshook = $hookmanager->executeHooks('afterODTCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
481
482
                dolChmod($file);
483
484
                $odfHandler = null; // Destroy object
485
486
                $this->result = array('fullpath' => $file);
487
488
                return 1; // Success
489
            } else {
490
                $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir);
491
                return -1;
492
            }
493
        }
494
495
        return -1;
496
    }
497
}
498