doc_generic_odt::write_file()   F
last analyzed

Complexity

Conditions 35
Paths > 20000

Size

Total Lines 246
Code Lines 156

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 35
eloc 156
nc 363101
nop 6
dl 0
loc 246
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/* Copyright (C) 2010-2011  Laurent Destailleur         <[email protected]>
4
 * Copyright (C) 2016	    Charlie Benke               <[email protected]>
5
 * Copyright (C) 2018-2024  Frédéric France             <[email protected]>
6
 * Copyright (C) 2024       Rafael San José             <[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
use Dolibarr\Code\Contact\Classes\Contact;
24
use Dolibarr\Lib\ViewMain;
25
26
/**
27
 *  \file       htdocs/core/modules/societe/doc/doc_generic_odt.modules.php
28
 *  \ingroup    societe
29
 *  \brief      File of class to build ODT documents for third parties
30
 */
31
32
use Dolibarr\Code\Core\Classes\Form;
33
use Dolibarr\Code\Core\Classes\Translate;
34
use Dolibarr\Code\Societe\Classes\ModeleThirdPartyDoc;
35
use Dolibarr\Code\Societe\Classes\Societe;
36
37
require_once constant('DOL_DOCUMENT_ROOT') . '/core/lib/company.lib.php';
38
require_once constant('DOL_DOCUMENT_ROOT') . '/core/lib/files.lib.php';
39
require_once constant('DOL_DOCUMENT_ROOT') . '/core/lib/doc.lib.php';
40
41
/**
42
 *  Class to build documents using ODF templates generator
43
 */
44
class doc_generic_odt extends ModeleThirdPartyDoc
45
{
46
    /**
47
     * @var string Dolibarr version of the loaded document
48
     */
49
    public $version = 'dolibarr';
50
51
52
    /**
53
     *  Constructor
54
     *
55
     * @param DoliDB $db Database handler
56
     */
57
    public function __construct($db)
58
    {
59
        global $langs, $mysoc;
60
61
        // Load translation files required by the page
62
        $langs->loadLangs(array("main", "companies"));
63
64
        $this->db = $db;
65
        $this->name = "ODT templates";
66
        $this->description = $langs->trans("DocumentModelOdt");
67
        $this->scandir = 'COMPANY_ADDON_PDF_ODT_PATH'; // Name of constant that is used to save list of directories to scan
68
69
        // Page size for A4 format
70
        $this->type = 'odt';
71
        $this->page_largeur = 0;
72
        $this->page_hauteur = 0;
73
        $this->format = array($this->page_largeur, $this->page_hauteur);
74
        $this->marge_gauche = 0;
75
        $this->marge_droite = 0;
76
        $this->marge_haute = 0;
77
        $this->marge_basse = 0;
78
79
        $this->option_logo = 1; // Display logo
80
        $this->option_freetext = 0; // Support add of a personalised text
81
        $this->option_draft_watermark = 0; // Support add of a watermark on drafts
82
83
        // Retrieves transmitter
84
        $this->emetteur = $mysoc;
85
        if (!$this->emetteur->country_code) {
86
            $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default, if was not defined
87
        }
88
    }
89
90
    /**
91
     * Return description of a module
92
     *
93
     * @param Translate $langs Object language
94
     * @return  string                  Description
95
     */
96
    public function info($langs)
97
    {
98
        global $conf, $langs;
99
100
        // Load traductions files required by page
101
        $langs->loadLangs(array("companies", "errors"));
102
103
        $form = new Form($this->db);
104
105
        $texte = $this->description . ".<br>\n";
106
        $texte .= '<!-- form for option of ODT templates -->';
107
        $texte .= '<form action="' . $_SERVER["PHP_SELF"] . '" method="POST" enctype="multipart/form-data">';
108
        $texte .= '<input type="hidden" name="token" value="' . newToken() . '">';
109
        $texte .= '<input type="hidden" name="page_y" value="">';
110
        $texte .= '<input type="hidden" name="action" value="setModuleOptions">';
111
        $texte .= '<input type="hidden" name="param1" value="COMPANY_ADDON_PDF_ODT_PATH">';
112
        $texte .= '<table class="nobordernopadding centpercent">';
113
114
        // List of directories area
115
        $texte .= '<tr><td>';
116
        $texttitle = $langs->trans("ListOfDirectories");
117
        $listofdir = explode(',', preg_replace('/[\r\n]+/', ',', trim(getDolGlobalString('COMPANY_ADDON_PDF_ODT_PATH'))));
118
        $listoffiles = array();
119
        foreach ($listofdir as $key => $tmpdir) {
120
            $tmpdir = trim($tmpdir);
121
            $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
122
            if (!$tmpdir) {
123
                unset($listofdir[$key]);
124
                continue;
125
            }
126
            if (!is_dir($tmpdir)) {
127
                $texttitle .= img_warning($langs->trans("ErrorDirNotFound", $tmpdir), 0);
128
            } else {
129
                $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0, true); // Disable hook for the moment
130
                if (count($tmpfiles)) {
131
                    $listoffiles = array_merge($listoffiles, $tmpfiles);
132
                }
133
            }
134
        }
135
        $texthelp = $langs->trans("ListOfDirectoriesForModelGenODT");
136
        $texthelp .= '<br><br><span class="opacitymedium">' . $langs->trans("ExampleOfDirectoriesForModelGen") . '</span>';
137
        // Add list of substitution keys
138
        $texthelp .= '<br>' . $langs->trans("FollowingSubstitutionKeysCanBeUsed") . '<br>';
139
        $texthelp .= $langs->transnoentitiesnoconv("FullListOnOnlineDocumentation"); // This contains an url, we don't modify it
140
141
        if (!getDolGlobalString('MAIN_NO_MULTIDIR_FOR_ODT')) {
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 .= '<table><tr><td>';
145
            $texte .= '<textarea class="flat" cols="60" name="value1">';
146
            $texte .= getDolGlobalString('COMPANY_ADDON_PDF_ODT_PATH');
147
            $texte .= '</textarea>';
148
            //$texte .= '</td>';
149
            //$texte .= '<td class="center">&nbsp; ';
150
            $texte .= '</div><div style="display: inline-block; vertical-align: middle;">';
151
            $texte .= '<input type="submit" class="button button-edit reposition smallpaddingimp" name="modify" value="' . dol_escape_htmltag($langs->trans("Modify")) . '">';
152
            //$texte .= '</td>';
153
            //$texte .= '</tr>';
154
            //$texte .= '</table>';
155
            $texte .= '</div></div>';
156
        } else {
157
            $texte .= '<br>';
158
            $texte .= '<input type="hidden" name="value1" value="COMPANY_ADDON_PDF_ODT_PATH">';
159
        }
160
161
        // Scan directories
162
        $nbofiles = count($listoffiles);
163
        if (getDolGlobalString('COMPANY_ADDON_PDF_ODT_PATH')) {
164
            $texte .= $langs->trans("NumberOfModelFilesFound") . ': <b>';
165
            //$texte.=$nbofiles?'<a id="a_'.get_only_class($this).'" href="#">':'';
166
            $texte .= $nbofiles;
167
            //$texte.=$nbofiles?'</a>':'';
168
            $texte .= '</b>';
169
        }
170
171
        if ($nbofiles) {
172
            $texte .= '<div id="div_' . get_only_class($this) . '" class="hiddenx">';
173
            // Show list of found files
174
            foreach ($listoffiles as $file) {
175
                $texte .= '- ' . $file['name'] . ' &nbsp; <a class="reposition" href="' . constant('BASE_URL') . 'document.php?modulepart=doctemplates&file=thirdparties/' . urlencode(basename($file['name'])) . '">' . img_picto('', 'listlight') . '</a>';
176
                $texte .= ' &nbsp; <a class="reposition" href="' . $_SERVER["PHP_SELF"] . '?modulepart=doctemplates&keyforuploaddir=COMPANY_ADDON_PDF_ODT_PATH&action=deletefile&token=' . newToken() . '&file=' . urlencode(basename($file['name'])) . '">' . img_picto('', 'delete') . '</a>';
177
                $texte .= '<br>';
178
            }
179
            $texte .= '</div>';
180
        }
181
        // Add input to upload a new template file.
182
        $texte .= '<div>' . $langs->trans("UploadNewTemplate");
183
        $maxfilesizearray = getMaxFileSizeArray();
184
        $maxmin = $maxfilesizearray['maxmin'];
185
        if ($maxmin > 0) {
186
            $texte .= '<input type="hidden" name="MAX_FILE_SIZE" value="' . ($maxmin * 1024) . '">';    // MAX_FILE_SIZE must precede the field type=file
187
        }
188
        $texte .= ' <input type="file" name="uploadfile">';
189
        $texte .= '<input type="hidden" value="COMPANY_ADDON_PDF_ODT_PATH" name="keyforuploaddir">';
190
        $texte .= '<input type="submit" class="button smallpaddingimp reposition" value="' . dol_escape_htmltag($langs->trans("Upload")) . '" name="upload">';
191
        $texte .= '</div>';
192
        $texte .= '</td>';
193
194
        $texte .= '</tr>';
195
196
        $texte .= '</table>';
197
        $texte .= '</form>';
198
199
        return $texte;
200
    }
201
202
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
203
204
    /**
205
     *  Function to build a document on disk using the generic odt module.
206
     *
207
     * @param Societe $object Object source to build document
208
     * @param Translate $outputlangs Lang output object
209
     * @param string $srctemplatepath Full path of source filename for generator using a template file
210
     * @param int $hidedetails Do not show line details
211
     * @param int $hidedesc Do not show desc
212
     * @param int $hideref Do not show ref
213
     * @return     int                             1 if OK, <=0 if KO
214
     */
215
    public function write_file($object, $outputlangs, $srctemplatepath, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
216
    {
217
        // phpcs:enable
218
        global $user, $langs, $conf, $mysoc, $hookmanager;
219
        global $action;
220
221
        if (empty($srctemplatepath)) {
222
            dol_syslog("doc_generic_odt::write_file parameter srctemplatepath empty", LOG_WARNING);
223
            return -1;
224
        }
225
226
        // Add odtgeneration hook
227
        if (!is_object($hookmanager)) {
228
            $hookmanager = new HookManager($this->db);
229
        }
230
        $hookmanager->initHooks(array('odtgeneration'));
231
232
        if (!is_object($outputlangs)) {
233
            $outputlangs = $langs;
234
        }
235
        $sav_charset_output = $outputlangs->charset_output;
236
        $outputlangs->charset_output = 'UTF-8';
237
238
        // Load translation files required by the page
239
        $outputlangs->loadLangs(array("main", "dict", "companies", "projects"));
240
241
        if ($conf->societe->multidir_output[$object->entity]) {
242
            $dir = $conf->societe->multidir_output[$object->entity];
243
            $objectref = dol_sanitizeFileName($object->id);
244
            if (!preg_match('/specimen/i', $objectref)) {
245
                $dir .= "/" . $objectref;
246
            }
247
248
            if (!file_exists($dir)) {
249
                if (dol_mkdir($dir) < 0) {
250
                    $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir);
251
                    return -1;
252
                }
253
            }
254
255
            if (file_exists($dir)) {
256
                //print "srctemplatepath=".$srctemplatepath;    // Src filename
257
                $newfile = basename($srctemplatepath);
258
                $newfiletmp = preg_replace('/\.od(s|t)/i', '', $newfile);
259
                $newfiletmp = preg_replace('/template_/i', '', $newfiletmp);
260
                $newfiletmp = preg_replace('/modele_/i', '', $newfiletmp);
261
                // Get extension (ods or odt)
262
                $newfileformat = substr($newfile, strrpos($newfile, '.') + 1);
263
                if (getDolGlobalString('MAIN_DOC_USE_OBJECT_THIRDPARTY_NAME')) {
264
                    $newfiletmp = dol_sanitizeFileName(dol_string_nospecial($object->name)) . '-' . $newfiletmp;
265
                    $newfiletmp = preg_replace('/__+/', '_', $newfiletmp);  // Replace repeated _ into one _ (to avoid string with substitution syntax)
266
                }
267
                if (getDolGlobalString('MAIN_DOC_USE_TIMING')) {
268
                    $format = getDolGlobalString('MAIN_DOC_USE_TIMING');
269
                    if ($format == '1') {
270
                        $format = '%Y%m%d%H%M%S';
271
                    }
272
                    $filename = $newfiletmp . '-' . dol_print_date(dol_now(), $format) . '.' . $newfileformat;
273
                } else {
274
                    $filename = $newfiletmp . '.' . $newfileformat;
275
                }
276
                $file = $dir . '/' . $filename;
277
                $object->builddoc_filename = $filename; // For triggers
0 ignored issues
show
Bug Best Practice introduced by
The property builddoc_filename does not exist on Dolibarr\Code\Societe\Classes\Societe. Since you implemented __set, consider adding a @property annotation.
Loading history...
278
                $object->context['builddoc_filename'] = $filename; // For triggers
279
                //print "newfileformat=".$newfileformat;
280
                //print "newdir=".$dir;
281
                //print "newfile=".$newfile;
282
                //print "file=".$file;
283
                //print "conf->societe->dir_temp=".$conf->societe->dir_temp;
284
                //exit;
285
286
                dol_mkdir($conf->societe->multidir_temp[$object->entity]);
287
                if (!is_writable($conf->societe->multidir_temp[$object->entity])) {
288
                    $this->error = $langs->transnoentities("ErrorFailedToWriteInTempDirectory", $conf->societe->multidir_temp[$object->entity]);
289
                    dol_syslog('Error in write_file: ' . $this->error, LOG_ERR);
290
                    return -1;
291
                }
292
293
                // Open and load template
294
                require_once ODTPHP_PATH . 'odf.php';
295
                try {
296
                    $odfHandler = new Odf(
297
                        $srctemplatepath,
298
                        array(
299
                            'PATH_TO_TMP' => $conf->societe->multidir_temp[$object->entity],
300
                            'ZIP_PROXY' => 'PclZipProxy', // PhpZipProxy or PclZipProxy. Got "bad compression method" error when using PhpZipProxy.
301
                            'DELIMITER_LEFT' => '{',
302
                            'DELIMITER_RIGHT' => '}'
303
                        )
304
                    );
305
                } catch (Exception $e) {
306
                    $this->error = $e->getMessage();
307
                    dol_syslog($e->getMessage(), LOG_INFO);
308
                    return -1;
309
                }
310
                //print $odfHandler->__toString()."\n";
311
312
                // Replace tags of lines for contacts
313
                $contact_arrray = array();
314
315
                $sql = "SELECT p.rowid";
316
                $sql .= " FROM " . MAIN_DB_PREFIX . "socpeople as p";
317
                $sql .= " WHERE p.fk_soc = " . ((int)$object->id);
318
319
                $result = $this->db->query($sql);
320
                $num = $this->db->num_rows($result);
321
322
                if ($num) {
323
                    $i = 0;
324
                    $contactstatic = new Contact($this->db);
325
326
                    while ($i < $num) {
327
                        $obj = $this->db->fetch_object($result);
328
329
                        $contact_arrray[$i] = $obj->rowid;
330
                        $i++;
331
                    }
332
                }
333
                if ((is_array($contact_arrray) && count($contact_arrray) > 0)) {
334
                    $foundtagforlines = 1;
335
                    try {
336
                        $listlines = $odfHandler->setSegment('companycontacts');
337
                    } catch (OdfExceptionSegmentNotFound $e) {
338
                        // We may arrive here if tags for lines not present into template
339
                        $foundtagforlines = 0;
340
                        dol_syslog($e->getMessage(), LOG_INFO);
341
                    }
342
                    if ($foundtagforlines) {
343
                        foreach ($contact_arrray as $array_key => $contact_id) {
344
                            $res_contact = $contactstatic->fetch($contact_id);
345
                            if ((int)$res_contact > 0) {
346
                                $tmparray = $this->get_substitutionarray_contact($contactstatic, $outputlangs, 'contact');
347
                                foreach ($tmparray as $key => $val) {
348
                                    try {
349
                                        $listlines->setVars($key, $val, true, 'UTF-8');
350
                                    } catch (SegmentException $e) {
351
                                        dol_syslog($e->getMessage(), LOG_INFO);
352
                                    }
353
                                }
354
                                $listlines->merge();
355
                            } else {
356
                                $this->error = $contactstatic->error;
357
                                dol_syslog($this->error, LOG_WARNING);
358
                            }
359
                        }
360
                        try {
361
                            $odfHandler->mergeSegment($listlines);
362
                        } catch (OdfException $e) {
363
                            $this->error = $e->getMessage();
364
                            dol_syslog($this->error, LOG_WARNING);
365
                            //return -1;
366
                        }
367
                    }
368
                }
369
370
                // Make substitutions into odt
371
                $array_user = $this->get_substitutionarray_user($user, $outputlangs);
372
                $array_soc = $this->get_substitutionarray_mysoc($mysoc, $outputlangs);
373
                $array_thirdparty = $this->get_substitutionarray_thirdparty($object, $outputlangs);
374
                $array_other = $this->get_substitutionarray_other($outputlangs);
375
376
                $tmparray = array_merge($array_user, $array_soc, $array_thirdparty, $array_other);
377
378
                complete_substitutions_array($tmparray, $outputlangs, $object);
379
380
                // Call the ODTSubstitution hook
381
                $parameters = array('odfHandler' => &$odfHandler, 'file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$tmparray);
382
                $reshook = $hookmanager->executeHooks('ODTSubstitution', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
383
384
                // Replace variables into document
385
                foreach ($tmparray as $key => $value) {
386
                    try {
387
                        if (preg_match('/logo$/', $key)) {  // Image
388
                            if (file_exists($value)) {
389
                                $odfHandler->setImage($key, $value);
390
                            } else {
391
                                $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8');
392
                            }
393
                        } else { // Text
394
                            $odfHandler->setVars($key, $value, true, 'UTF-8');
395
                        }
396
                    } catch (OdfException $e) {
397
                        // setVars failed, probably because key not found
398
                        dol_syslog($e->getMessage(), LOG_INFO);
399
                    }
400
                }
401
402
                // Replace labels translated
403
                $tmparray = $outputlangs->get_translations_for_substitutions();
404
                foreach ($tmparray as $key => $value) {
405
                    try {
406
                        $odfHandler->setVars($key, $value, true, 'UTF-8');
407
                    } catch (OdfException $e) {
408
                        dol_syslog($e->getMessage(), LOG_INFO);
409
                    }
410
                }
411
412
                // Call the beforeODTSave hook
413
                $parameters = array('odfHandler' => &$odfHandler, 'file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$tmparray);
414
                $reshook = $hookmanager->executeHooks('beforeODTSave', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
415
416
                // Write new file
417
                if (getDolGlobalString('MAIN_ODT_AS_PDF')) {
418
                    try {
419
                        $odfHandler->exportAsAttachedPDF($file);
420
                    } catch (Exception $e) {
421
                        $this->error = $e->getMessage();
422
                        dol_syslog($e->getMessage(), LOG_INFO);
423
                        return -1;
424
                    }
425
                } else {
426
                    try {
427
                        $odfHandler->creator = $user->getFullName($outputlangs);
428
                        $odfHandler->title = $object->builddoc_filename;
0 ignored issues
show
Bug Best Practice introduced by
The property builddoc_filename does not exist on Dolibarr\Code\Societe\Classes\Societe. Since you implemented __get, consider adding a @property annotation.
Loading history...
429
                        $odfHandler->subject = $object->builddoc_filename;
430
431
                        if (getDolGlobalString('ODT_ADD_DOLIBARR_ID')) {
432
                            $odfHandler->userdefined['dol_id'] = $object->id;
433
                            $odfHandler->userdefined['dol_element'] = $object->element;
434
                        }
435
436
                        $odfHandler->saveToDisk($file);
437
                    } catch (Exception $e) {
438
                        $this->error = $e->getMessage();
439
                        dol_syslog($e->getMessage(), LOG_INFO);
440
                        return -1;
441
                    }
442
                }
443
                $parameters = array('odfHandler' => &$odfHandler, 'file' => $file, 'object' => $object, 'outputlangs' => $outputlangs, 'substitutionarray' => &$tmparray);
444
                $reshook = $hookmanager->executeHooks('afterODTCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
445
446
                dolChmod($file);
447
448
                $odfHandler = null; // Destroy object
449
450
                $this->result = array('fullpath' => $file);
451
452
                return 1; // Success
453
            } else {
454
                $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir);
455
                return -1;
456
            }
457
        }
458
459
        $this->error = 'UnknownError';
460
        return -1;
461
    }
462
}
463