Passed
Push — EXTRACT_CLASSES ( ae6b5c...83d77a )
by Rafael
60:14 queued 23:58
created

Workstation::getNomUrl()   F

Complexity

Conditions 31
Paths 8640

Size

Total Lines 102
Code Lines 67

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 31
eloc 67
nc 8640
nop 5
dl 0
loc 102
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) 2017       Laurent Destailleur         <[email protected]>
4
 * Copyright (C) 2020       Gauthier VERDOL             <[email protected]>
5
 * Copyright (C) 2023-2024  Frédéric France             <[email protected]>
6
 * Copyright (C) 2024		MDW							<[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\Workstation\Classes;
24
25
use Dolibarr\Core\Base\CommonObject;
26
27
/**
28
 * \file        htdocs/workstation/class/workstation.class.php
29
 * \ingroup     workstation
30
 * \brief       This file is a CRUD class file for Workstation (Create/Read/Update/Delete)
31
 */
32
33
// Put here all includes required by your class file
34
35
/**
36
 * Class for Workstation
37
 */
38
class Workstation extends CommonObject
39
{
40
    /**
41
     * @var string ID of module.
42
     */
43
    public $module = 'workstation';
44
45
    /**
46
     * @var string ID to identify managed object.
47
     */
48
    public $element = 'workstation';
49
50
    /**
51
     * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management.
52
     */
53
    public $table_element = 'workstation_workstation';
54
55
    /**
56
     * @var int<0,1>|string     Does this object support multicompany module ?
57
     *                          0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table (example 'fk_soc@societe')
58
     */
59
    public $ismultientitymanaged = 1;
60
61
    /**
62
     * @var int<0,1>    Does object support extrafields ? 0=No, 1=Yes
63
     */
64
    public $isextrafieldmanaged = 0;
65
66
    /**
67
     * @var string String with name of icon for workstation. Must be the part after the 'object_' into object_workstation.png
68
     */
69
    public $picto = 'workstation';
70
71
72
    const STATUS_DISABLED = 0;
73
    const STATUS_ENABLED = 1;
74
75
76
    /**
77
     *  'type' if the field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'text:none', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password')
78
     *         Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
79
     *  'label' the translation key.
80
     *  'picto' is code of a picto to show before value in forms
81
     *  'enabled' is a condition when the field must be managed (Example: 1 or 'getDolGlobalString("MY_SETUP_PARAM")'
82
     *  'position' is the sort order of field.
83
     *  'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
84
     *  '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)
85
     *  'noteditable' says if field is not editable (1 or 0)
86
     *  '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.
87
     *  'index' if we want an index in database.
88
     *  'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommended to name the field fk_...).
89
     *  'searchall' is 1 if we want to search in this field when making a search from the quick search button.
90
     *  '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).
91
     *  '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: 'maxwidth200', 'wordbreak', 'tdoverflowmax200'
92
     *  'help' is a string visible as a tooltip on field
93
     *  'showoncombobox' if value of the field must be visible into the label of the combobox that list record
94
     *  '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.
95
     *  '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'
96
     *  'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1.
97
     *  'comment' is not used. You can store here any text of your choice. It is not used by application.
98
     *
99
     *  Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
100
     */
101
102
    // BEGIN MODULEBUILDER PROPERTIES
103
    /**
104
     * @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...
105
     */
106
    public $fields = array(
107
        'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'position' => 1, 'notnull' => 1, 'visible' => 0, 'noteditable' => 1, 'index' => 1, 'css' => 'left', 'comment' => "Id"),
108
        'entity' => array('type' => 'integer', 'label' => 'Entity', 'enabled' => 1, 'visible' => 0, 'position' => 5, 'notnull' => 1, 'default' => '1', 'index' => 1),
109
        'ref' => array('type' => 'varchar(128)', 'label' => 'Ref', 'enabled' => 1, 'position' => 10, 'notnull' => 1, 'visible' => 1, 'noteditable' => 0, 'default' => '', 'index' => 1, 'searchall' => 1, 'showoncombobox' => 1, 'comment' => "Reference of object", 'csslist' => 'nowraponall'),
110
        'label' => array('type' => 'varchar(255)', 'label' => 'Label', 'enabled' => 1, 'position' => 30, 'notnull' => 1, 'visible' => 1, 'searchall' => 1, 'css' => 'minwidth300', 'csslist' => 'tdoverflowmax125', 'showoncombobox' => '2',),
111
        'type' => array('type' => 'varchar(8)', 'label' => 'Type', 'enabled' => 1, 'position' => 32, 'default' => '1', 'notnull' => 1, 'visible' => 1, 'arrayofkeyval' => array('HUMAN' => 'Human', 'MACHINE' => 'Machine', 'BOTH' => 'HumanMachine'),),
112
        'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'position' => 61, 'notnull' => 0, 'visible' => 0,),
113
        'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'position' => 62, 'notnull' => 0, 'visible' => 0,),
114
        'date_creation' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'position' => 500, 'notnull' => 1, 'visible' => -2, 'csslist' => 'nowraponall'),
115
        'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'position' => 501, 'notnull' => 0, 'visible' => -2, 'csslist' => 'nowraponall'),
116
        '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',),
117
        'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => 1, 'position' => 511, 'notnull' => -1, 'visible' => -2,),
118
        'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'position' => 512, 'notnull' => -1, 'visible' => -2,),
119
        'nb_operators_required' => array('type' => 'integer', 'label' => 'NbOperatorsRequired', 'enabled' => 1, 'position' => 50, 'notnull' => 0, 'visible' => 1, 'css' => 'right', 'csslist' => 'maxwidth75imp'),
120
        'thm_operator_estimated' => array('type' => 'double', 'help' => 'THMOperatorEstimatedHelp','label' => 'THMOperatorEstimated', 'enabled' => 1, 'position' => 50, 'notnull' => 0, 'visible' => 1, 'css' => 'right', 'csslist' => 'maxwidth75imp'),
121
        'thm_machine_estimated' => array('type' => 'double', 'help' => 'THMMachineEstimatedHelp', 'label' => 'THMMachineEstimated', 'enabled' => 1, 'position' => 50, 'notnull' => 0, 'visible' => 1, 'css' => 'right', 'csslist' => 'maxwidth75imp'),
122
        'status' => array('type' => 'smallint', 'label' => 'Status', 'enabled' => 1, 'position' => 1000, 'default' => '1', 'notnull' => 1, 'visible' => 1, 'index' => 1, 'arrayofkeyval' => array('0' => 'Disabled', '1' => 'Enabled'),),
123
    );
124
125
    /**
126
     * @var int rowid ID
127
     */
128
    public $rowid;
129
130
    /**
131
     * @var string ref of workstation
132
     */
133
    public $ref;
134
135
    /**
136
     * @var string label of workstation
137
     */
138
    public $label;
139
140
    /**
141
     * @var string type
142
     */
143
    public $type;   // HUMAN, MACHINE, ...
144
145
    /**
146
     * @var integer|string date_creation
147
     */
148
    public $date_creation;
149
150
    /**
151
     * @var int User ID
152
     */
153
    public $fk_user_creat;
154
155
    /**
156
     * @var int User ID
157
     */
158
    public $fk_user_modif;
159
160
    /**
161
     * @var int status enabled or disabled
162
     */
163
    public $status;
164
165
    /**
166
     * @var int nb operators required
167
     */
168
    public $nb_operators_required;
169
170
    /**
171
     * @var float thm operator estimated
172
     */
173
    public $thm_operator_estimated;
174
175
    /**
176
     * @var float thm machine estimated
177
     */
178
    public $thm_machine_estimated;
179
180
    // END MODULEBUILDER PROPERTIES
181
182
    /**
183
     * @var int[] array of ID
184
     */
185
    public $resources;
186
187
    /**
188
     * @var int[] array of ID
189
     */
190
    public $usergroups;
191
192
    /**
193
     * Constructor
194
     *
195
     * @param DoliDB $db Database handler
196
     */
197
    public function __construct(DoliDB $db)
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\Workstation\Classes\DoliDB was not found. Did you mean DoliDB? If so, make sure to prefix the type with \.
Loading history...
198
    {
199
        global $conf, $langs;
200
201
        require_once constant('DOL_DOCUMENT_ROOT') . '/workstation/class/workstationusergroup.class.php';
202
        require_once constant('DOL_DOCUMENT_ROOT') . '/workstation/class/workstationresource.class.php';
203
204
        $this->db = $db;
205
206
        $this->ismultientitymanaged = 1;
207
        $this->isextrafieldmanaged = 0;
208
209
        if (!getDolGlobalString('MAIN_SHOW_TECHNICAL_ID') && isset($this->fields['rowid'])) {
210
            $this->fields['rowid']['visible'] = 0;
211
        }
212
        if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) {
213
            $this->fields['entity']['enabled'] = 0;
214
        }
215
216
        // Unset fields that are disabled
217
        foreach ($this->fields as $key => $val) {
218
            if (isset($val['enabled']) && empty($val['enabled'])) {
219
                unset($this->fields[$key]);
220
            }
221
        }
222
223
        // Translate some data of arrayofkeyval
224
        if (is_object($langs)) {
225
            foreach ($this->fields as $key => $val) {
226
                if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
227
                    foreach ($val['arrayofkeyval'] as $key2 => $val2) {
228
                        $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
229
                    }
230
                }
231
            }
232
        }
233
    }
234
235
    /**
236
     * Create object into database
237
     *
238
     * @param  User $user      User that creates
239
     * @param  int  $notrigger 0=launch triggers after, 1=disable triggers
240
     * @return int             Return integer <0 if KO, Id of created object if OK
241
     */
242
    public function create(User $user, $notrigger = 0)
243
    {
244
        global $db;
245
246
        $id = $this->createCommon($user, $notrigger);
247
248
        // Usergroups
249
        $groups = GETPOST('groups', 'array:int');
250
        if (empty($groups)) {
251
            $groups = $this->usergroups; // createFromClone
252
        }
253
        if (!empty($groups)) {
254
            foreach ($groups as $id_group) {
255
                $ws_usergroup = new WorkstationUserGroup($db);
256
                $ws_usergroup->fk_workstation = $id;
257
                $ws_usergroup->fk_usergroup = $id_group;
258
                $ws_usergroup->createCommon($user);
259
                $this->usergroups[] = $id_group;
260
            }
261
        }
262
263
        // Resources
264
        $resources = GETPOST('resources', 'array:int');
265
        if (empty($resources)) {
266
            $resources = $this->resources; // createFromClone
267
        }
268
        if (!empty($resources)) {
269
            foreach ($resources as $id_resource) {
270
                $ws_resource = new WorkstationResource($db);
271
                $ws_resource->fk_workstation = $id;
272
                $ws_resource->fk_resource = $id_resource;
273
                $ws_resource->createCommon($user);
274
                $this->resources[] = $id_resource;
275
            }
276
        }
277
278
        return $id;
279
    }
280
281
    /**
282
     * Clone an object into another one
283
     *
284
     * @param   User    $user       User that creates
285
     * @param   int     $fromid     Id of object to clone
286
     * @return  mixed               New object created, <0 if KO
287
     */
288
    public function createFromClone(User $user, $fromid)
289
    {
290
        global $langs, $extrafields;
291
        $error = 0;
292
293
        dol_syslog(__METHOD__, LOG_DEBUG);
294
295
        $object = new self($this->db);
296
297
        $this->db->begin();
298
299
        // Load source object
300
        $result = $object->fetch($fromid);
301
        if ($result > 0 && !empty($object->table_element_line)) {
302
            $object->fetchLines();
303
        }
304
305
        // get lines so they will be clone
306
        //foreach($this->lines as $line)
307
        //  $line->fetch_optionals();
308
309
        // Reset some properties
310
        unset($object->id);
311
        unset($object->fk_user_creat);
312
        unset($object->import_key);
313
314
        // Clear fields
315
        if (property_exists($object, 'ref')) {
316
            $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_" . $object->ref : $this->fields['ref']['default'];
317
        }
318
        if (property_exists($object, 'label')) {
319
            $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf") . " " . $object->label : $this->fields['label']['default'];
320
        }
321
        if (property_exists($object, 'status')) {
322
            $object->status = self::STATUS_DISABLED;
323
        }
324
        if (property_exists($object, 'date_creation')) {
325
            $object->date_creation = dol_now();
326
        }
327
        if (property_exists($object, 'date_modification')) {
328
            $object->date_modification = null;
329
        }
330
        // ...
331
        // Clear extrafields that are unique
332
        if (is_array($object->array_options) && count($object->array_options) > 0) {
333
            $extrafields->fetch_name_optionals_label($this->table_element);
334
            foreach ($object->array_options as $key => $option) {
335
                $shortkey = preg_replace('/options_/', '', $key);
336
                if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) {
337
                    //var_dump($key);
338
                    //var_dump($clonedObj->array_options[$key]); exit;
339
                    unset($object->array_options[$key]);
340
                }
341
            }
342
        }
343
344
        // Create clone
345
        $object->context['createfromclone'] = 'createfromclone';
346
        $result = $object->create($user);
347
        if ($result < 0) {
348
            $error++;
349
            $this->error = $object->error;
350
            $this->errors = $object->errors;
351
        }
352
353
        if (!$error) {
354
            // copy internal contacts
355
            if ($this->copy_linked_contact($object, 'internal') < 0) {
356
                $error++;
357
            }
358
        }
359
360
        if (!$error) {
361
            // copy external contacts if same company
362
            if (property_exists($this, 'socid') && $this->socid == $object->socid) {
363
                if ($this->copy_linked_contact($object, 'external') < 0) {
364
                    $error++;
365
                }
366
            }
367
        }
368
369
        unset($object->context['createfromclone']);
370
371
        // End
372
        if (!$error) {
373
            $this->db->commit();
374
            return $object;
375
        } else {
376
            $this->db->rollback();
377
            return -1;
378
        }
379
    }
380
381
    /**
382
     * Load object in memory from the database
383
     *
384
     * @param int    $id   Id object
385
     * @param string $ref  Ref
386
     * @return int         Return integer <0 if KO, 0 if not found, >0 if OK
387
     */
388
    public function fetch($id, $ref = null)
389
    {
390
        $result = $this->fetchCommon($id, $ref);
391
392
        $this->usergroups = WorkstationUserGroup::getAllGroupsOfWorkstation($this->id);
393
        $this->resources = WorkstationResource::getAllResourcesOfWorkstation($this->id);
394
395
        if ($result > 0 && !empty($this->table_element_line)) {
396
            $this->fetchLines();
397
        }
398
        return $result;
399
    }
400
401
    /**
402
     * Load object lines in memory from the database
403
     *
404
     * @return int         Return integer <0 if KO, 0 if not found, >0 if OK
405
     */
406
    public function fetchLines()
407
    {
408
        $this->lines = array();
409
410
        $result = $this->fetchLinesCommon();
411
        return $result;
412
    }
413
414
415
    /**
416
     * Load list of objects in memory from the database.
417
     *
418
     * @param  string       $sortorder      Sort Order
419
     * @param  string       $sortfield      Sort field
420
     * @param  int          $limit          limit
421
     * @param  int          $offset         Offset
422
     * @param  string       $filter         Filter as an Universal Search string.
423
     *                                      Example: '((client:=:1) OR ((client:>=:2) AND (client:<=:3))) AND (client:!=:8) AND (nom:like:'a%')'
424
     * @param  string       $filtermode     No more used
425
     * @return array|int                    int <0 if KO, array of pages if OK
426
     */
427
    public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, $filter = '', $filtermode = 'AND')
428
    {
429
        dol_syslog(__METHOD__, LOG_DEBUG);
430
431
        $records = array();
432
433
        $sql = 'SELECT ';
434
        $sql .= $this->getFieldList();
435
        $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t';
436
        if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
437
            $sql .= ' WHERE t.entity IN (' . getEntity($this->element) . ')';
438
        } else {
439
            $sql .= ' WHERE 1 = 1';
440
        }
441
442
        // Manage filter
443
        $errormessage = '';
444
        $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
445
        if ($errormessage) {
446
            $this->errors[] = $errormessage;
447
            dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
448
            return -1;
449
        }
450
451
        if (!empty($sortfield)) {
452
            $sql .= $this->db->order($sortfield, $sortorder);
453
        }
454
        if (!empty($limit)) {
455
            $sql .= $this->db->plimit($limit, $offset);
456
        }
457
458
        $resql = $this->db->query($sql);
459
        if ($resql) {
460
            $num = $this->db->num_rows($resql);
461
            $i = 0;
462
            while ($i < ($limit ? min($limit, $num) : $num)) {
463
                $obj = $this->db->fetch_object($resql);
464
465
                $record = new self($this->db);
466
                $record->setVarsFromFetchObj($obj);
467
468
                $records[$record->id] = $record;
469
470
                $i++;
471
            }
472
            $this->db->free($resql);
473
474
            return $records;
475
        } else {
476
            $this->errors[] = 'Error ' . $this->db->lasterror();
477
            dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
478
479
            return -1;
480
        }
481
    }
482
483
    /**
484
     * Update object into database
485
     *
486
     * @param  User $user      User that modifies
487
     * @param  int  $notrigger 0=launch triggers after, 1=disable triggers
488
     * @return int             Return integer <0 if KO, >0 if OK
489
     */
490
    public function update(User $user, $notrigger = 0)
491
    {
492
493
        // Usergroups
494
        $groups = GETPOST('groups', 'array:int');
495
        WorkstationUserGroup::deleteAllGroupsOfWorkstation($this->id);
496
        $this->usergroups = array();
497
498
        foreach ($groups as $id_group) {
499
            $ws_usergroup = new WorkstationUserGroup($this->db);
500
            $ws_usergroup->fk_workstation = $this->id;
501
            $ws_usergroup->fk_usergroup = $id_group;
502
            $ws_usergroup->createCommon($user);
503
            $this->usergroups[] = $id_group;
504
        }
505
506
        // Resources
507
        $resources = GETPOST('resources', 'array:int');
508
        WorkstationResource::deleteAllResourcesOfWorkstation($this->id);
509
        $this->resources = array();
510
        if (!empty($resources)) {
511
            foreach ($resources as $id_resource) {
512
                $ws_resource = new WorkstationResource($this->db);
513
                $ws_resource->fk_workstation = $this->id;
514
                $ws_resource->fk_resource = $id_resource;
515
                $ws_resource->createCommon($user);
516
                $this->resources[] = $id_resource;
517
            }
518
        }
519
520
        return $this->updateCommon($user, $notrigger);
521
    }
522
523
    /**
524
     * Delete object in database
525
     *
526
     * @param User  $user       User that deletes
527
     * @param int   $notrigger  0=launch triggers after, 1=disable triggers
528
     * @return int              Return integer <0 if KO, >0 if OK
529
     */
530
    public function delete(User $user, $notrigger = 0)
531
    {
532
        return $this->deleteCommon($user, $notrigger);
533
        //return $this->deleteCommon($user, $notrigger, 1);
534
    }
535
536
    /**
537
     *  Delete a line of object in database
538
     *
539
     *  @param  User    $user       User that delete
540
     *  @param  int     $idline     Id of line to delete
541
     *  @param  int     $notrigger  0=launch triggers after, 1=disable triggers
542
     *  @return int                 Return >0 if OK, <0 if KO
543
     */
544
    public function deleteLine(User $user, $idline, $notrigger = 0)
545
    {
546
        if ($this->status < 0) {
547
            $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
548
            return -2;
549
        }
550
551
        return $this->deleteLineCommon($user, $idline, $notrigger);
552
    }
553
554
    /**
555
     *  Set draft status
556
     *
557
     *  @param  int $status         New status to set
558
     *  @param  int     $notrigger      1=Does not execute triggers, 0=Execute triggers
559
     *  @return int                     Return integer <0 if KO, >0 if OK
560
     */
561
    public function setStatus($status, $notrigger = 0)
562
    {
563
        global $user;
564
565
        $this->status = $status;
566
567
        if (empty($status)) {
568
            return $this->setDisabled($user, $notrigger);
569
        } else {
570
            return $this->setEnabled($user, $notrigger);
571
        }
572
    }
573
574
575
    /**
576
     *  Set draft status
577
     *
578
     *  @param  User    $user           Object user that modify
579
     *  @param  int     $notrigger      1=Does not execute triggers, 0=Execute triggers
580
     *  @return int                     Return integer <0 if KO, >0 if OK
581
     */
582
    public function setEnabled($user, $notrigger = 0)
583
    {
584
        return $this->setStatusCommon($user, self::STATUS_ENABLED, $notrigger, 'WORKSTATION_ENABLED');
585
    }
586
587
588
    /**
589
     *  Set draft status
590
     *
591
     *  @param  User    $user           Object user that modify
592
     *  @param  int     $notrigger      1=Does not execute triggers, 0=Execute triggers
593
     *  @return int                     Return integer <0 if KO, >0 if OK
594
     */
595
    public function setDisabled($user, $notrigger = 0)
596
    {
597
        return $this->setStatusCommon($user, self::STATUS_DISABLED, $notrigger, 'WORKSTATION_DISABLED');
598
    }
599
600
    /**
601
     * getTooltipContentArray
602
     *
603
     * @param array $params ex option, infologin
604
     * @since v18
605
     * @return array
606
     */
607
    public function getTooltipContentArray($params)
608
    {
609
        global $conf, $langs;
610
611
        $langs->load('mrp');
612
613
        $datas = [];
614
        $datas['picto'] = img_picto('', $this->picto) . ' <u>' . $langs->trans("Workstation") . '</u>';
615
        $datas['ref'] = '<br><b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;
616
        if (isset($this->status)) {
617
            $datas['status'] = '<br><b>' . $langs->trans("Status") . ":</b> " . $this->getLibStatut(5);
618
        }
619
620
        return $datas;
621
    }
622
623
    /**
624
     *  Return a link to the object card (with optionally the picto)
625
     *
626
     *  @param  int     $withpicto                  Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
627
     *  @param  string  $option                     On what the link point to ('nolink', ...)
628
     *  @param  int     $notooltip                  1=Disable tooltip
629
     *  @param  string  $morecss                    Add more css on link
630
     *  @param  int     $save_lastsearch_value      -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
631
     *  @return string                              String with URL
632
     */
633
    public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
634
    {
635
        global $conf, $langs, $hookmanager;
636
637
        if (!empty($conf->dol_no_mouse_hover)) {
638
            $notooltip = 1; // Force disable tooltips
639
        }
640
641
        $result = '';
642
643
        $params = [
644
            'id' => $this->id,
645
            'objecttype' => $this->element,
646
        ];
647
        $classfortooltip = 'classfortooltip';
648
        $dataparams = '';
649
        if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
650
            $classfortooltip = 'classforajaxtooltip';
651
            $dataparams = ' data-params="' . dol_escape_htmltag(json_encode($params)) . '"';
652
            $label = '';
653
        } else {
654
            $label = implode($this->getTooltipContentArray($params));
655
        }
656
657
        $url = dol_buildpath('/workstation/workstation_card.php', 1) . '?id=' . $this->id;
658
659
        if ($option != 'nolink') {
660
            // Add param to save lastsearch_values or not
661
            $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
662
            if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
663
                $add_save_lastsearch_values = 1;
664
            }
665
            if ($add_save_lastsearch_values) {
666
                $url .= '&save_lastsearch_values=1';
667
            }
668
        }
669
670
        $linkclose = '';
671
        if (empty($notooltip)) {
672
            if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
673
                $label = $langs->trans("ShowWorkstation");
674
                $linkclose .= ' alt="' . dol_escape_htmltag($label, 1) . '"';
675
            }
676
            $linkclose .= ($label ? ' title="' . dol_escape_htmltag($label, 1) . '"' : ' title="tocomplete"');
677
            $linkclose .= $dataparams . ' class="' . $classfortooltip . ($morecss ? ' ' . $morecss : '') . '"';
678
        } else {
679
            $linkclose = ($morecss ? ' class="' . $morecss . '"' : '');
680
        }
681
682
        $linkstart = '<a href="' . $url . '"';
683
        $linkstart .= $linkclose . '>';
684
        $linkend = '</a>';
685
686
        $result .= $linkstart;
687
688
        if (empty($this->showphoto_on_popup)) {
689
            if ($withpicto) {
690
                $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'mrp'), (($withpicto != 2) ? 'class="paddingright"' : ''), 0, 0, $notooltip ? 0 : 1);
691
            }
692
        } else {
693
            if ($withpicto) {
694
                require_once constant('DOL_DOCUMENT_ROOT') . '/core/lib/files.lib.php';
695
696
                list($class, $module) = explode('@', $this->picto);
697
                $upload_dir = $conf->$module->multidir_output[$conf->entity] . "/$class/" . dol_sanitizeFileName($this->ref);
698
                $filearray = dol_dir_list($upload_dir, "files");
699
                $filename = $filearray[0]['name'];
700
                if (!empty($filename)) {
701
                    $pospoint = strpos($filearray[0]['name'], '.');
702
703
                    $pathtophoto = $class . '/' . $this->ref . '/thumbs/' . substr($filename, 0, $pospoint) . '_mini' . substr($filename, $pospoint);
704
                    if (!getDolGlobalString(strtoupper($module . '_' . $class) . '_FORMATLISTPHOTOSASUSERS')) {
705
                        $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>';
706
                    } else {
707
                        $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>';
708
                    }
709
710
                    $result .= '</div>';
711
                } else {
712
                    $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'mrp'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="' . (($withpicto != 2) ? 'paddingright ' : '') . 'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
713
                }
714
            }
715
        }
716
717
        if ($withpicto != 2) {
718
            $result .= $this->ref;
719
        }
720
721
        $result .= $linkend;
722
        //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
723
724
        global $action, $hookmanager;
725
        $hookmanager->initHooks(array('workstationdao'));
726
        $parameters = array('id' => $this->id, 'getnomurl' => &$result);
727
        $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
728
        if ($reshook > 0) {
729
            $result = $hookmanager->resPrint;
730
        } else {
731
            $result .= $hookmanager->resPrint;
732
        }
733
734
        return $result;
735
    }
736
737
    /**
738
     *  Return a thumb for kanban views
739
     *
740
     *  @param      string      $option                 Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
741
     *  @param      array       $arraydata              Array of data
742
     *  @return     string                              HTML Code for Kanban thumb.
743
     */
744
    public function getKanbanView($option = '', $arraydata = null)
745
    {
746
        global $conf, $langs;
747
748
        $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
749
750
        $return = '<div class="box-flex-item box-flex-grow-zero">';
751
        $return .= '<div class="info-box info-box-sm">';
752
        $return .= '<span class="info-box-icon bg-infobox-action">';
753
        $return .= img_picto('', $this->picto);
754
        $return .= '</span>';
755
        $return .= '<div class="info-box-content">';
756
        $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">' . (method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref) . '</span>';
757
        if ($selected >= 0) {
758
            $return .= '<input id="cb' . $this->id . '" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="' . $this->id . '"' . ($selected ? ' checked="checked"' : '') . '>';
759
        }
760
        if (property_exists($this, 'label')) {
761
            $return .= ' <div class="inline-block opacitymedium valignmiddle tdoverflowmax100">' . $this->label . '</div>';
762
        }
763
        if (property_exists($this, 'thirdparty') && is_object($this->thirdparty)) {
764
            $return .= '<br><div class="info-box-ref tdoverflowmax150">' . $this->thirdparty->getNomUrl(1) . '</div>';
765
        }
766
        if (property_exists($this, 'amount')) {
767
            $return .= '<br>';
768
            $return .= '<span class="info-box-label amount">' . price($this->amount, 0, $langs, 1, -1, -1, $conf->currency) . '</span>';
0 ignored issues
show
Bug Best Practice introduced by
The property amount does not exist on Dolibarr\Code\Workstation\Classes\Workstation. Since you implemented __get, consider adding a @property annotation.
Loading history...
769
        }
770
        if (method_exists($this, 'getLibStatut')) {
771
            $return .= '<br><div class="info-box-status">' . $this->getLibStatut(3) . '</div>';
772
        }
773
        $return .= '</div>';
774
        $return .= '</div>';
775
        $return .= '</div>';
776
777
        return $return;
778
    }
779
780
    /**
781
     *  Return the label of the status
782
     *
783
     *  @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
784
     *  @return string                 Label of status
785
     */
786
    public function getLibStatut($mode = 0)
787
    {
788
        return $this->LibStatut($this->status, $mode);
789
    }
790
791
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
792
    /**
793
     *  Return the status
794
     *
795
     *  @param  int     $status        Id status
796
     *  @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
797
     *  @return string                 Label of status
798
     */
799
    public function LibStatut($status, $mode = 0)
800
    {
801
		// phpcs:enable
802
        if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
803
            global $langs;
804
            //$langs->load("workstation");
805
            $this->labelStatus[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv('Disabled');
806
            $this->labelStatus[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv('Enabled');
807
            $this->labelStatusShort[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv('Disabled');
808
            $this->labelStatusShort[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv('Enabled');
809
        }
810
811
        $statusType = 'status' . $status;
812
        //if ($status == self::STATUS_DISABLED) $statusType = 'status6';
813
        if ($status == self::STATUS_ENABLED) {
814
            $statusType = 'status4';
815
        }
816
817
        return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
818
    }
819
820
    /**
821
     *  Load the info information in the object
822
     *
823
     *  @param  int     $id       Id of object
824
     *  @return void
825
     */
826
    public function info($id)
827
    {
828
        $sql = 'SELECT rowid, date_creation as datec, tms as datem,';
829
        $sql .= ' fk_user_creat, fk_user_modif';
830
        $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t';
831
        $sql .= ' WHERE t.rowid = ' . ((int) $id);
832
        $result = $this->db->query($sql);
833
        if ($result) {
834
            if ($this->db->num_rows($result)) {
835
                $obj = $this->db->fetch_object($result);
836
837
                $this->id = $obj->rowid;
838
839
                $this->user_creation_id = $obj->fk_user_creat;
840
                $this->user_modification_id = $obj->fk_user_modif;
841
                $this->date_creation = $this->db->jdate($obj->datec);
842
                $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
843
            }
844
845
            $this->db->free($result);
846
        } else {
847
            dol_print_error($this->db);
848
        }
849
    }
850
851
    /**
852
     * Initialise object with example values
853
     * Id must be 0 if object instance is a specimen
854
     *
855
     * @return int
856
     */
857
    public function initAsSpecimen()
858
    {
859
        return $this->initAsSpecimenCommon();
860
    }
861
862
    /**
863
     *  Returns the reference to the following non used object depending on the active numbering module.
864
     *
865
     *  @return string              Object free reference
866
     */
867
    public function getNextNumRef()
868
    {
869
        global $langs, $conf;
870
        $langs->load("workstation");
871
872
        if (!getDolGlobalString('WORKSTATION_WORKSTATION_ADDON')) {
873
            $conf->global->WORKSTATION_WORKSTATION_ADDON = 'mod_workstation_standard';
874
        }
875
876
        if (getDolGlobalString('WORKSTATION_WORKSTATION_ADDON')) {
877
            $mybool = false;
878
879
            $file = getDolGlobalString('WORKSTATION_WORKSTATION_ADDON') . ".php";
880
            $classname = getDolGlobalString('WORKSTATION_WORKSTATION_ADDON');
881
882
            // Include file with class
883
            $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
884
            foreach ($dirmodels as $reldir) {
885
                $dir = dol_buildpath($reldir . "core/modules/workstation/");
886
887
                // Load file with numbering class (if found)
888
                if (file_exists($dir . $file)) {
889
                    $mybool = ((bool) @include_once $dir . $file) || $mybool;
890
                }
891
            }
892
893
            if ($mybool === false) {
894
                dol_print_error(null, "Failed to include file " . $file);
895
                return '';
896
            }
897
898
            if (class_exists($classname)) {
899
                $obj = new $classname();
900
                $numref = $obj->getNextValue($this);
901
902
                if ($numref != '' && $numref != '-1') {
903
                    return $numref;
904
                } else {
905
                    $this->error = $obj->error;
906
                    //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
907
                    return "";
908
                }
909
            } else {
910
                print $langs->trans("Error") . " " . $langs->trans("ClassNotFound") . ' ' . $classname;
911
                return "";
912
            }
913
        } else {
914
            print $langs->trans("ErrorNumberingModuleNotSetup", $this->element);
915
            return "";
916
        }
917
    }
918
919
    /**
920
     *  Create a document onto disk according to template module.
921
     *
922
     *  @param      string      $modele         Force template to use ('' to not force)
923
     *  @param      Translate   $outputlangs    object lang a utiliser pour traduction
924
     *  @param      int         $hidedetails    Hide details of lines
925
     *  @param      int         $hidedesc       Hide description
926
     *  @param      int         $hideref        Hide ref
927
     *  @param      null|array  $moreparams     Array to provide more information
928
     *  @return     int                         0 if KO, 1 if OK
929
     */
930
    public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
931
    {
932
        global $conf, $langs;
933
934
        $result = 0;
935
        $includedocgeneration = 0;
936
937
        $langs->load("workstation");
938
939
        if (!dol_strlen($modele)) {
940
            $modele = 'standard_workstation';
941
942
            if ($this->model_pdf) {
943
                $modele = $this->model_pdf;
944
            } elseif (getDolGlobalString('WORKSTATION_ADDON_PDF')) {
945
                $modele = getDolGlobalString('WORKSTATION_ADDON_PDF');
946
            }
947
        }
948
949
        $modelpath = "core/modules/workstation/doc/";
950
951
        if ($includedocgeneration) {
952
            $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
953
        }
954
955
        return $result;
956
    }
957
}
958