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

Skilldet   F

Complexity

Total Complexity 140

Size/Duplication

Total Lines 924
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 355
dl 0
loc 924
rs 2
c 0
b 0
f 0
wmc 140

20 Methods

Rating   Name   Duplication   Size   Complexity  
A initAsSpecimen() 0 7 1
A reopen() 0 15 2
A delete() 0 3 1
B fetchAll() 0 53 9
A LibStatut() 0 21 4
A fetch() 0 7 3
A generateDocument() 0 26 6
B getNextNumRef() 0 47 9
A cancel() 0 15 2
A create() 0 7 1
F getNomUrl() 0 103 34
F createFromClone() 0 88 22
A deleteLine() 0 8 2
A update() 0 3 1
A fetchLines() 0 6 1
F validate() 0 122 22
A getLibStatut() 0 3 1
A setDraft() 0 15 2
C __construct() 0 35 13
A info() 0 22 4

How to fix   Complexity   

Complex Class

Complex classes like Skilldet 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 Skilldet, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/* Copyright (C) 2017       Laurent Destailleur         <[email protected]>
4
 * Copyright (C) 2021       Gauthier VERDOL             <[email protected]>
5
 * Copyright (C) 2021       Greg Rastklan               <[email protected]>
6
 * Copyright (C) 2021       Jean-Pascal BOUDET          <[email protected]>
7
 * Copyright (C) 2021       Grégory BLEMAND             <[email protected]>
8
 * Copyright (C) 2024       Frédéric France             <[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
 */
25
26
namespace Dolibarr\Code\Hrm\Classes;
27
28
use Dolibarr\Core\Base\CommonObjectLine;
29
30
/**
31
 * \file        class/skilldet.class.php
32
 * \ingroup     hrm
33
 * \brief       This file is a CRUD class file for Skilldet (Create/Read/Update/Delete)
34
 */
35
36
/**
37
 * Class for Skilldet
38
 */
39
class Skilldet extends CommonObjectLine
40
{
41
    /**
42
     * @var string ID of module.
43
     */
44
    public $module = 'hrm';
45
46
    /**
47
     * @var string ID to identify managed object.
48
     */
49
    public $element = 'skilldet';
50
51
    /**
52
     * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management.
53
     */
54
    public $table_element = 'hrm_skilldet';
55
56
    /**
57
     * @see CommonObjectLine
58
     */
59
    public $parent_element = 'skill';
60
61
    /**
62
     * @see CommonObjectLine
63
     */
64
    public $fk_parent_attribute = 'fk_skill';
65
66
    /**
67
     * @var string String with name of icon for skilldet. Must be the part after the 'object_' into object_skilldet.png
68
     */
69
    public $picto = 'skilldet@hrm';
70
71
72
    const STATUS_DRAFT = 0;
73
    const STATUS_VALIDATED = 1;
74
    const STATUS_CANCELED = 9;
75
76
77
    /**
78
     *  'type' field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter]]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'text:none', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password')
79
     *         Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
80
     *  'label' the translation key.
81
     *  'picto' is code of a picto to show before value in forms
82
     *  'enabled' is a condition when the field must be managed (Example: 1 or 'getDolGlobalString("MY_SETUP_PARAM")')
83
     *  'position' is the sort order of field.
84
     *  'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
85
     *  'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing)
86
     *  'noteditable' says if field is not editable (1 or 0)
87
     *  'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created.
88
     *  'index' if we want an index in database.
89
     *  'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommended to name the field fk_...).
90
     *  'searchall' is 1 if we want to search in this field when making a search from the quick search button.
91
     *  'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8).
92
     *  'css' and 'cssview' and 'csslist' is the CSS style to use on field. 'css' is used in creation and update. 'cssview' is used in view mode. 'csslist' is used for columns in lists. For example: 'css'=>'minwidth300 maxwidth500 widthcentpercentminusx', 'cssview'=>'wordbreak', 'csslist'=>'tdoverflowmax200'
93
     *  'help' is a 'TranslationString' to use to show a tooltip on field. You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
94
     *  'showoncombobox' if value of the field must be visible into the label of the combobox that list record
95
     *  'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code.
96
     *  'arrayofkeyval' to set a list of values if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel"). Note that type can be 'integer' or 'varchar'
97
     *  'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1.
98
     *  'comment' is not used. You can store here any text of your choice. It is not used by application.
99
     *
100
     *  Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
101
     */
102
103
    // BEGIN MODULEBUILDER PROPERTIES
104
    /**
105
     * @var array<string,array{type:string,label:string,enabled:int<0,2>|string,position:int,notnull?:int,visible:int,noteditable?:int,default?:string,index?:int,foreignkey?:string,searchall?:int,isameasure?:int,css?:string,csslist?:string,help?:string,showoncombobox?:int,disabled?:int,arrayofkeyval?:array<int,string>,comment?:string}>  Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
0 ignored issues
show
Documentation Bug introduced by
The doc comment array<string,array{type:...ring>,comment?:string}> at position 16 could not be parsed: Expected '}' at position 16, but found 'int'.
Loading history...
106
     */
107
    public $fields = array(
108
        'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'position' => 1, 'notnull' => 1, 'visible' => 0, 'noteditable' => 1, 'index' => 1, 'css' => 'left', 'comment' => "Id"),
109
        'fk_skill' => array('type' => 'integer:Skill:/hrm/class/skill.class.php', 'label' => 'fk_skill', 'enabled' => 1, 'position' => 5, 'notnull' => 1, 'visible' => 0,),
110
        'rankorder' => array('type' => 'integer', 'label' => 'rank', 'enabled' => 1, 'position' => 10, 'notnull' => 0, 'visible' => 2,),
111
        'description' => array('type' => 'text', 'label' => 'Description', 'enabled' => 1, 'position' => 60, 'notnull' => 0, 'visible' => 1,),
112
        'fk_user_creat' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'enabled' => 1, 'position' => 510, 'notnull' => 1, 'visible' => -2, 'foreignkey' => 'user.rowid',),
113
        'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => 1, 'position' => 511, 'notnull' => -1, 'visible' => 0,),
114
    );
115
    public $rowid;
116
    public $fk_skill;
117
    public $rankorder;
118
    public $description;
119
    public $fk_user_creat;
120
    public $fk_user_modif;
121
    // END MODULEBUILDER PROPERTIES
122
123
124
    // If this object has a subtable with lines
125
126
    // /**
127
    //  * @var string    Name of subtable line
128
    //  */
129
    // public $table_element_line = 'hrm_skilldetline';
130
131
    // /**
132
    //  * @var string    Field with ID of parent key if this object has a parent
133
    //  */
134
    // public $fk_element = 'fk_skilldet';
135
136
    // /**
137
    //  * @var string    Name of subtable class that manage subtable lines
138
    //  */
139
    // public $class_element_line = 'Skilldetline';
140
141
    // /**
142
    //  * @var array    List of child tables. To test if we can delete object.
143
    //  */
144
    // protected $childtables = array();
145
146
    // /**
147
    //  * @var array    List of child tables. To know object to delete on cascade.
148
    //  *               If name matches '@ClassNAme:FilePathClass;ParentFkFieldName' it will
149
    //  *               call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object
150
    //  */
151
    // protected $childtablesoncascade = array('hrm_skilldetdet');
152
153
    // /**
154
    //  * @var SkilldetLine[]     Array of subtable lines
155
    //  */
156
    // public $lines = array();
157
158
159
160
    /**
161
     * Constructor
162
     *
163
     * @param DoliDB $db Database handler
164
     */
165
    public function __construct(DoliDB $db)
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\Hrm\Classes\DoliDB was not found. Did you mean DoliDB? If so, make sure to prefix the type with \.
Loading history...
166
    {
167
        global $conf, $langs;
168
169
        $this->db = $db;
170
171
        $this->ismultientitymanaged = 0;
172
        $this->isextrafieldmanaged = 1;
173
174
        if (!getDolGlobalString('MAIN_SHOW_TECHNICAL_ID') && isset($this->fields['rowid'])) {
175
            $this->fields['rowid']['visible'] = 0;
176
        }
177
        if (!isModEnabled('multicompany') && isset($this->fields['entity'])) {
178
            $this->fields['entity']['enabled'] = 0;
179
        }
180
181
        // Example to show how to set values of fields definition dynamically
182
        /*if ($user->rights->hrm->skilldet->read) {
183
            $this->fields['myfield']['visible'] = 1;
184
            $this->fields['myfield']['noteditable'] = 0;
185
        }*/
186
187
        // Unset fields that are disabled
188
        foreach ($this->fields as $key => $val) {
189
            if (isset($val['enabled']) && empty($val['enabled'])) {
190
                unset($this->fields[$key]);
191
            }
192
        }
193
194
        // Translate some data of arrayofkeyval
195
        if (is_object($langs)) {
196
            foreach ($this->fields as $key => $val) {
197
                if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
198
                    foreach ($val['arrayofkeyval'] as $key2 => $val2) {
199
                        $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
200
                    }
201
                }
202
            }
203
        }
204
    }
205
206
    /**
207
     * Create object into database
208
     *
209
     * @param  User $user      User that creates
210
     * @param  int  $notrigger 0=launch triggers after, 1=disable triggers
211
     * @return int             Return integer <0 if KO, Id of created object if OK
212
     */
213
    public function create(User $user, $notrigger = 0)
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\Hrm\Classes\User was not found. Did you mean User? If so, make sure to prefix the type with \.
Loading history...
214
    {
215
        $resultcreate = $this->createCommon($user, $notrigger);
216
217
        //$resultvalidate = $this->validate($user, $notrigger);
218
219
        return $resultcreate;
220
    }
221
222
    /**
223
     * Clone an object into another one
224
     *
225
     * @param   User    $user       User that creates
226
     * @param   int     $fromid     Id of object to clone
227
     * @return  mixed               New object created, <0 if KO
228
     */
229
    public function createFromClone(User $user, $fromid)
230
    {
231
        global $langs, $extrafields;
232
        $error = 0;
233
234
        dol_syslog(__METHOD__, LOG_DEBUG);
235
236
        $object = new self($this->db);
237
238
        $this->db->begin();
239
240
        // Load source object
241
        $result = $object->fetchCommon($fromid);
242
        if ($result > 0 && !empty($object->table_element_line)) {
243
            $object->fetchLines();
244
        }
245
246
        // get lines so they will be clone
247
        //foreach($this->lines as $line)
248
        //  $line->fetch_optionals();
249
250
        // Reset some properties
251
        unset($object->id);
252
        unset($object->fk_user_creat);
253
        unset($object->import_key);
254
255
        // Clear fields
256
        if (property_exists($object, 'ref')) {
257
            $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_" . $object->ref : $this->fields['ref']['default'];
258
        }
259
        if (property_exists($object, 'label')) {
260
            $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf") . " " . $object->label : $this->fields['label']['default'];
261
        }
262
        if (property_exists($object, 'status')) {
263
            $object->status = self::STATUS_DRAFT;
264
        }
265
        if (property_exists($object, 'date_creation')) {
266
            $object->date_creation = dol_now();
267
        }
268
        if (property_exists($object, 'date_modification')) {
269
            $object->date_modification = null;
270
        }
271
        // ...
272
        // Clear extrafields that are unique
273
        if (is_array($object->array_options) && count($object->array_options) > 0) {
274
            $extrafields->fetch_name_optionals_label($this->table_element);
275
            foreach ($object->array_options as $key => $option) {
276
                $shortkey = preg_replace('/options_/', '', $key);
277
                if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) {
278
                    //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
279
                    unset($object->array_options[$key]);
280
                }
281
            }
282
        }
283
284
        // Create clone
285
        $object->context['createfromclone'] = 'createfromclone';
286
        $result = $object->createCommon($user);
287
        if ($result < 0) {
288
            $error++;
289
            $this->setErrorsFromObject($object);
290
        }
291
292
        if (!$error) {
293
            // copy internal contacts
294
            if ($this->copy_linked_contact($object, 'internal') < 0) {
295
                $error++;
296
            }
297
        }
298
299
        if (!$error) {
300
            // copy external contacts if same company
301
            if (property_exists($this, 'fk_soc') && $this->fk_soc == $object->socid) {
302
                if ($this->copy_linked_contact($object, 'external') < 0) {
303
                    $error++;
304
                }
305
            }
306
        }
307
308
        unset($object->context['createfromclone']);
309
310
        // End
311
        if (!$error) {
312
            $this->db->commit();
313
            return $object;
314
        } else {
315
            $this->db->rollback();
316
            return -1;
317
        }
318
    }
319
320
    /**
321
     * Load object in memory from the database
322
     *
323
     * @param int    $id   Id object
324
     * @param string $ref  Ref
325
     * @return int         Return integer <0 if KO, 0 if not found, >0 if OK
326
     */
327
    public function fetch($id, $ref = null)
328
    {
329
        $result = $this->fetchCommon($id, $ref);
330
        if ($result > 0 && !empty($this->table_element_line)) {
331
            $this->fetchLines();
332
        }
333
        return $result;
334
    }
335
336
    /**
337
     * Load object lines in memory from the database
338
     *
339
     * @return int         Return integer <0 if KO, 0 if not found, >0 if OK
340
     */
341
    public function fetchLines()
342
    {
343
        $this->lines = array();
344
345
        $result = $this->fetchLinesCommon();
346
        return $result;
347
    }
348
349
350
    /**
351
     * Load list of objects in memory from the database.
352
     *
353
     * @param  string       $sortorder      Sort Order
354
     * @param  string       $sortfield      Sort field
355
     * @param  int          $limit          limit
356
     * @param  int          $offset         Offset
357
     * @param  string       $filter         Filter as an Universal Search string.
358
     *                                      Example: '((client:=:1) OR ((client:>=:2) AND (client:<=:3))) AND (client:!=:8) AND (nom:like:'a%')'
359
     * @param  string       $filtermode     No more used
360
     * @return array|int                    int <0 if KO, array of pages if OK
361
     */
362
    public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, $filter = '', $filtermode = 'AND')
363
    {
364
        dol_syslog(__METHOD__, LOG_DEBUG);
365
366
        $records = array();
367
368
        $sql = 'SELECT ';
369
        $sql .= $this->getFieldList('t');
370
        $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t';
371
        if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
372
            $sql .= ' WHERE t.entity IN (' . getEntity($this->element) . ')';
373
        } else {
374
            $sql .= ' WHERE 1 = 1';
375
        }
376
377
        // Manage filter
378
        $errormessage = '';
379
        $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
380
        if ($errormessage) {
381
            $this->errors[] = $errormessage;
382
            dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
383
            return -1;
384
        }
385
386
        if (!empty($sortfield)) {
387
            $sql .= $this->db->order($sortfield, $sortorder);
388
        }
389
        if (!empty($limit)) {
390
            $sql .= " " . $this->db->plimit($limit, $offset);
391
        }
392
393
        $resql = $this->db->query($sql);
394
        if ($resql) {
395
            $num = $this->db->num_rows($resql);
396
            $i = 0;
397
            while ($i < ($limit ? min($limit, $num) : $num)) {
398
                $obj = $this->db->fetch_object($resql);
399
400
                $record = new self($this->db);
401
                $record->setVarsFromFetchObj($obj);
402
403
                $records[$record->id] = $record;
404
405
                $i++;
406
            }
407
            $this->db->free($resql);
408
409
            return $records;
410
        } else {
411
            $this->errors[] = 'Error ' . $this->db->lasterror();
412
            dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
413
414
            return -1;
415
        }
416
    }
417
418
    /**
419
     * Update object into database
420
     *
421
     * @param  User $user      User that modifies
422
     * @param  int  $notrigger 0=launch triggers after, 1=disable triggers
423
     * @return int             Return integer <0 if KO, >0 if OK
424
     */
425
    public function update(User $user, $notrigger = 0)
426
    {
427
        return $this->updateCommon($user, $notrigger);
428
    }
429
430
    /**
431
     * Delete object in database
432
     *
433
     * @param User  $user       User that deletes
434
     * @param int   $notrigger  0=launch triggers after, 1=disable triggers
435
     * @return int              Return integer <0 if KO, >0 if OK
436
     */
437
    public function delete(User $user, $notrigger = 0)
438
    {
439
        return $this->deleteCommon($user, $notrigger);
440
        //return $this->deleteCommon($user, $notrigger, 1);
441
    }
442
443
    /**
444
     *  Delete a line of object in database
445
     *
446
     *  @param  User    $user       User that delete
447
     *  @param  int     $idline     Id of line to delete
448
     *  @param  int     $notrigger  0=launch triggers after, 1=disable triggers
449
     *  @return int                 Return >0 if OK, <0 if KO
450
     */
451
    public function deleteLine(User $user, $idline, $notrigger = 0)
452
    {
453
        if ($this->status < 0) {
454
            $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
455
            return -2;
456
        }
457
458
        return $this->deleteLineCommon($user, $idline, $notrigger);
459
    }
460
461
462
    /**
463
     *  Validate object
464
     *
465
     *  @param      User    $user           User making status change
466
     *  @param      int     $notrigger      1=Does not execute triggers, 0= execute triggers
467
     *  @return     int                     Return integer <=0 if OK, 0=Nothing done, >0 if KO
468
     */
469
    public function validate($user, $notrigger = 0)
470
    {
471
        global $conf, $langs;
472
473
        require_once constant('DOL_DOCUMENT_ROOT') . '/core/lib/files.lib.php';
474
475
        $error = 0;
476
477
        // Protection
478
        if ($this->status == self::STATUS_VALIDATED) {
479
            dol_syslog(get_class($this) . "::validate action abandoned: already validated", LOG_WARNING);
480
            return 0;
481
        }
482
483
        /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->hrm->skilldet->write))
484
         || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->hrm->skilldet->skilldet_advance->validate))))
485
         {
486
         $this->error='NotEnoughPermissions';
487
         dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
488
         return -1;
489
         }*/
490
491
        $now = dol_now();
492
493
        $this->db->begin();
494
495
        // Define new ref
496
        if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
497
            $num = $this->getNextNumRef();
498
        } else {
499
            $num = $this->ref;
500
        }
501
        $this->newref = $num;
502
503
        if (!empty($num)) {
504
            // Validate
505
            $sql = "UPDATE " . MAIN_DB_PREFIX . $this->table_element;
506
            $sql .= " SET ref = '" . $this->db->escape($num) . "',";
507
            $sql .= " status = " . self::STATUS_VALIDATED;
508
            if (!empty($this->fields['date_validation'])) {
509
                $sql .= ", date_validation = '" . $this->db->idate($now) . "'";
510
            }
511
            if (!empty($this->fields['fk_user_valid'])) {
512
                $sql .= ", fk_user_valid = " . ((int) $user->id);
513
            }
514
            $sql .= " WHERE rowid = " . ((int) $this->id);
515
516
            dol_syslog(get_class($this) . "::validate()", LOG_DEBUG);
517
            $resql = $this->db->query($sql);
518
            if (!$resql) {
519
                dol_print_error($this->db);
520
                $this->error = $this->db->lasterror();
521
                $error++;
522
            }
523
524
            if (!$error && !$notrigger) {
525
                // Call trigger
526
                $result = $this->call_trigger('HRM_SKILLDET_VALIDATE', $user);
527
                if ($result < 0) {
528
                    $error++;
529
                }
530
                // End call triggers
531
            }
532
        }
533
534
        if (!$error) {
535
            $this->oldref = $this->ref;
536
537
            // Rename directory if dir was a temporary ref
538
            if (preg_match('/^[\(]?PROV/i', $this->ref)) {
539
                // Now we rename also files into index
540
                $sql = 'UPDATE ' . MAIN_DB_PREFIX . "ecm_files set filename = CONCAT('" . $this->db->escape($this->newref) . "', SUBSTR(filename, " . (strlen($this->ref) + 1) . ")), filepath = 'skilldet/" . $this->db->escape($this->newref) . "'";
541
                $sql .= " WHERE filename LIKE '" . $this->db->escape($this->ref) . "%' AND filepath = 'skilldet/" . $this->db->escape($this->ref) . "' and entity = " . $conf->entity;
542
                $resql = $this->db->query($sql);
543
                if (!$resql) {
544
                    $error++;
545
                    $this->error = $this->db->lasterror();
546
                }
547
                $sql = 'UPDATE ' . MAIN_DB_PREFIX . "ecm_files set filepath = 'skilldet/" . $this->db->escape($this->newref) . "'";
548
                $sql .= " WHERE filepath = 'skilldet/" . $this->db->escape($this->ref) . "' and entity = " . $conf->entity;
549
                $resql = $this->db->query($sql);
550
                if (!$resql) {
551
                    $error++;
552
                    $this->error = $this->db->lasterror();
553
                }
554
555
                // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
556
                $oldref = dol_sanitizeFileName($this->ref);
557
                $newref = dol_sanitizeFileName($num);
558
                $dirsource = $conf->hrm->dir_output . '/skilldet/' . $oldref;
559
                $dirdest = $conf->hrm->dir_output . '/skilldet/' . $newref;
560
                if (!$error && file_exists($dirsource)) {
561
                    dol_syslog(get_class($this) . "::validate() rename dir " . $dirsource . " into " . $dirdest);
562
563
                    if (@rename($dirsource, $dirdest)) {
564
                        dol_syslog("Rename ok");
565
                        // Rename docs starting with $oldref with $newref
566
                        $listoffiles = dol_dir_list($conf->hrm->dir_output . '/skilldet/' . $newref, 'files', 1, '^' . preg_quote($oldref, '/'));
567
                        foreach ($listoffiles as $fileentry) {
568
                            $dirsource = $fileentry['name'];
569
                            $dirdest = preg_replace('/^' . preg_quote($oldref, '/') . '/', $newref, $dirsource);
570
                            $dirsource = $fileentry['path'] . '/' . $dirsource;
571
                            $dirdest = $fileentry['path'] . '/' . $dirdest;
572
                            @rename($dirsource, $dirdest);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for rename(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

572
                            /** @scrutinizer ignore-unhandled */ @rename($dirsource, $dirdest);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
573
                        }
574
                    }
575
                }
576
            }
577
        }
578
579
        // Set new ref and current status
580
        if (!$error) {
581
            $this->ref = $num;
582
            $this->status = self::STATUS_VALIDATED;
583
        }
584
585
        if (!$error) {
586
            $this->db->commit();
587
            return 1;
588
        } else {
589
            $this->db->rollback();
590
            return -1;
591
        }
592
    }
593
594
595
    /**
596
     *  Set draft status
597
     *
598
     *  @param  User    $user           Object user that modify
599
     *  @param  int     $notrigger      1=Does not execute triggers, 0=Execute triggers
600
     *  @return int                     Return integer <0 if KO, >0 if OK
601
     */
602
    public function setDraft($user, $notrigger = 0)
603
    {
604
        // Protection
605
        if ($this->status <= self::STATUS_DRAFT) {
606
            return 0;
607
        }
608
609
        /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->hrm->write))
610
         || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->hrm->hrm_advance->validate))))
611
         {
612
         $this->error='Permission denied';
613
         return -1;
614
         }*/
615
616
        return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'SKILLDET_UNVALIDATE');
617
    }
618
619
    /**
620
     *  Set cancel status
621
     *
622
     *  @param  User    $user           Object user that modify
623
     *  @param  int     $notrigger      1=Does not execute triggers, 0=Execute triggers
624
     *  @return int                     Return integer <0 if KO, 0=Nothing done, >0 if OK
625
     */
626
    public function cancel($user, $notrigger = 0)
627
    {
628
        // Protection
629
        if ($this->status != self::STATUS_VALIDATED) {
630
            return 0;
631
        }
632
633
        /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->hrm->write))
634
         || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->hrm->hrm_advance->validate))))
635
         {
636
         $this->error='Permission denied';
637
         return -1;
638
         }*/
639
640
        return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'SKILLDET_CANCEL');
641
    }
642
643
    /**
644
     *  Set back to validated status
645
     *
646
     *  @param  User    $user           Object user that modify
647
     *  @param  int     $notrigger      1=Does not execute triggers, 0=Execute triggers
648
     *  @return int                     Return integer <0 if KO, 0=Nothing done, >0 if OK
649
     */
650
    public function reopen($user, $notrigger = 0)
651
    {
652
        // Protection
653
        if ($this->status != self::STATUS_CANCELED) {
654
            return 0;
655
        }
656
657
        /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->hrm->write))
658
         || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->hrm->hrm_advance->validate))))
659
         {
660
         $this->error='Permission denied';
661
         return -1;
662
         }*/
663
664
        return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'SKILLDET_REOPEN');
665
    }
666
667
    /**
668
     *  Return a link to the object card (with optionally the picto)
669
     *
670
     *  @param  int     $withpicto                  Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
671
     *  @param  string  $option                     On what the link point to ('nolink', ...)
672
     *  @param  int     $notooltip                  1=Disable tooltip
673
     *  @param  string  $morecss                    Add more css on link
674
     *  @param  int     $save_lastsearch_value      -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
675
     *  @return string                              String with URL
676
     */
677
    public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
678
    {
679
        global $conf, $langs, $hookmanager;
680
681
        if (!empty($conf->dol_no_mouse_hover)) {
682
            $notooltip = 1; // Force disable tooltips
683
        }
684
685
        $result = '';
686
687
        $label = img_picto('', $this->picto) . ' <u>' . $langs->trans("Skilldet") . '</u>';
688
        if (isset($this->status)) {
689
            $label .= ' ' . $this->getLibStatut(5);
690
        }
691
        $label .= '<br>';
692
        $label .= '<b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;
693
694
        $url = dol_buildpath('/hrm/skilldet_card.php', 1) . '?id=' . $this->id;
695
696
        if ($option != 'nolink') {
697
            // Add param to save lastsearch_values or not
698
            $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
699
            if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
700
                $add_save_lastsearch_values = 1;
701
            }
702
            if ($add_save_lastsearch_values) {
703
                $url .= '&save_lastsearch_values=1';
704
            }
705
        }
706
707
        $linkclose = '';
708
        if (empty($notooltip)) {
709
            if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
710
                $label = $langs->trans("ShowSkilldet");
711
                $linkclose .= ' alt="' . dol_escape_htmltag($label, 1) . '"';
712
            }
713
            $linkclose .= ' title="' . dol_escape_htmltag($label, 1) . '"';
714
            $linkclose .= ' class="classfortooltip' . ($morecss ? ' ' . $morecss : '') . '"';
715
        } else {
716
            $linkclose = ($morecss ? ' class="' . $morecss . '"' : '');
717
        }
718
719
        if ($option == 'nolink') {
720
            $linkstart = '<span';
721
        } else {
722
            $linkstart = '<a href="' . $url . '"';
723
        }
724
        $linkstart .= $linkclose . '>';
725
        if ($option == 'nolink') {
726
            $linkend = '</span>';
727
        } else {
728
            $linkend = '</a>';
729
        }
730
731
        $result .= $linkstart;
732
733
        if (empty($this->showphoto_on_popup)) {
734
            if ($withpicto) {
735
                $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="' . (($withpicto != 2) ? 'paddingright ' : '') . 'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
736
            }
737
        } else {
738
            if ($withpicto) {
739
                require_once constant('DOL_DOCUMENT_ROOT') . '/core/lib/files.lib.php';
740
741
                list($class, $module) = explode('@', $this->picto);
742
                $upload_dir = $conf->$module->multidir_output[$conf->entity] . "/$class/" . dol_sanitizeFileName($this->ref);
743
                $filearray = dol_dir_list($upload_dir, "files");
744
                $filename = $filearray[0]['name'];
745
                if (!empty($filename)) {
746
                    $pospoint = strpos($filearray[0]['name'], '.');
747
748
                    $pathtophoto = $class . '/' . $this->ref . '/thumbs/' . substr($filename, 0, $pospoint) . '_mini' . substr($filename, $pospoint);
749
                    if (!getDolGlobalString(strtoupper($module . '_' . $class) . '_FORMATLISTPHOTOSASUSERS')) {
750
                        $result .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref"><img class="photo' . $module . '" alt="No photo" border="0" src="' . constant('BASE_URL') . '/viewimage.php?modulepart=' . $module . '&entity=' . $conf->entity . '&file=' . urlencode($pathtophoto) . '"></div></div>';
751
                    } else {
752
                        $result .= '<div class="floatleft inline-block valignmiddle divphotoref"><img class="photouserphoto userphoto" alt="No photo" border="0" src="' . constant('BASE_URL') . '/viewimage.php?modulepart=' . $module . '&entity=' . $conf->entity . '&file=' . urlencode($pathtophoto) . '"></div>';
753
                    }
754
755
                    $result .= '</div>';
756
                } else {
757
                    $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="' . (($withpicto != 2) ? 'paddingright ' : '') . 'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
758
                }
759
            }
760
        }
761
762
        if ($withpicto != 2) {
763
            $result .= $this->ref;
764
        }
765
766
        $result .= $linkend;
767
        //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
768
769
        global $action, $hookmanager;
770
        $hookmanager->initHooks(array('skilldetdao'));
771
        $parameters = array('id' => $this->id, 'getnomurl' => &$result);
772
        $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
773
        if ($reshook > 0) {
774
            $result = $hookmanager->resPrint;
775
        } else {
776
            $result .= $hookmanager->resPrint;
777
        }
778
779
        return $result;
780
    }
781
782
    /**
783
     *  Return the label of the status
784
     *
785
     *  @param  int     $mode          0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
786
     *  @return string                 Label of status
787
     */
788
    public function getLibStatut($mode = 0)
789
    {
790
        return $this->LibStatut($this->status, $mode);
791
    }
792
793
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
794
    /**
795
     *  Return the status
796
     *
797
     *  @param  int     $status        Id status
798
     *  @param  int     $mode          0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
799
     *  @return string                 Label of status
800
     */
801
    public function LibStatut($status, $mode = 0)
802
    {
803
		// phpcs:enable
804
        if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
805
            global $langs;
806
            //$langs->load("hrm");
807
            $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
808
            $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
809
            $this->labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
810
            $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
811
            $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
812
            $this->labelStatusShort[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
813
        }
814
815
        $statusType = 'status' . $status;
816
        //if ($status == self::STATUS_VALIDATED) $statusType = 'status1';
817
        if ($status == self::STATUS_CANCELED) {
818
            $statusType = 'status6';
819
        }
820
821
        return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
822
    }
823
824
    /**
825
     *  Load the info information in the object
826
     *
827
     *  @param  int     $id       Id of object
828
     *  @return void
829
     */
830
    public function info($id)
831
    {
832
        $sql = 'SELECT rowid, date_creation as datec, tms as datem,';
833
        $sql .= ' fk_user_creat, fk_user_modif';
834
        $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t';
835
        $sql .= ' WHERE t.rowid = ' . ((int) $id);
836
        $result = $this->db->query($sql);
837
        if ($result) {
838
            if ($this->db->num_rows($result)) {
839
                $obj = $this->db->fetch_object($result);
840
841
                $this->id = $obj->rowid;
842
843
                $this->user_creation_id = $obj->fk_user_creat;
844
                $this->user_modification_id = $obj->fk_user_modif;
845
                $this->date_creation     = $this->db->jdate($obj->datec);
846
                $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
847
            }
848
849
            $this->db->free($result);
850
        } else {
851
            dol_print_error($this->db);
852
        }
853
    }
854
855
    /**
856
     * Initialise object with example values
857
     * Id must be 0 if object instance is a specimen
858
     *
859
     * @return int
860
     */
861
    public function initAsSpecimen()
862
    {
863
        // Set here init that are not commonf fields
864
        // $this->property1 = ...
865
        // $this->property2 = ...
866
867
        return $this->initAsSpecimenCommon();
868
    }
869
870
871
    /**
872
     *  Returns the reference to the following non used object depending on the active numbering module.
873
     *
874
     *  @return string              Object free reference
875
     */
876
    public function getNextNumRef()
877
    {
878
        global $langs, $conf;
879
        $langs->load("hrm");
880
881
        if (!getDolGlobalString('hrm_SKILLDET_ADDON')) {
882
            $conf->global->hrm_SKILLDET_ADDON = 'mod_skilldet_standard';
883
        }
884
885
        if (getDolGlobalString('hrm_SKILLDET_ADDON')) {
886
            $mybool = false;
887
888
            $file = getDolGlobalString('hrm_SKILLDET_ADDON') . ".php";
889
            $classname = getDolGlobalString('hrm_SKILLDET_ADDON');
890
891
            // Include file with class
892
            $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
893
            foreach ($dirmodels as $reldir) {
894
                $dir = dol_buildpath($reldir . "core/modules/hrm/");
895
896
                // Load file with numbering class (if found)
897
                $mybool = ((bool) @include_once $dir . $file) || $mybool;
898
            }
899
900
            if ($mybool === false) {
901
                dol_print_error(null, "Failed to include file " . $file);
902
                return '';
903
            }
904
905
            if (class_exists($classname)) {
906
                $obj = new $classname();
907
                $numref = $obj->getNextValue($this);
908
909
                if ($numref != '' && $numref != '-1') {
910
                    return $numref;
911
                } else {
912
                    $this->error = $obj->error;
913
                    //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
914
                    return "";
915
                }
916
            } else {
917
                print $langs->trans("Error") . " " . $langs->trans("ClassNotFound") . ' ' . $classname;
918
                return "";
919
            }
920
        } else {
921
            print $langs->trans("ErrorNumberingModuleNotSetup", $this->element);
922
            return "";
923
        }
924
    }
925
926
    /**
927
     *  Create a document onto disk according to template module.
928
     *
929
     *  @param      string      $modele         Force template to use ('' to not force)
930
     *  @param      Translate   $outputlangs    object lang a utiliser pour traduction
931
     *  @param      int         $hidedetails    Hide details of lines
932
     *  @param      int         $hidedesc       Hide description
933
     *  @param      int         $hideref        Hide ref
934
     *  @param      null|array  $moreparams     Array to provide more information
935
     *  @return     int                         0 if KO, 1 if OK
936
     */
937
    public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
938
    {
939
        global $conf, $langs;
940
941
        $result = 0;
942
        $includedocgeneration = 0;
943
944
        $langs->load("hrm");
945
946
        if (!dol_strlen($modele)) {
947
            $modele = 'standard_skilldet';
948
949
            if (!empty($this->model_pdf)) {
950
                $modele = $this->model_pdf;
951
            } elseif (getDolGlobalString('SKILLDET_ADDON_PDF')) {
952
                $modele = getDolGlobalString('SKILLDET_ADDON_PDF');
953
            }
954
        }
955
956
        $modelpath = "core/modules/hrm/doc/";
957
958
        if ($includedocgeneration && !empty($modele)) {
959
            $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
960
        }
961
962
        return $result;
963
    }
964
}
965