Passed
Push — EXTRACT_CLASSES ( 231cec...0382f2 )
by Rafael
65:54 queued 05:18
created

AssetModel::__construct()   C

Complexity

Conditions 13
Paths 60

Size

Total Lines 30
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 13
eloc 16
nc 60
nop 1
dl 0
loc 30
rs 6.6166
c 0
b 0
f 0

How to fix   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) 2021       Open-Dsi  			<[email protected]>
5
 * Copyright (C) 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\Asset\Classes;
24
25
/**
26
 * \file        htdocs/asset/class/assetmodel.class.php
27
 * \ingroup     asset
28
 * \brief       This file is a CRUD class file for AssetModel (Create/Read/Update/Delete)
29
 */
30
31
// Put here all includes required by your class file
32
use Dolibarr\Core\Base\CommonObject;
33
use DoliDB;
34
35
//require_once constant('DOL_DOCUMENT_ROOT') . '/societe/class/societe.class.php';
36
//require_once constant('DOL_DOCUMENT_ROOT') . '/product/class/product.class.php';
37
38
/**
39
 * Class for AssetModel
40
 */
41
class AssetModel extends CommonObject
42
{
43
    /**
44
     * @var string ID of module.
45
     */
46
    public $module = 'asset';
47
48
    /**
49
     * @var string ID to identify managed object.
50
     */
51
    public $element = 'assetmodel';
52
53
    /**
54
     * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management.
55
     */
56
    public $table_element = 'asset_model';
57
58
    /**
59
     * @var string String with name of icon for assetmodel. Must be the part after the 'object_' into object_assetmodel.png
60
     */
61
    public $picto = 'asset';
62
63
64
    const STATUS_DRAFT = 0;
65
    const STATUS_VALIDATED = 1;
66
    const STATUS_CANCELED = 9;
67
68
69
    /**
70
     *  'type' field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]', 'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter[:Sortfield]]]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'text:none', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password')
71
     *         Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
72
     *  'label' the translation key.
73
     *  'picto' is code of a picto to show before value in forms
74
     *  'enabled' is a condition when the field must be managed (Example: 1 or 'getDolGlobalString("MY_SETUP_PARAM")'
75
     *  'position' is the sort order of field.
76
     *  'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
77
     *  '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)
78
     *  'noteditable' says if field is not editable (1 or 0)
79
     *  '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.
80
     *  'index' if we want an index in database.
81
     *  'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommended to name the field fk_...).
82
     *  'searchall' is 1 if we want to search in this field when making a search from the quick search button.
83
     *  'isameasure' must be set to 1 or 2 if field can be used for measure. Field type must be summable like integer or double(24,8). Use 1 in most cases, or 2 if you don't want to see the column total into list (for example for percentage)
84
     *  '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'
85
     *  'help' is a 'TranslationString' to use to show a tooltip on field. You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
86
     *  'showoncombobox' if value of the field must be visible into the label of the combobox that list record
87
     *  '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.
88
     *  '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'
89
     *  'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1.
90
     *  'comment' is not used. You can store here any text of your choice. It is not used by application.
91
     *  'validate' is 1 if need to validate with $this->validateField()
92
     *  'copytoclipboard' is 1 or 2 to allow to add a picto to copy value into clipboard (1=picto after label, 2=picto after value)
93
     *
94
     *  Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
95
     */
96
97
    /**
98
     * @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...
99
     */
100
    public $fields = array(
101
        'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'position' => 1, 'notnull' => 1, 'visible' => 0, 'noteditable' => 1, 'index' => 1, 'css' => 'left', 'comment' => "Id"),
102
        'ref' => array('type' => 'varchar(128)', 'label' => 'Ref', 'enabled' => 1, 'position' => 20, 'notnull' => 1, 'visible' => 1, 'index' => 1, 'searchall' => 1, 'showoncombobox' => 1, 'validate' => 1),
103
        'label' => array('type' => 'varchar(255)', 'label' => 'Label', 'enabled' => 1, 'position' => 30, 'notnull' => 1, 'visible' => 1, 'searchall' => 1, 'css' => 'minwidth300', 'cssview' => 'wordbreak', 'showoncombobox' => '2', 'validate' => 1,),
104
        'asset_type' => array('type' => 'smallint', 'label' => 'AssetType', 'enabled' => 1, 'position' => 40, 'notnull' => 1, 'visible' => 1, 'arrayofkeyval' => array('0' => 'AssetTypeIntangible', '1' => 'AssetTypeTangible', '2' => 'AssetTypeInProgress', '3' => 'AssetTypeFinancial'), 'validate' => 1,),
105
        'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'position' => 300, 'notnull' => 0, 'visible' => 0, 'validate' => 1,),
106
        'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'position' => 301, 'notnull' => 0, 'visible' => 0, 'validate' => 1,),
107
        'date_creation' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'position' => 500, 'notnull' => 1, 'visible' => -2,),
108
        'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'position' => 501, 'notnull' => 0, 'visible' => -2,),
109
        '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',),
110
        'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => 1, 'position' => 511, 'notnull' => -1, 'visible' => -2,),
111
        'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'position' => 1000, 'notnull' => -1, 'visible' => -2,),
112
        'status' => array('type' => 'smallint', 'label' => 'Status', 'enabled' => 1, 'position' => 1000, 'notnull' => 1, 'default' => '1', 'visible' => 1, 'index' => 1, 'arrayofkeyval' => array('0' => 'Draft', '1' => 'Enabled', '9' => 'Disabled'), 'validate' => 1,),
113
    );
114
    public $rowid;
115
    public $ref;
116
    public $label;
117
    public $asset_type;
118
    public $note_public;
119
    public $note_private;
120
    public $date_creation;
121
    public $fk_user_creat;
122
    public $fk_user_modif;
123
    public $last_main_doc;
124
    public $import_key;
125
    public $model_pdf;
126
    public $status;
127
    public $asset_depreciation_options;
128
    public $asset_accountancy_codes;
129
130
    // /**
131
    //  * @var string    Field with ID of parent key if this object has a parent
132
    //  */
133
    // public $fk_element = 'fk_assetmodel';
134
    // /**
135
    //  * @var array    List of child tables. To test if we can delete object.
136
    //  */
137
    // protected $childtables = array();
138
    // /**
139
    //  * @var array    List of child tables. To know object to delete on cascade.
140
    //  *               If name matches '@ClassNAme:FilePathClass;ParentFkFieldName' it will
141
    //  *               call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object
142
    //  */
143
    // protected $childtablesoncascade = array('asset_assetmodeldet');
144
145
146
    /**
147
     * Constructor
148
     *
149
     * @param DoliDB $db Database handler
150
     */
151
    public function __construct(DoliDB $db)
152
    {
153
        global $conf, $langs;
154
155
        $this->db = $db;
0 ignored issues
show
Documentation Bug introduced by
It seems like $db of type DoliDB is incompatible with the declared type Dolibarr\Core\Base\DoliDB of property $db.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
156
157
        $this->ismultientitymanaged = 1;
158
159
        $this->isextrafieldmanaged = 1;
160
161
        if (!getDolGlobalString('MAIN_SHOW_TECHNICAL_ID') && isset($this->fields['rowid'])) {
162
            $this->fields['rowid']['visible'] = 0;
163
        }
164
        if (!isModEnabled('multicompany') && isset($this->fields['entity'])) {
165
            $this->fields['entity']['enabled'] = 0;
166
        }
167
168
        // Unset fields that are disabled
169
        foreach ($this->fields as $key => $val) {
170
            if (isset($val['enabled']) && empty($val['enabled'])) {
171
                unset($this->fields[$key]);
172
            }
173
        }
174
175
        // Translate some data of arrayofkeyval
176
        if (is_object($langs)) {
177
            foreach ($this->fields as $key => $val) {
178
                if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
179
                    foreach ($val['arrayofkeyval'] as $key2 => $val2) {
180
                        $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
181
                    }
182
                }
183
            }
184
        }
185
    }
186
187
    /**
188
     * Create object into database
189
     *
190
     * @param  User $user      User that creates
191
     * @param  int  $notrigger false=launch triggers after, true=disable triggers
192
     * @return int             Return integer <0 if KO, Id of created object if OK
193
     */
194
    public function create(User $user, $notrigger = 0)
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\Asset\Classes\User was not found. Did you mean User? If so, make sure to prefix the type with \.
Loading history...
195
    {
196
        $resultcreate = $this->createCommon($user, $notrigger);
197
198
        if ($resultcreate > 0 && !empty($this->asset_depreciation_options)) {
199
            $this->asset_depreciation_options->setDeprecationOptionsFromPost(1);
200
            $this->asset_depreciation_options->updateDeprecationOptions($user, 0, $resultcreate);
201
        }
202
203
        if ($resultcreate > 0 && !empty($this->asset_accountancy_codes)) {
204
            $this->asset_accountancy_codes->setAccountancyCodesFromPost();
205
            $this->asset_accountancy_codes->updateAccountancyCodes($user, 0, $resultcreate);
206
        }
207
208
        return $resultcreate;
209
    }
210
211
    /**
212
     * Clone an object into another one
213
     *
214
     * @param   User    $user       User that creates
215
     * @param   int     $fromid     Id of object to clone
216
     * @return  mixed               New object created, <0 if KO
217
     */
218
    public function createFromClone(User $user, $fromid)
219
    {
220
        global $langs, $extrafields;
221
        $error = 0;
222
223
        dol_syslog(__METHOD__, LOG_DEBUG);
224
225
        $object = new self($this->db);
226
227
        $this->db->begin();
228
229
        // Load source object
230
        $result = $object->fetchCommon($fromid);
231
        if ($result > 0 && !empty($object->table_element_line)) {
232
            $object->fetchLines();
233
        }
234
235
        // get lines so they will be clone
236
        //foreach($this->lines as $line)
237
        //  $line->fetch_optionals();
238
239
        // Reset some properties
240
        unset($object->id);
241
        unset($object->fk_user_creat);
242
        unset($object->import_key);
243
244
        // Clear fields
245
        if (property_exists($object, 'ref')) {
246
            $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_" . $object->ref : $this->fields['ref']['default'];
247
        }
248
        if (property_exists($object, 'label')) {
249
            $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf") . " " . $object->label : $this->fields['label']['default'];
250
        }
251
        if (property_exists($object, 'status')) {
252
            $object->status = self::STATUS_DRAFT;
253
        }
254
        if (property_exists($object, 'date_creation')) {
255
            $object->date_creation = dol_now();
256
        }
257
        if (property_exists($object, 'date_modification')) {
258
            $object->date_modification = null;
259
        }
260
        // ...
261
        // Clear extrafields that are unique
262
        if (is_array($object->array_options) && count($object->array_options) > 0) {
263
            $extrafields->fetch_name_optionals_label($this->table_element);
264
            foreach ($object->array_options as $key => $option) {
265
                $shortkey = preg_replace('/options_/', '', $key);
266
                if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) {
267
                    //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
268
                    unset($object->array_options[$key]);
269
                }
270
            }
271
        }
272
273
        // Create clone
274
        $object->context['createfromclone'] = 'createfromclone';
275
        $result = $object->createCommon($user);
276
        if ($result < 0) {
277
            $error++;
278
            $this->error = $object->error;
279
            $this->errors = $object->errors;
280
        }
281
282
        if (!$error) {
283
            // copy internal contacts
284
            if ($this->copy_linked_contact($object, 'internal') < 0) {
285
                $error++;
286
            }
287
        }
288
289
        if (!$error) {
290
            // copy external contacts if same company
291
            if (property_exists($this, 'fk_soc') && $this->fk_soc == $object->socid) {
292
                if ($this->copy_linked_contact($object, 'external') < 0) {
293
                    $error++;
294
                }
295
            }
296
        }
297
298
        unset($object->context['createfromclone']);
299
300
        // End
301
        if (!$error) {
302
            $this->db->commit();
303
            return $object;
304
        } else {
305
            $this->db->rollback();
306
            return -1;
307
        }
308
    }
309
310
    /**
311
     * Load object in memory from the database
312
     *
313
     * @param int    $id   Id object
314
     * @param string $ref  Ref
315
     * @return int         Return integer <0 if KO, 0 if not found, >0 if OK
316
     */
317
    public function fetch($id, $ref = null)
318
    {
319
        $result = $this->fetchCommon($id, $ref);
320
        if ($result > 0 && !empty($this->table_element_line)) {
321
            $this->fetchLines();
322
        }
323
        return $result;
324
    }
325
326
    /**
327
     * Load object lines in memory from the database
328
     *
329
     * @return int         Return integer <0 if KO, 0 if not found, >0 if OK
330
     */
331
    public function fetchLines()
332
    {
333
        $this->lines = array();
334
335
        return 1;
336
    }
337
338
339
    /**
340
     * Load list of objects in memory from the database.
341
     *
342
     * @param  string       $sortorder      Sort Order
343
     * @param  string       $sortfield       Sort field
344
     * @param  int          $limit          limit
345
     * @param  int          $offset         Offset
346
     * @param  string       $filter         Filter as an Universal Search string.
347
     *                                      Example: '((client:=:1) OR ((client:>=:2) AND (client:<=:3))) AND (client:!=:8) AND (nom:like:'a%')'
348
     * @param  string       $filtermode     No more used
349
     * @return array|int                    int <0 if KO, array of pages if OK
350
     */
351
    public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, $filter = '', $filtermode = 'AND')
352
    {
353
        dol_syslog(__METHOD__, LOG_DEBUG);
354
355
        $records = array();
356
357
        $sql = "SELECT ";
358
        $sql .= $this->getFieldList('t');
359
        $sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element . " as t";
360
        if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
361
            $sql .= " WHERE t.entity IN (" . getEntity($this->element) . ")";
362
        } else {
363
            $sql .= " WHERE 1 = 1";
364
        }
365
366
        // Manage filter
367
        $errormessage = '';
368
        $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
369
        if ($errormessage) {
370
            $this->errors[] = $errormessage;
371
            dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
372
            return -1;
373
        }
374
375
        if (!empty($sortfield)) {
376
            $sql .= $this->db->order($sortfield, $sortorder);
377
        }
378
        if (!empty($limit)) {
379
            $sql .= $this->db->plimit($limit, $offset);
380
        }
381
382
        $resql = $this->db->query($sql);
383
        if ($resql) {
384
            $num = $this->db->num_rows($resql);
385
            $i = 0;
386
            while ($i < ($limit ? min($limit, $num) : $num)) {
387
                $obj = $this->db->fetch_object($resql);
388
389
                $record = new self($this->db);
390
                $record->setVarsFromFetchObj($obj);
391
392
                $records[$record->id] = $record;
393
394
                $i++;
395
            }
396
            $this->db->free($resql);
397
398
            return $records;
399
        } else {
400
            $this->errors[] = 'Error ' . $this->db->lasterror();
401
            dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
402
403
            return -1;
404
        }
405
    }
406
407
    /**
408
     * Update object into database
409
     *
410
     * @param  User $user      User that modifies
411
     * @param  int  $notrigger 0=launch triggers after, 1=disable triggers
412
     * @return int             Return integer <0 if KO, >0 if OK
413
     */
414
    public function update(User $user, $notrigger = 0)
415
    {
416
        $resultupdate = $this->updateCommon($user, $notrigger);
417
418
        if ($resultupdate > 0 && !empty($this->asset_depreciation_options)) {
419
            $this->asset_depreciation_options->setDeprecationOptionsFromPost(1);
420
            $this->asset_depreciation_options->updateDeprecationOptions($user, 0, $resultupdate);
421
        }
422
423
        if ($resultupdate > 0 && !empty($this->asset_accountancy_codes)) {
424
            $this->asset_accountancy_codes->setAccountancyCodesFromPost();
425
            $this->asset_accountancy_codes->updateAccountancyCodes($user, 0, $resultupdate);
426
        }
427
428
        return $resultupdate;
429
    }
430
431
    /**
432
     * Delete object in database
433
     *
434
     * @param User  $user       User that deletes
435
     * @param int   $notrigger  0=launch triggers after, 1=disable triggers
436
     * @return int              Return integer <0 if KO, >0 if OK
437
     */
438
    public function delete(User $user, $notrigger = 0)
439
    {
440
        return $this->deleteCommon($user, $notrigger);
441
        //return $this->deleteCommon($user, $notrigger, 1);
442
    }
443
444
445
    /**
446
     *  Validate object
447
     *
448
     *  @param      User    $user           User making status change
449
     *  @param      int     $notrigger      1=Does not execute triggers, 0= execute triggers
450
     *  @return     int                     Return integer <=0 if OK, 0=Nothing done, >0 if KO
451
     */
452
    public function validate($user, $notrigger = 0)
453
    {
454
        global $conf, $langs;
455
456
        $error = 0;
457
458
        // Protection
459
        if ($this->status == self::STATUS_VALIDATED) {
460
            dol_syslog(get_class($this) . "::validate action abandoned: already validated", LOG_WARNING);
461
            return 0;
462
        }
463
464
        $now = dol_now();
465
466
        $this->db->begin();
467
468
        // Validate
469
        $sql = "UPDATE " . MAIN_DB_PREFIX . $this->table_element;
470
        $sql .= " SET status = " . self::STATUS_VALIDATED;
471
        if (!empty($this->fields['date_validation'])) {
472
            $sql .= ", date_validation = '" . $this->db->idate($now) . "'";
473
        }
474
        if (!empty($this->fields['fk_user_valid'])) {
475
            $sql .= ", fk_user_valid = " . ((int) $user->id);
476
        }
477
        $sql .= " WHERE rowid = " . ((int) $this->id);
478
479
        dol_syslog(get_class($this) . "::validate()", LOG_DEBUG);
480
        $resql = $this->db->query($sql);
481
        if (!$resql) {
482
            dol_print_error($this->db);
483
            $this->error = $this->db->lasterror();
484
            $error++;
485
        }
486
487
        if (!$error && !$notrigger) {
488
            // Call trigger
489
            $result = $this->call_trigger('ASSETMODEL_VALIDATE', $user);
490
            if ($result < 0) {
491
                $error++;
492
            }
493
            // End call triggers
494
        }
495
496
        // Set new ref and current status
497
        if (!$error) {
498
            $this->status = self::STATUS_VALIDATED;
499
        }
500
501
        if (!$error) {
502
            $this->db->commit();
503
            return 1;
504
        } else {
505
            $this->db->rollback();
506
            return -1;
507
        }
508
    }
509
510
511
    /**
512
     *  Set draft status
513
     *
514
     *  @param  User    $user           Object user that modify
515
     *  @param  int     $notrigger      1=Does not execute triggers, 0=Execute triggers
516
     *  @return int                     Return integer <0 if KO, >0 if OK
517
     */
518
    public function setDraft($user, $notrigger = 0)
519
    {
520
        // Protection
521
        if ($this->status <= self::STATUS_DRAFT) {
522
            return 0;
523
        }
524
525
        return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'ASSETMODEL_UNVALIDATE');
526
    }
527
528
    /**
529
     *  Set cancel status
530
     *
531
     *  @param  User    $user           Object user that modify
532
     *  @param  int     $notrigger      1=Does not execute triggers, 0=Execute triggers
533
     *  @return int                     Return integer <0 if KO, 0=Nothing done, >0 if OK
534
     */
535
    public function cancel($user, $notrigger = 0)
536
    {
537
        // Protection
538
        if ($this->status != self::STATUS_VALIDATED) {
539
            return 0;
540
        }
541
542
        return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'ASSETMODEL_CANCEL');
543
    }
544
545
    /**
546
     *  Set back to validated status
547
     *
548
     *  @param  User    $user           Object user that modify
549
     *  @param  int     $notrigger      1=Does not execute triggers, 0=Execute triggers
550
     *  @return int                     Return integer <0 if KO, 0=Nothing done, >0 if OK
551
     */
552
    public function reopen($user, $notrigger = 0)
553
    {
554
        // Protection
555
        if ($this->status != self::STATUS_CANCELED) {
556
            return 0;
557
        }
558
559
        return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'ASSETMODEL_REOPEN');
560
    }
561
562
    /**
563
     *  Return a link to the object card (with optionally the picto)
564
     *
565
     *  @param  int     $withpicto                  Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
566
     *  @param  string  $option                     On what the link point to ('nolink', ...)
567
     *  @param  int     $notooltip                  1=Disable tooltip
568
     *  @param  string  $morecss                    Add more css on link
569
     *  @param  int     $save_lastsearch_value      -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
570
     *  @return string                              String with URL
571
     */
572
    public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
573
    {
574
        global $conf, $langs, $hookmanager;
575
576
        if (!empty($conf->dol_no_mouse_hover)) {
577
            $notooltip = 1; // Force disable tooltips
578
        }
579
580
        $result = '';
581
582
        $label = img_picto('', $this->picto) . ' <u>' . $langs->trans("AssetModel") . '</u>';
583
        if (isset($this->status)) {
584
            $label .= ' ' . $this->getLibStatut(5);
585
        }
586
        $label .= '<br>';
587
        $label .= '<b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;
588
589
        $url = dol_buildpath('/asset/model/card.php', 1) . '?id=' . $this->id;
590
591
        if ($option != 'nolink') {
592
            // Add param to save lastsearch_values or not
593
            $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
594
            if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
595
                $add_save_lastsearch_values = 1;
596
            }
597
            if ($add_save_lastsearch_values) {
598
                $url .= '&save_lastsearch_values=1';
599
            }
600
        }
601
602
        $linkclose = '';
603
        if (empty($notooltip)) {
604
            if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
605
                $label = $langs->trans("ShowAssetModel");
606
                $linkclose .= ' alt="' . dol_escape_htmltag($label, 1) . '"';
607
            }
608
            $linkclose .= ' title="' . dol_escape_htmltag($label, 1) . '"';
609
            $linkclose .= ' class="classfortooltip' . ($morecss ? ' ' . $morecss : '') . '"';
610
        } else {
611
            $linkclose = ($morecss ? ' class="' . $morecss . '"' : '');
612
        }
613
614
        if ($option == 'nolink') {
615
            $linkstart = '<span';
616
        } else {
617
            $linkstart = '<a href="' . $url . '"';
618
        }
619
        $linkstart .= $linkclose . '>';
620
        if ($option == 'nolink') {
621
            $linkend = '</span>';
622
        } else {
623
            $linkend = '</a>';
624
        }
625
626
        $result .= $linkstart;
627
628
        if (empty($this->showphoto_on_popup)) {
629
            if ($withpicto) {
630
                $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);
631
            }
632
        } else {
633
            if ($withpicto) {
634
                require_once constant('DOL_DOCUMENT_ROOT') . '/core/lib/files.lib.php';
635
636
                list($class, $module) = explode('@', $this->picto);
637
                $upload_dir = $conf->$module->multidir_output[$conf->entity] . "/$class/" . dol_sanitizeFileName($this->ref);
638
                $filearray = dol_dir_list($upload_dir, "files");
639
                $filename = $filearray[0]['name'];
640
                if (!empty($filename)) {
641
                    $pospoint = strpos($filearray[0]['name'], '.');
642
643
                    $pathtophoto = $class . '/' . $this->ref . '/thumbs/' . substr($filename, 0, $pospoint) . '_mini' . substr($filename, $pospoint);
644
                    if (!getDolGlobalString(strtoupper($module . '_' . $class) . '_FORMATLISTPHOTOSASUSERS')) {
645
                        $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>';
646
                    } else {
647
                        $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>';
648
                    }
649
650
                    $result .= '</div>';
651
                } else {
652
                    $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);
653
                }
654
            }
655
        }
656
657
        if ($withpicto != 2) {
658
            $result .= $this->ref;
659
        }
660
661
        $result .= $linkend;
662
        //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
663
664
        global $action, $hookmanager;
665
        $hookmanager->initHooks(array('assetmodeldao'));
666
        $parameters = array('id' => $this->id, 'getnomurl' => $result);
667
        $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
668
        if ($reshook > 0) {
669
            $result = $hookmanager->resPrint;
670
        } else {
671
            $result .= $hookmanager->resPrint;
672
        }
673
674
        return $result;
675
    }
676
677
    /**
678
     *  Return the label of the status
679
     *
680
     *  @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
681
     *  @return string                 Label of status
682
     */
683
    public function getLabelStatus($mode = 0)
684
    {
685
        return $this->LibStatut($this->status, $mode);
686
    }
687
688
    /**
689
     *  Return the label of the status
690
     *
691
     *  @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
692
     *  @return string                 Label of status
693
     */
694
    public function getLibStatut($mode = 0)
695
    {
696
        return $this->LibStatut($this->status, $mode);
697
    }
698
699
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
700
    /**
701
     *  Return the status
702
     *
703
     *  @param  int     $status        Id status
704
     *  @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
705
     *  @return string                 Label of status
706
     */
707
    public function LibStatut($status, $mode = 0)
708
    {
709
		// phpcs:enable
710
        if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
711
            global $langs;
712
            //$langs->load("assets");
713
            $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
714
            $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
715
            $this->labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
716
            $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
717
            $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
718
            $this->labelStatusShort[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
719
        }
720
721
        $statusType = 'status' . $status;
722
        //if ($status == self::STATUS_VALIDATED) $statusType = 'status1';
723
        if ($status == self::STATUS_CANCELED) {
724
            $statusType = 'status6';
725
        }
726
727
        return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
728
    }
729
730
    /**
731
     *  Load the info information in the object
732
     *
733
     *  @param  int     $id       Id of object
734
     *  @return void
735
     */
736
    public function info($id)
737
    {
738
        $sql = "SELECT rowid, date_creation as datec, tms as datem,";
739
        $sql .= " fk_user_creat, fk_user_modif";
740
        $sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element . " as t";
741
        $sql .= " WHERE t.rowid = " . ((int) $id);
742
743
        $result = $this->db->query($sql);
744
        if ($result) {
745
            if ($this->db->num_rows($result)) {
746
                $obj = $this->db->fetch_object($result);
747
748
                $this->id = $obj->rowid;
749
750
                $this->user_creation_id = $obj->fk_user_creat;
751
                $this->user_modification_id = $obj->fk_user_modif;
752
                $this->date_creation     = $this->db->jdate($obj->datec);
753
                $this->date_modification = $this->db->jdate($obj->datem);
754
            }
755
756
            $this->db->free($result);
757
        } else {
758
            dol_print_error($this->db);
759
        }
760
    }
761
762
    /**
763
     * Initialise object with example values
764
     * Id must be 0 if object instance is a specimen
765
     *
766
     * @return int
767
     */
768
    public function initAsSpecimen()
769
    {
770
        // Set here init that are not commonf fields
771
        // $this->property1 = ...
772
        // $this->property2 = ...
773
774
        return $this->initAsSpecimenCommon();
775
    }
776
777
    /**
778
     *  Create an array of lines
779
     *
780
     *  @return array|int       array of lines if OK, <0 if KO
781
     */
782
    public function getLinesArray()
783
    {
784
        $this->lines = array();
785
786
        return $this->lines;
787
    }
788
789
    /**
790
     * Action executed by scheduler
791
     * CAN BE A CRON TASK. In such a case, parameters come from the schedule job setup field 'Parameters'
792
     * Use public function doScheduledJob($param1, $param2, ...) to get parameters
793
     *
794
     * @return  int         0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
795
     */
796
    public function doScheduledJob()
797
    {
798
        //global $conf, $langs;
799
800
        //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
801
802
        $error = 0;
803
        $this->output = '';
804
        $this->error = '';
805
806
        dol_syslog(__METHOD__, LOG_DEBUG);
807
808
        $now = dol_now();
809
810
        $this->db->begin();
811
812
        // ...
813
814
        $this->db->commit();
815
816
        return $error;
817
    }
818
}
819