Passed
Push — EXTRACT_CLASSES ( 9f3ede...ff35ec )
by Rafael
76:09 queued 20:57
created

Import::load_arrays()   F

Complexity

Conditions 24
Paths 4116

Size

Total Lines 118
Code Lines 53

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 24
eloc 53
nc 4116
nop 2
dl 0
loc 118
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) 2011       Laurent Destailleur         <[email protected]>
4
 * Copyright (C) 2016       Raphaël Doursenaud          <[email protected]>
5
 * Copyright (C) 2020		Ahmad Jamaly Rabib	        <[email protected]>
6
 * Copyright (C) 2021-2024  Frédéric France		        <[email protected]>
7
 * Copyright (C) 2024       Rafael San José             <[email protected]>
8
 *
9
 * This program is free software; you can redistribute it and/or modify
10
 * it under the terms of the GNU General Public License as published by
11
 * the Free Software Foundation; either version 3 of the License, or
12
 * (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21
 */
22
23
namespace Dolibarr\Code\Imports\Classes;
24
25
/**
26
 *  \file       htdocs/imports/class/import.class.php
27
 *  \ingroup    import
28
 *  \brief      File of class to manage imports
29
 */
30
31
/**
32
 *  Class to manage imports
33
 */
34
class Import
35
{
36
    /**
37
     * @var DoliDB Database handler.
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\Imports\Classes\DoliDB was not found. Did you mean DoliDB? If so, make sure to prefix the type with \.
Loading history...
38
     */
39
    public $db;
40
41
    /**
42
     * @var string Error code (or message)
43
     */
44
    public $error = '';
45
46
    /**
47
     * @var string[] Error codes (or messages)
48
     */
49
    public $errors = array();
50
51
    /**
52
     * @var string DB Error number
53
     */
54
    public $errno;
55
56
    /**
57
     * @var array
58
     */
59
    public $array_import_module;
60
61
    /**
62
     * @var array
63
     */
64
    public $array_import_perms;
65
66
    /**
67
     * @var array
68
     */
69
    public $array_import_icon;
70
71
    /**
72
     * @var array
73
     */
74
    public $array_import_code;
75
76
    /**
77
     * @var array
78
     */
79
    public $array_import_label;
80
81
    /**
82
     * @var array
83
     */
84
    public $array_import_tables;
85
86
    /**
87
     * @var array
88
     */
89
    public $array_import_tables_creator;
90
91
    /**
92
     * @var array
93
     */
94
    public $array_import_fields;
95
96
    /**
97
     * @var array
98
     */
99
    public $array_import_fieldshidden;
100
101
    /**
102
     * @var array
103
     */
104
    public $array_import_entities;
105
106
    /**
107
     * @var array
108
     */
109
    public $array_import_regex;
110
111
    /**
112
     * @var array
113
     */
114
    public $array_import_updatekeys;
115
116
    /**
117
     * @var array
118
     */
119
    public $array_import_preselected_updatekeys;
120
121
    /**
122
     * @var array
123
     */
124
    public $array_import_examplevalues;
125
126
    /**
127
     * @var array
128
     */
129
    public $array_import_convertvalue;
130
131
    /**
132
     * @var array
133
     */
134
    public $array_import_run_sql_after;
135
136
    // To store import templates
137
    public $id;
138
    public $hexa; // List of fields in the export profile
139
    public $datatoimport;
140
141
    /**
142
     * @var string Name of export profile
143
     */
144
    public $model_name;
145
146
    /**
147
     * @var int ID
148
     */
149
    public $fk_user;
150
151
152
    /**
153
     *    Constructor
154
     *
155
     *    @param    DoliDB      $db     Database handler
156
     */
157
    public function __construct($db)
158
    {
159
        $this->db = $db;
160
    }
161
162
163
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
164
    /**
165
     *  Load description int this->array_import_module, this->array_import_fields, ... of an importable dataset
166
     *
167
     *  @param      User    $user       Object user making import
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\Imports\Classes\User was not found. Did you mean User? If so, make sure to prefix the type with \.
Loading history...
168
     *  @param      string  $filter     Load a particular dataset only. Index will start to 0.
169
     *  @return     int                 Return integer <0 if KO, >0 if OK
170
     */
171
    public function load_arrays($user, $filter = '')
172
    {
173
		// phpcs:enable
174
        global $langs, $conf;
175
176
        dol_syslog(get_class($this) . "::load_arrays user=" . $user->id . " filter=" . $filter);
177
178
        $i = 0;
179
180
        require_once constant('DOL_DOCUMENT_ROOT') . '/core/lib/functions2.lib.php';
181
        $modulesdir = dolGetModulesDirs();
182
183
        // Load list of modules
184
        foreach ($modulesdir as $dir) {
185
            $handle = @opendir(dol_osencode($dir));
186
            if (!is_resource($handle)) {
187
                continue;
188
            }
189
190
            // Search module files
191
            while (($file = readdir($handle)) !== false) {
192
                if (!preg_match("/^(mod.*)\.class\.php/i", $file, $reg)) {
193
                    continue;
194
                }
195
196
                $modulename = $reg[1];
197
198
                // Defined if module is enabled
199
                $enabled = true;
200
                $part = strtolower(preg_replace('/^mod/i', '', $modulename));
201
                // Adds condition for propal module
202
                if ($part === 'propale') {
203
                    $part = 'propal';
204
                }
205
                if (empty($conf->$part->enabled)) {
206
                    $enabled = false;
207
                }
208
209
                if (empty($enabled)) {
210
                    continue;
211
                }
212
213
                // Init load class
214
                $file = $dir . "/" . $modulename . ".class.php";
215
                $classname = $modulename;
216
                require_once $file;
217
                $module = new $classname($this->db);
218
219
                if (isset($module->import_code) && is_array($module->import_code)) {
220
                    foreach ($module->import_code as $r => $value) {
221
                        if ($filter && ($filter != $module->import_code[$r])) {
222
                            continue;
223
                        }
224
225
                        // Test if permissions are ok
226
                        /*$perm=$module->import_permission[$r][0];
227
                        //print_r("$perm[0]-$perm[1]-$perm[2]<br>");
228
                        if ($perm[2])
229
                        {
230
                        $bool=$user->rights->{$perm[0]}->{$perm[1]}->{$perm[2]};
231
                        }
232
                        else
233
                        {
234
                        $bool=$user->rights->{$perm[0]}->{$perm[1]};
235
                        }
236
                        if ($perm[0]=='user' && $user->admin) $bool=true;
237
                        //print $bool." $perm[0]"."<br>";
238
                        */
239
240
                        // Load lang file
241
                        $langtoload = $module->getLangFilesArray();
242
                        if (is_array($langtoload)) {
243
                            foreach ($langtoload as $key) {
244
                                $langs->load($key);
245
                            }
246
                        }
247
248
                        // Permission
249
                        $this->array_import_perms[$i] = $user->hasRight('import', 'run');
250
                        // Icon
251
                        $this->array_import_icon[$i] = (isset($module->import_icon[$r]) ? $module->import_icon[$r] : $module->picto);
252
                        // Code of dataset export
253
                        $this->array_import_code[$i] = $module->import_code[$r];
254
                        // Label of dataset export
255
                        $this->array_import_label[$i] = $module->getImportDatasetLabel($r);
256
                        // Array of tables to import (key=alias, value=tablename)
257
                        $this->array_import_tables[$i] = $module->import_tables_array[$r];
258
                        // Array of tables creator field to import (key=alias, value=creator field name)
259
                        $this->array_import_tables_creator[$i] = (isset($module->import_tables_creator_array[$r]) ? $module->import_tables_creator_array[$r] : '');
260
                        // Array of fields to import (key=field, value=label)
261
                        $this->array_import_fields[$i] = $module->import_fields_array[$r];
262
                        // Array of hidden fields to import (key=field, value=label)
263
                        $this->array_import_fieldshidden[$i] = (isset($module->import_fieldshidden_array[$r]) ? $module->import_fieldshidden_array[$r] : '');
264
                        // Array of entiteis to export (key=field, value=entity)
265
                        $this->array_import_entities[$i] = $module->import_entities_array[$r];
266
                        // Array of aliases to export (key=field, value=alias)
267
                        $this->array_import_regex[$i] = (isset($module->import_regex_array[$r]) ? $module->import_regex_array[$r] : '');
268
                        // Array of columns allowed as UPDATE options
269
                        $this->array_import_updatekeys[$i] = (isset($module->import_updatekeys_array[$r]) ? $module->import_updatekeys_array[$r] : '');
270
                        // Array of columns preselected as UPDATE options
271
                        $this->array_import_preselected_updatekeys[$i] = (isset($module->import_preselected_updatekeys_array[$r]) ? $module->import_preselected_updatekeys_array[$r] : '');
272
                        // Array of examples
273
                        $this->array_import_examplevalues[$i] = (isset($module->import_examplevalues_array[$r]) ? $module->import_examplevalues_array[$r] : '');
274
                        // Tableau des regles de conversion d'une valeur depuis une autre source (cle=champ, valeur=tableau des regles)
275
                        $this->array_import_convertvalue[$i] = (isset($module->import_convertvalue_array[$r]) ? $module->import_convertvalue_array[$r] : '');
276
                        // Sql request to run after import
277
                        $this->array_import_run_sql_after[$i] = (isset($module->import_run_sql_after_array[$r]) ? $module->import_run_sql_after_array[$r] : '');
278
                        // Module
279
                        $this->array_import_module[$i] = array('position_of_profile' => ($module->module_position . '-' . $module->import_code[$r]), 'module' => $module);
280
281
                        dol_syslog("Import loaded for module " . $modulename . " with index " . $i . ", dataset=" . $module->import_code[$r] . ", nb of fields=" . count($module->import_fields_array[$r]));
282
                        $i++;
283
                    }
284
                }
285
            }
286
            closedir($handle);
287
        }
288
        return 1;
289
    }
290
291
292
293
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
294
    /**
295
     *  Build an import example file.
296
     *  Arrays this->array_export_xxx are already loaded for required datatoexport
297
     *
298
     *  @param      string  $model              Name of import engine ('csv', ...)
299
     *  @param      string  $headerlinefields   Array of values for first line of example file
300
     *  @param      string  $contentlinevalues  Array of values for content line of example file
301
     *  @param      string  $datatoimport       Dataset to import
302
     *  @return     string                      Return integer <0 if KO, >0 if OK
303
     */
304
    public function build_example_file($model, $headerlinefields, $contentlinevalues, $datatoimport)
305
    {
306
		// phpcs:enable
307
        global $conf, $langs;
308
309
        $indice = 0;
310
311
        dol_syslog(get_class($this) . "::build_example_file " . $model);
312
313
        // Create the import class for the model Import_XXX
314
        $dir = DOL_DOCUMENT_ROOT . "/core/modules/import/";
315
        $file = "import_" . $model . ".modules.php";
316
        $classname = "Import" . $model;
317
        require_once $dir . $file;
318
        $objmodel = new $classname($this->db, $datatoimport);
319
320
        $outputlangs = $langs; // Lang for output
321
        $s = '';
322
323
        // Genere en-tete
324
        $s .= $objmodel->write_header_example($outputlangs);
325
326
        // Genere ligne de titre
327
        $s .= $objmodel->write_title_example($outputlangs, $headerlinefields);
328
329
        // Genere ligne de titre
330
        $s .= $objmodel->write_record_example($outputlangs, $contentlinevalues);
331
332
        // Genere pied de page
333
        $s .= $objmodel->write_footer_example($outputlangs);
334
335
        return $s;
336
    }
337
338
    /**
339
     *  Save an export model in database
340
     *
341
     *  @param      User    $user   Object user that save
342
     *  @return     int             Return integer <0 if KO, >0 if OK
343
     */
344
    public function create($user)
345
    {
346
        global $conf;
347
348
        dol_syslog("Import.class.php::create");
349
350
        // Check parameters
351
        if (empty($this->model_name)) {
352
            $this->error = 'ErrorWrongParameters';
353
            return -1;
354
        }
355
        if (empty($this->datatoimport)) {
356
            $this->error = 'ErrorWrongParameters';
357
            return -1;
358
        }
359
        if (empty($this->hexa)) {
360
            $this->error = 'ErrorWrongParameters';
361
            return -1;
362
        }
363
364
        $this->db->begin();
365
366
        $sql = 'INSERT INTO ' . MAIN_DB_PREFIX . 'import_model (';
367
        $sql .= 'fk_user,';
368
        $sql .= ' label,';
369
        $sql .= ' type,';
370
        $sql .= ' field';
371
        $sql .= ')';
372
        $sql .= " VALUES (";
373
        $sql .= (isset($this->fk_user) ? (int) $this->fk_user : 'null') . ",";
374
        $sql .= " '" . $this->db->escape($this->model_name) . "',";
375
        $sql .= " '" . $this->db->escape($this->datatoimport) . "',";
376
        $sql .= " '" . $this->db->escape($this->hexa) . "'";
377
        $sql .= ")";
378
379
        $resql = $this->db->query($sql);
380
        if ($resql) {
381
            $this->db->commit();
382
            return 1;
383
        } else {
384
            $this->error = $this->db->lasterror();
385
            $this->errno = $this->db->lasterrno();
386
            $this->db->rollback();
387
            return -1;
388
        }
389
    }
390
391
    /**
392
     *  Load an import profil from database
393
     *
394
     *  @param      int     $id     Id of profil to load
395
     *  @return     int             Return integer <0 if KO, >0 if OK
396
     */
397
    public function fetch($id)
398
    {
399
        $sql = 'SELECT em.rowid, em.field, em.label, em.type';
400
        $sql .= ' FROM ' . MAIN_DB_PREFIX . 'import_model as em';
401
        $sql .= ' WHERE em.rowid = ' . ((int) $id);
402
403
        dol_syslog(get_class($this) . "::fetch", LOG_DEBUG);
404
        $result = $this->db->query($sql);
405
        if ($result) {
406
            $obj = $this->db->fetch_object($result);
407
            if ($obj) {
408
                $this->id                   = $obj->rowid;
409
                $this->hexa                 = $obj->field;
410
                $this->model_name           = $obj->label;
411
                $this->datatoimport         = $obj->type;
412
                $this->fk_user              = $obj->fk_user;
413
                return 1;
414
            } else {
415
                $this->error = "Model not found";
416
                return -2;
417
            }
418
        } else {
419
            dol_print_error($this->db);
420
            return -3;
421
        }
422
    }
423
424
    /**
425
     *  Delete object in database
426
     *
427
     *  @param      User    $user           User that delete
428
     *  @param      int     $notrigger      0=launch triggers after, 1=disable triggers
429
     *  @return     int                     Return integer <0 if KO, >0 if OK
430
     */
431
    public function delete($user, $notrigger = 0)
432
    {
433
        $error = 0;
434
435
        $sql = "DELETE FROM " . MAIN_DB_PREFIX . "import_model";
436
        $sql .= " WHERE rowid=" . ((int) $this->id);
437
438
        $this->db->begin();
439
440
        dol_syslog(get_class($this) . "::delete", LOG_DEBUG);
441
        $resql = $this->db->query($sql);
442
        if (!$resql) {
443
            $error++;
444
            $this->errors[] = "Error " . $this->db->lasterror();
445
        }
446
447
        if (!$error) {
448
            if (!$notrigger) {
449
                /* Not used. This is not a business object. To convert it we must herit from CommonObject
450
                // Call trigger
451
                $result=$this->call_trigger('IMPORT_DELETE',$user);
452
                if ($result < 0) $error++;
453
                // End call triggers
454
                 */
455
            }
456
        }
457
458
        // Commit or rollback
459
        if ($error) {
460
            foreach ($this->errors as $errmsg) {
461
                dol_syslog(get_class($this) . "::delete " . $errmsg, LOG_ERR);
462
                $this->error .= ($this->error ? ', ' . $errmsg : $errmsg);
463
            }
464
            $this->db->rollback();
465
            return -1 * $error;
466
        } else {
467
            $this->db->commit();
468
            return 1;
469
        }
470
    }
471
}
472