Passed
Pull Request — dev (#8)
by Rafael
58:47
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
//use Dolibarr\Code\Societe\Classes\Societe;
36
//
37
/**
38
 * Class for AssetModel
39
 */
40
class AssetModel extends CommonObject
41
{
42
    /**
43
     * @var string ID of module.
44
     */
45
    public $module = 'asset';
46
47
    /**
48
     * @var string ID to identify managed object.
49
     */
50
    public $element = 'assetmodel';
51
52
    /**
53
     * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management.
54
     */
55
    public $table_element = 'asset_model';
56
57
    /**
58
     * @var string String with name of icon for assetmodel. Must be the part after the 'object_' into object_assetmodel.png
59
     */
60
    public $picto = 'asset';
61
62
63
    const STATUS_DRAFT = 0;
64
    const STATUS_VALIDATED = 1;
65
    const STATUS_CANCELED = 9;
66
67
68
    /**
69
     *  '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')
70
     *         Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
71
     *  'label' the translation key.
72
     *  'picto' is code of a picto to show before value in forms
73
     *  'enabled' is a condition when the field must be managed (Example: 1 or 'getDolGlobalString("MY_SETUP_PARAM")'
74
     *  'position' is the sort order of field.
75
     *  'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
76
     *  '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)
77
     *  'noteditable' says if field is not editable (1 or 0)
78
     *  '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.
79
     *  'index' if we want an index in database.
80
     *  'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommended to name the field fk_...).
81
     *  'searchall' is 1 if we want to search in this field when making a search from the quick search button.
82
     *  '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)
83
     *  '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'
84
     *  'help' is a 'TranslationString' to use to show a tooltip on field. You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
85
     *  'showoncombobox' if value of the field must be visible into the label of the combobox that list record
86
     *  '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.
87
     *  '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'
88
     *  'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1.
89
     *  'comment' is not used. You can store here any text of your choice. It is not used by application.
90
     *  'validate' is 1 if need to validate with $this->validateField()
91
     *  'copytoclipboard' is 1 or 2 to allow to add a picto to copy value into clipboard (1=picto after label, 2=picto after value)
92
     *
93
     *  Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
94
     */
95
96
    /**
97
     * @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...
98
     */
99
    public $fields = array(
100
        'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'position' => 1, 'notnull' => 1, 'visible' => 0, 'noteditable' => 1, 'index' => 1, 'css' => 'left', 'comment' => "Id"),
101
        'ref' => array('type' => 'varchar(128)', 'label' => 'Ref', 'enabled' => 1, 'position' => 20, 'notnull' => 1, 'visible' => 1, 'index' => 1, 'searchall' => 1, 'showoncombobox' => 1, 'validate' => 1),
102
        '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,),
103
        '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,),
104
        'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'position' => 300, 'notnull' => 0, 'visible' => 0, 'validate' => 1,),
105
        'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'position' => 301, 'notnull' => 0, 'visible' => 0, 'validate' => 1,),
106
        'date_creation' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'position' => 500, 'notnull' => 1, 'visible' => -2,),
107
        'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'position' => 501, 'notnull' => 0, 'visible' => -2,),
108
        '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',),
109
        'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => 1, 'position' => 511, 'notnull' => -1, 'visible' => -2,),
110
        'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'position' => 1000, 'notnull' => -1, 'visible' => -2,),
111
        '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,),
112
    );
113
    public $rowid;
114
    public $ref;
115
    public $label;
116
    public $asset_type;
117
    public $note_public;
118
    public $note_private;
119
    public $date_creation;
120
    public $fk_user_creat;
121
    public $fk_user_modif;
122
    public $last_main_doc;
123
    public $import_key;
124
    public $model_pdf;
125
    public $status;
126
    public $asset_depreciation_options;
127
    public $asset_accountancy_codes;
128
129
    // /**
130
    //  * @var string    Field with ID of parent key if this object has a parent
131
    //  */
132
    // public $fk_element = 'fk_assetmodel';
133
    // /**
134
    //  * @var array    List of child tables. To test if we can delete object.
135
    //  */
136
    // protected $childtables = array();
137
    // /**
138
    //  * @var array    List of child tables. To know object to delete on cascade.
139
    //  *               If name matches '@ClassNAme:FilePathClass;ParentFkFieldName' it will
140
    //  *               call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object
141
    //  */
142
    // protected $childtablesoncascade = array('asset_assetmodeldet');
143
144
145
    /**
146
     * Constructor
147
     *
148
     * @param DoliDB $db Database handler
149
     */
150
    public function __construct(DoliDB $db)
151
    {
152
        global $conf, $langs;
153
154
        $this->db = $db;
155
156
        $this->ismultientitymanaged = 1;
157
158
        $this->isextrafieldmanaged = 1;
159
160
        if (!getDolGlobalString('MAIN_SHOW_TECHNICAL_ID') && isset($this->fields['rowid'])) {
161
            $this->fields['rowid']['visible'] = 0;
162
        }
163
        if (!isModEnabled('multicompany') && isset($this->fields['entity'])) {
164
            $this->fields['entity']['enabled'] = 0;
165
        }
166
167
        // Unset fields that are disabled
168
        foreach ($this->fields as $key => $val) {
169
            if (isset($val['enabled']) && empty($val['enabled'])) {
170
                unset($this->fields[$key]);
171
            }
172
        }
173
174
        // Translate some data of arrayofkeyval
175
        if (is_object($langs)) {
176
            foreach ($this->fields as $key => $val) {
177
                if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
178
                    foreach ($val['arrayofkeyval'] as $key2 => $val2) {
179
                        $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
180
                    }
181
                }
182
            }
183
        }
184
    }
185
186
    /**
187
     * Create object into database
188
     *
189
     * @param  User $user      User that creates
190
     * @param  int  $notrigger false=launch triggers after, true=disable triggers
191
     * @return int             Return integer <0 if KO, Id of created object if OK
192
     */
193
    public function create(User $user, $notrigger = 0)
194
    {
195
        $resultcreate = $this->createCommon($user, $notrigger);
196
197
        if ($resultcreate > 0 && !empty($this->asset_depreciation_options)) {
198
            $this->asset_depreciation_options->setDeprecationOptionsFromPost(1);
199
            $this->asset_depreciation_options->updateDeprecationOptions($user, 0, $resultcreate);
200
        }
201
202
        if ($resultcreate > 0 && !empty($this->asset_accountancy_codes)) {
203
            $this->asset_accountancy_codes->setAccountancyCodesFromPost();
204
            $this->asset_accountancy_codes->updateAccountancyCodes($user, 0, $resultcreate);
205
        }
206
207
        return $resultcreate;
208
    }
209
210
    /**
211
     * Clone an object into another one
212
     *
213
     * @param   User    $user       User that creates
214
     * @param   int     $fromid     Id of object to clone
215
     * @return  mixed               New object created, <0 if KO
216
     */
217
    public function createFromClone(User $user, $fromid)
218
    {
219
        global $langs, $extrafields;
220
        $error = 0;
221
222
        dol_syslog(__METHOD__, LOG_DEBUG);
223
224
        $object = new self($this->db);
225
226
        $this->db->begin();
227
228
        // Load source object
229
        $result = $object->fetchCommon($fromid);
230
        if ($result > 0 && !empty($object->table_element_line)) {
231
            $object->fetchLines();
232
        }
233
234
        // get lines so they will be clone
235
        //foreach($this->lines as $line)
236
        //  $line->fetch_optionals();
237
238
        // Reset some properties
239
        unset($object->id);
240
        unset($object->fk_user_creat);
241
        unset($object->import_key);
242
243
        // Clear fields
244
        if (property_exists($object, 'ref')) {
245
            $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_" . $object->ref : $this->fields['ref']['default'];
246
        }
247
        if (property_exists($object, 'label')) {
248
            $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf") . " " . $object->label : $this->fields['label']['default'];
249
        }
250
        if (property_exists($object, 'status')) {
251
            $object->status = self::STATUS_DRAFT;
252
        }
253
        if (property_exists($object, 'date_creation')) {
254
            $object->date_creation = dol_now();
255
        }
256
        if (property_exists($object, 'date_modification')) {
257
            $object->date_modification = null;
258
        }
259
        // ...
260
        // Clear extrafields that are unique
261
        if (is_array($object->array_options) && count($object->array_options) > 0) {
262
            $extrafields->fetch_name_optionals_label($this->table_element);
263
            foreach ($object->array_options as $key => $option) {
264
                $shortkey = preg_replace('/options_/', '', $key);
265
                if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) {
266
                    //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
267
                    unset($object->array_options[$key]);
268
                }
269
            }
270
        }
271
272
        // Create clone
273
        $object->context['createfromclone'] = 'createfromclone';
274
        $result = $object->createCommon($user);
275
        if ($result < 0) {
276
            $error++;
277
            $this->error = $object->error;
278
            $this->errors = $object->errors;
279
        }
280
281
        if (!$error) {
282
            // copy internal contacts
283
            if ($this->copy_linked_contact($object, 'internal') < 0) {
284
                $error++;
285
            }
286
        }
287
288
        if (!$error) {
289
            // copy external contacts if same company
290
            if (property_exists($this, 'fk_soc') && $this->fk_soc == $object->socid) {
291
                if ($this->copy_linked_contact($object, 'external') < 0) {
292
                    $error++;
293
                }
294
            }
295
        }
296
297
        unset($object->context['createfromclone']);
298
299
        // End
300
        if (!$error) {
301
            $this->db->commit();
302
            return $object;
303
        } else {
304
            $this->db->rollback();
305
            return -1;
306
        }
307
    }
308
309
    /**
310
     * Load object in memory from the database
311
     *
312
     * @param int    $id   Id object
313
     * @param string $ref  Ref
314
     * @return int         Return integer <0 if KO, 0 if not found, >0 if OK
315
     */
316
    public function fetch($id, $ref = null)
317
    {
318
        $result = $this->fetchCommon($id, $ref);
319
        if ($result > 0 && !empty($this->table_element_line)) {
320
            $this->fetchLines();
321
        }
322
        return $result;
323
    }
324
325
    /**
326
     * Load object lines in memory from the database
327
     *
328
     * @return int         Return integer <0 if KO, 0 if not found, >0 if OK
329
     */
330
    public function fetchLines()
331
    {
332
        $this->lines = array();
333
334
        return 1;
335
    }
336
337
338
    /**
339
     * Load list of objects in memory from the database.
340
     *
341
     * @param  string       $sortorder      Sort Order
342
     * @param  string       $sortfield       Sort field
343
     * @param  int          $limit          limit
344
     * @param  int          $offset         Offset
345
     * @param  string       $filter         Filter as an Universal Search string.
346
     *                                      Example: '((client:=:1) OR ((client:>=:2) AND (client:<=:3))) AND (client:!=:8) AND (nom:like:'a%')'
347
     * @param  string       $filtermode     No more used
348
     * @return array|int                    int <0 if KO, array of pages if OK
349
     */
350
    public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, $filter = '', $filtermode = 'AND')
351
    {
352
        dol_syslog(__METHOD__, LOG_DEBUG);
353
354
        $records = array();
355
356
        $sql = "SELECT ";
357
        $sql .= $this->getFieldList('t');
358
        $sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element . " as t";
359
        if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
360
            $sql .= " WHERE t.entity IN (" . getEntity($this->element) . ")";
361
        } else {
362
            $sql .= " WHERE 1 = 1";
363
        }
364
365
        // Manage filter
366
        $errormessage = '';
367
        $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
368
        if ($errormessage) {
369
            $this->errors[] = $errormessage;
370
            dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
371
            return -1;
372
        }
373
374
        if (!empty($sortfield)) {
375
            $sql .= $this->db->order($sortfield, $sortorder);
376
        }
377
        if (!empty($limit)) {
378
            $sql .= $this->db->plimit($limit, $offset);
379
        }
380
381
        $resql = $this->db->query($sql);
382
        if ($resql) {
383
            $num = $this->db->num_rows($resql);
384
            $i = 0;
385
            while ($i < ($limit ? min($limit, $num) : $num)) {
386
                $obj = $this->db->fetch_object($resql);
387
388
                $record = new self($this->db);
389
                $record->setVarsFromFetchObj($obj);
390
391
                $records[$record->id] = $record;
392
393
                $i++;
394
            }
395
            $this->db->free($resql);
396
397
            return $records;
398
        } else {
399
            $this->errors[] = 'Error ' . $this->db->lasterror();
400
            dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
401
402
            return -1;
403
        }
404
    }
405
406
    /**
407
     * Update object into database
408
     *
409
     * @param  User $user      User that modifies
410
     * @param  int  $notrigger 0=launch triggers after, 1=disable triggers
411
     * @return int             Return integer <0 if KO, >0 if OK
412
     */
413
    public function update(User $user, $notrigger = 0)
414
    {
415
        $resultupdate = $this->updateCommon($user, $notrigger);
416
417
        if ($resultupdate > 0 && !empty($this->asset_depreciation_options)) {
418
            $this->asset_depreciation_options->setDeprecationOptionsFromPost(1);
419
            $this->asset_depreciation_options->updateDeprecationOptions($user, 0, $resultupdate);
420
        }
421
422
        if ($resultupdate > 0 && !empty($this->asset_accountancy_codes)) {
423
            $this->asset_accountancy_codes->setAccountancyCodesFromPost();
424
            $this->asset_accountancy_codes->updateAccountancyCodes($user, 0, $resultupdate);
425
        }
426
427
        return $resultupdate;
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
    /**
445
     *  Validate object
446
     *
447
     *  @param      User    $user           User making status change
448
     *  @param      int     $notrigger      1=Does not execute triggers, 0= execute triggers
449
     *  @return     int                     Return integer <=0 if OK, 0=Nothing done, >0 if KO
450
     */
451
    public function validate($user, $notrigger = 0)
452
    {
453
        global $conf, $langs;
454
455
        $error = 0;
456
457
        // Protection
458
        if ($this->status == self::STATUS_VALIDATED) {
459
            dol_syslog(get_class($this) . "::validate action abandoned: already validated", LOG_WARNING);
460
            return 0;
461
        }
462
463
        $now = dol_now();
464
465
        $this->db->begin();
466
467
        // Validate
468
        $sql = "UPDATE " . MAIN_DB_PREFIX . $this->table_element;
469
        $sql .= " SET status = " . self::STATUS_VALIDATED;
470
        if (!empty($this->fields['date_validation'])) {
471
            $sql .= ", date_validation = '" . $this->db->idate($now) . "'";
472
        }
473
        if (!empty($this->fields['fk_user_valid'])) {
474
            $sql .= ", fk_user_valid = " . ((int) $user->id);
475
        }
476
        $sql .= " WHERE rowid = " . ((int) $this->id);
477
478
        dol_syslog(get_class($this) . "::validate()", LOG_DEBUG);
479
        $resql = $this->db->query($sql);
480
        if (!$resql) {
481
            dol_print_error($this->db);
482
            $this->error = $this->db->lasterror();
483
            $error++;
484
        }
485
486
        if (!$error && !$notrigger) {
487
            // Call trigger
488
            $result = $this->call_trigger('ASSETMODEL_VALIDATE', $user);
489
            if ($result < 0) {
490
                $error++;
491
            }
492
            // End call triggers
493
        }
494
495
        // Set new ref and current status
496
        if (!$error) {
497
            $this->status = self::STATUS_VALIDATED;
498
        }
499
500
        if (!$error) {
501
            $this->db->commit();
502
            return 1;
503
        } else {
504
            $this->db->rollback();
505
            return -1;
506
        }
507
    }
508
509
510
    /**
511
     *  Set draft status
512
     *
513
     *  @param  User    $user           Object user that modify
514
     *  @param  int     $notrigger      1=Does not execute triggers, 0=Execute triggers
515
     *  @return int                     Return integer <0 if KO, >0 if OK
516
     */
517
    public function setDraft($user, $notrigger = 0)
518
    {
519
        // Protection
520
        if ($this->status <= self::STATUS_DRAFT) {
521
            return 0;
522
        }
523
524
        return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'ASSETMODEL_UNVALIDATE');
525
    }
526
527
    /**
528
     *  Set cancel status
529
     *
530
     *  @param  User    $user           Object user that modify
531
     *  @param  int     $notrigger      1=Does not execute triggers, 0=Execute triggers
532
     *  @return int                     Return integer <0 if KO, 0=Nothing done, >0 if OK
533
     */
534
    public function cancel($user, $notrigger = 0)
535
    {
536
        // Protection
537
        if ($this->status != self::STATUS_VALIDATED) {
538
            return 0;
539
        }
540
541
        return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'ASSETMODEL_CANCEL');
542
    }
543
544
    /**
545
     *  Set back to validated status
546
     *
547
     *  @param  User    $user           Object user that modify
548
     *  @param  int     $notrigger      1=Does not execute triggers, 0=Execute triggers
549
     *  @return int                     Return integer <0 if KO, 0=Nothing done, >0 if OK
550
     */
551
    public function reopen($user, $notrigger = 0)
552
    {
553
        // Protection
554
        if ($this->status != self::STATUS_CANCELED) {
555
            return 0;
556
        }
557
558
        return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'ASSETMODEL_REOPEN');
559
    }
560
561
    /**
562
     *  Return a link to the object card (with optionally the picto)
563
     *
564
     *  @param  int     $withpicto                  Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
565
     *  @param  string  $option                     On what the link point to ('nolink', ...)
566
     *  @param  int     $notooltip                  1=Disable tooltip
567
     *  @param  string  $morecss                    Add more css on link
568
     *  @param  int     $save_lastsearch_value      -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
569
     *  @return string                              String with URL
570
     */
571
    public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
572
    {
573
        global $conf, $langs, $hookmanager;
574
575
        if (!empty($conf->dol_no_mouse_hover)) {
576
            $notooltip = 1; // Force disable tooltips
577
        }
578
579
        $result = '';
580
581
        $label = img_picto('', $this->picto) . ' <u>' . $langs->trans("AssetModel") . '</u>';
582
        if (isset($this->status)) {
583
            $label .= ' ' . $this->getLibStatut(5);
584
        }
585
        $label .= '<br>';
586
        $label .= '<b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;
587
588
        $url = dol_buildpath('/asset/model/card.php', 1) . '?id=' . $this->id;
589
590
        if ($option != 'nolink') {
591
            // Add param to save lastsearch_values or not
592
            $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
593
            if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
594
                $add_save_lastsearch_values = 1;
595
            }
596
            if ($add_save_lastsearch_values) {
597
                $url .= '&save_lastsearch_values=1';
598
            }
599
        }
600
601
        $linkclose = '';
602
        if (empty($notooltip)) {
603
            if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
604
                $label = $langs->trans("ShowAssetModel");
605
                $linkclose .= ' alt="' . dol_escape_htmltag($label, 1) . '"';
606
            }
607
            $linkclose .= ' title="' . dol_escape_htmltag($label, 1) . '"';
608
            $linkclose .= ' class="classfortooltip' . ($morecss ? ' ' . $morecss : '') . '"';
609
        } else {
610
            $linkclose = ($morecss ? ' class="' . $morecss . '"' : '');
611
        }
612
613
        if ($option == 'nolink') {
614
            $linkstart = '<span';
615
        } else {
616
            $linkstart = '<a href="' . $url . '"';
617
        }
618
        $linkstart .= $linkclose . '>';
619
        if ($option == 'nolink') {
620
            $linkend = '</span>';
621
        } else {
622
            $linkend = '</a>';
623
        }
624
625
        $result .= $linkstart;
626
627
        if (empty($this->showphoto_on_popup)) {
628
            if ($withpicto) {
629
                $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);
630
            }
631
        } else {
632
            if ($withpicto) {
633
                require_once constant('DOL_DOCUMENT_ROOT') . '/core/lib/files.lib.php';
634
635
                list($class, $module) = explode('@', $this->picto);
636
                $upload_dir = $conf->$module->multidir_output[$conf->entity] . "/$class/" . dol_sanitizeFileName($this->ref);
637
                $filearray = dol_dir_list($upload_dir, "files");
638
                $filename = $filearray[0]['name'];
639
                if (!empty($filename)) {
640
                    $pospoint = strpos($filearray[0]['name'], '.');
641
642
                    $pathtophoto = $class . '/' . $this->ref . '/thumbs/' . substr($filename, 0, $pospoint) . '_mini' . substr($filename, $pospoint);
643
                    if (!getDolGlobalString(strtoupper($module . '_' . $class) . '_FORMATLISTPHOTOSASUSERS')) {
644
                        $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>';
645
                    } else {
646
                        $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>';
647
                    }
648
649
                    $result .= '</div>';
650
                } else {
651
                    $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);
652
                }
653
            }
654
        }
655
656
        if ($withpicto != 2) {
657
            $result .= $this->ref;
658
        }
659
660
        $result .= $linkend;
661
        //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
662
663
        global $action, $hookmanager;
664
        $hookmanager->initHooks(array('assetmodeldao'));
665
        $parameters = array('id' => $this->id, 'getnomurl' => $result);
666
        $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
667
        if ($reshook > 0) {
668
            $result = $hookmanager->resPrint;
669
        } else {
670
            $result .= $hookmanager->resPrint;
671
        }
672
673
        return $result;
674
    }
675
676
    /**
677
     *  Return the label of the status
678
     *
679
     *  @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
680
     *  @return string                 Label of status
681
     */
682
    public function getLabelStatus($mode = 0)
683
    {
684
        return $this->LibStatut($this->status, $mode);
685
    }
686
687
    /**
688
     *  Return the label of the status
689
     *
690
     *  @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
691
     *  @return string                 Label of status
692
     */
693
    public function getLibStatut($mode = 0)
694
    {
695
        return $this->LibStatut($this->status, $mode);
696
    }
697
698
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
699
    /**
700
     *  Return the status
701
     *
702
     *  @param  int     $status        Id status
703
     *  @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
704
     *  @return string                 Label of status
705
     */
706
    public function LibStatut($status, $mode = 0)
707
    {
708
		// phpcs:enable
709
        if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
710
            global $langs;
711
            //$langs->load("assets");
712
            $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
713
            $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
714
            $this->labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
715
            $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
716
            $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
717
            $this->labelStatusShort[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
718
        }
719
720
        $statusType = 'status' . $status;
721
        //if ($status == self::STATUS_VALIDATED) $statusType = 'status1';
722
        if ($status == self::STATUS_CANCELED) {
723
            $statusType = 'status6';
724
        }
725
726
        return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
727
    }
728
729
    /**
730
     *  Load the info information in the object
731
     *
732
     *  @param  int     $id       Id of object
733
     *  @return void
734
     */
735
    public function info($id)
736
    {
737
        $sql = "SELECT rowid, date_creation as datec, tms as datem,";
738
        $sql .= " fk_user_creat, fk_user_modif";
739
        $sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element . " as t";
740
        $sql .= " WHERE t.rowid = " . ((int) $id);
741
742
        $result = $this->db->query($sql);
743
        if ($result) {
744
            if ($this->db->num_rows($result)) {
745
                $obj = $this->db->fetch_object($result);
746
747
                $this->id = $obj->rowid;
748
749
                $this->user_creation_id = $obj->fk_user_creat;
750
                $this->user_modification_id = $obj->fk_user_modif;
751
                $this->date_creation     = $this->db->jdate($obj->datec);
752
                $this->date_modification = $this->db->jdate($obj->datem);
753
            }
754
755
            $this->db->free($result);
756
        } else {
757
            dol_print_error($this->db);
758
        }
759
    }
760
761
    /**
762
     * Initialise object with example values
763
     * Id must be 0 if object instance is a specimen
764
     *
765
     * @return int
766
     */
767
    public function initAsSpecimen()
768
    {
769
        // Set here init that are not commonf fields
770
        // $this->property1 = ...
771
        // $this->property2 = ...
772
773
        return $this->initAsSpecimenCommon();
774
    }
775
776
    /**
777
     *  Create an array of lines
778
     *
779
     *  @return array|int       array of lines if OK, <0 if KO
780
     */
781
    public function getLinesArray()
782
    {
783
        $this->lines = array();
784
785
        return $this->lines;
786
    }
787
788
    /**
789
     * Action executed by scheduler
790
     * CAN BE A CRON TASK. In such a case, parameters come from the schedule job setup field 'Parameters'
791
     * Use public function doScheduledJob($param1, $param2, ...) to get parameters
792
     *
793
     * @return  int         0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
794
     */
795
    public function doScheduledJob()
796
    {
797
        //global $conf, $langs;
798
799
        //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
800
801
        $error = 0;
802
        $this->output = '';
803
        $this->error = '';
804
805
        dol_syslog(__METHOD__, LOG_DEBUG);
806
807
        $now = dol_now();
808
809
        $this->db->begin();
810
811
        // ...
812
813
        $this->db->commit();
814
815
        return $error;
816
    }
817
}
818