Passed
Push — CHECK_API ( 78ffdd...fa4f39 )
by Rafael
41:29
created

KnowledgeRecord::getTooltipContentArray()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 5
eloc 15
nc 8
nop 1
dl 0
loc 24
rs 9.4555
c 1
b 0
f 1
1
<?php
2
3
/* Copyright (C) 2017       Laurent Destailleur         <[email protected]>
4
 * Copyright (C) 2024       Frédéric France             <[email protected]>
5
 * Copyright (C) 2024		MDW							<[email protected]>
6
 * Copyright (C) 2024       Rafael San José             <[email protected]>
7
 *
8
 * This program is free software; you can redistribute it and/or modify
9
 * it under the terms of the GNU General Public License as published by
10
 * the Free Software Foundation; either version 3 of the License, or
11
 * (at your option) any later version.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU General Public License
19
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20
 */
21
22
namespace Dolibarr\Code\KnowledgeManagement\Classes;
23
24
use Dolibarr\Code\Categories\Classes\Categorie;
25
use Dolibarr\Code\Core\Classes\Form;
26
use Dolibarr\Code\Core\Classes\Translate;
27
use Dolibarr\Code\User\Classes\User;
28
use Dolibarr\Core\Base\CommonObject;
29
use DoliDB;
30
31
/**
32
 * \file        htdocs/knowledgemanagement/class/knowledgerecord.class.php
33
 * \ingroup     knowledgemanagement
34
 * \brief       This file is a CRUD class file for KnowledgeRecord (Create/Read/Update/Delete)
35
 */
36
37
// Put here all includes required by your class file
38
//use Dolibarr\Code\Societe\Classes\Societe;
39
//
40
/**
41
 * Class for KnowledgeRecord
42
 */
43
class KnowledgeRecord extends CommonObject
44
{
45
    /**
46
     * @var string ID of module.
47
     */
48
    public $module = 'knowledgemanagement';
49
50
    /**
51
     * @var string ID to identify managed object.
52
     */
53
    public $element = 'knowledgerecord';
54
55
    /**
56
     * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management.
57
     */
58
    public $table_element = 'knowledgemanagement_knowledgerecord';
59
60
    /**
61
     * @var string String with name of icon for knowledgerecord. Must be the part after the 'object_' into object_knowledgerecord.png
62
     */
63
    public $picto = 'knowledgemanagement';
64
65
66
    const STATUS_DRAFT = 0;
67
    const STATUS_VALIDATED = 1;
68
    const STATUS_CANCELED = 9;
69
70
71
    /**
72
     *  'type' field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:SortField]]]', 'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter]]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'text:none', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password')
73
     *         Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
74
     *  'label' the translation key.
75
     *  'picto' is code of a picto to show before value in forms
76
     *  'enabled' is a condition when the field must be managed (Example: 1 or 'getDolGlobalString("MY_SETUP_PARAM")'
77
     *  'position' is the sort order of field.
78
     *  'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
79
     *  '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)
80
     *  'noteditable' says if field is not editable (1 or 0)
81
     *  '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.
82
     *  'index' if we want an index in database.
83
     *  'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommended to name the field fk_...).
84
     *  'searchall' is 1 if we want to search in this field when making a search from the quick search button.
85
     *  '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).
86
     *  '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'
87
     *  'help' is a 'TranslationString' to use to show a tooltip on field. You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
88
     *  'showoncombobox' if value of the field must be visible into the label of the combobox that list record
89
     *  '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.
90
     *  'arraykeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel")
91
     *  'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1.
92
     *  'comment' is not used. You can store here any text of your choice. It is not used by application.
93
     *  'copytoclipboard' is 1 or 2 to allow to add a picto to copy value into clipboard (1=picto after label, 2=picto after value)
94
     *
95
     *  Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
96
     */
97
98
    // BEGIN MODULEBUILDER PROPERTIES
99
    /**
100
     * @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...
101
     */
102
    public $fields = array(
103
        'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'position' => 1, 'notnull' => 1, 'visible' => 0, 'noteditable' => 1, 'index' => 1, 'css' => 'left', 'comment' => "Id"),
104
        'ref' => array('type' => 'varchar(128)', 'label' => 'Ref', 'enabled' => 1, 'position' => 10, 'notnull' => 1, 'default' => '(PROV)', 'visible' => 5, 'index' => 1, 'searchall' => 1, 'comment' => "Reference of object", "csslist" => "nowraponall", "showoncombobox" => 1),
105
        'entity' => array('type' => 'integer', 'label' => 'Entity', 'default' => '1', 'enabled' => 1, 'visible' => 0, 'notnull' => 1, 'position' => 20, 'index' => 1),
106
        'question' => array('type' => 'text', 'label' => 'Question', 'enabled' => 1, 'position' => 30, 'notnull' => 1, 'visible' => 1, 'searchall' => 1, 'csslist' => 'tdoverflowmax300 small', 'copytoclipboard' => 1, 'tdcss' => 'titlefieldcreate nowraponall'),
107
        'lang' => array('type' => 'varchar(6)', 'label' => 'Language', 'enabled' => 1, 'position' => 40, 'notnull' => 0, 'visible' => 1, 'tdcss' => 'titlefieldcreate nowraponall', "csslist" => "minwidth100 maxwidth200"),
108
        'date_creation' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'position' => 500, 'notnull' => 1, 'visible' => -2, 'csslist' => 'nowraponall'),
109
        'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'position' => 501, 'notnull' => 0, 'visible' => 2,),
110
        'last_main_doc' => array('type' => 'varchar(255)', 'label' => 'LastMainDoc', 'enabled' => 1, 'position' => 600, 'notnull' => 0, 'visible' => 0,),
111
        'fk_user_creat' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserCreation', 'enabled' => 1, 'position' => 510, 'notnull' => 1, 'visible' => -2, 'foreignkey' => 'user.rowid',),
112
        'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => 1, 'position' => 511, 'notnull' => -1, 'visible' => -2,),
113
        'fk_user_valid' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserValidation', 'enabled' => 1, 'position' => 512, 'notnull' => 0, 'visible' => -2,),
114
        'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'position' => 1000, 'notnull' => -1, 'visible' => -2,),
115
        'model_pdf' => array('type' => 'varchar(255)', 'label' => 'Model pdf', 'enabled' => 1, 'position' => 1010, 'notnull' => -1, 'visible' => 0,),
116
        //'url' => array('type'=>'varchar(255)', 'label'=>'URL', 'enabled'=>'1', 'position'=>55, 'notnull'=>0, 'visible'=>-1, 'csslist'=>'tdoverflow200', 'help'=>'UrlForInfoPage'),
117
        'fk_c_ticket_category' => array('type' => 'integer:CTicketCategory:ticket/class/cticketcategory.class.php:0:(t.active:=:1):pos', 'label' => 'SuggestedForTicketsInGroup', 'enabled' => 'isModEnabled("ticket")', 'position' => 520, 'notnull' => 0, 'visible' => -1, 'help' => 'YouCanLinkArticleToATicketCategory', 'csslist' => 'minwidth200 tdoverflowmax250'),
118
        'answer' => array('type' => 'html', 'label' => 'Solution', 'enabled' => 1, 'position' => 600, 'notnull' => 0, 'visible' => 3, 'searchall' => 1, 'csslist' => 'tdoverflowmax300', 'copytoclipboard' => 1, 'tdcss' => 'titlefieldcreate nowraponall'),
119
        'status' => array('type' => 'integer', 'label' => 'Status', 'enabled' => 1, 'position' => 1000, 'notnull' => 1, 'visible' => 5, 'default' => '0', 'index' => 1, 'arrayofkeyval' => array('0' => 'Draft', '1' => 'Validated', '9' => 'Obsolete'),),
120
    );
121
    public $rowid;
122
    public $ref;
123
    public $entity;
124
    public $date_creation;
125
    public $last_main_doc;
126
    public $fk_user_creat;
127
    public $fk_user_modif;
128
    public $fk_user_valid;
129
    public $import_key;
130
    public $model_pdf;
131
132
    /**
133
     * @var string question asked
134
     */
135
    public $question;
136
137
    /**
138
     * @var string answer to question
139
     */
140
    public $answer;
141
    public $url;
142
    public $status;
143
    public $lang;
144
    // END MODULEBUILDER PROPERTIES
145
146
147
    // If this object has a subtable with lines
148
149
    // /**
150
    //  * @var string    Name of subtable line
151
    //  */
152
    // public $table_element_line = 'knowledgemanagement_knowledgerecordline';
153
154
    // /**
155
    //  * @var string    Field with ID of parent key if this object has a parent
156
    //  */
157
    // public $fk_element = 'fk_knowledgerecord';
158
159
    // /**
160
    //  * @var string    Name of subtable class that manage subtable lines
161
    //  */
162
    // public $class_element_line = 'KnowledgeRecordline';
163
164
    // /**
165
    //  * @var array    List of child tables. To test if we can delete object.
166
    //  */
167
    // protected $childtables = array();
168
169
    // /**
170
    //  * @var array    List of child tables. To know object to delete on cascade.
171
    //  *               If name matches '@ClassNAme:FilePathClass;ParentFkFieldName' it will
172
    //  *               call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object
173
    //  */
174
    // protected $childtablesoncascade = array('knowledgemanagement_knowledgerecorddet');
175
176
    // /**
177
    //  * @var KnowledgeRecordLine[]     Array of subtable lines
178
    //  */
179
    // public $lines = array();
180
181
182
183
    /**
184
     * Constructor
185
     *
186
     * @param DoliDB $db Database handler
187
     */
188
    public function __construct(DoliDB $db)
189
    {
190
        global $langs;
191
192
        $this->db = $db;
193
194
        $this->ismultientitymanaged = 1;
195
        $this->isextrafieldmanaged = 1;
196
197
        if (!getDolGlobalString('MAIN_SHOW_TECHNICAL_ID') && isset($this->fields['rowid'])) {
198
            $this->fields['rowid']['visible'] = 0;
199
        }
200
        if (!isModEnabled('multicompany') && isset($this->fields['entity'])) {
201
            $this->fields['entity']['enabled'] = 0;
202
        }
203
204
        // Unset fields that are disabled
205
        foreach ($this->fields as $key => $val) {
206
            if (isset($val['enabled']) && empty($val['enabled'])) {
207
                unset($this->fields[$key]);
208
            }
209
        }
210
211
        // Translate some data of arrayofkeyval
212
        if (is_object($langs)) {
213
            foreach ($this->fields as $key => $val) {
214
                if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
215
                    foreach ($val['arrayofkeyval'] as $key2 => $val2) {
216
                        $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
217
                    }
218
                }
219
            }
220
        }
221
    }
222
223
    /**
224
     * Create object into database
225
     *
226
     * @param  User $user      User that creates
227
     * @param  int  $notrigger 0=launch triggers after, 1=disable triggers
228
     * @return int             Return integer <0 if KO, Id of created object if OK
229
     */
230
    public function create(User $user, $notrigger = 0)
231
    {
232
        return $this->createCommon($user, $notrigger);
233
    }
234
235
    /**
236
     * Clone an object into another one
237
     *
238
     * @param   User    $user       User that creates
239
     * @param   int     $fromid     Id of object to clone
240
     * @return  mixed               New object created, <0 if KO
241
     */
242
    public function createFromClone(User $user, $fromid)
243
    {
244
        global $langs, $extrafields;
245
        $error = 0;
246
247
        dol_syslog(__METHOD__, LOG_DEBUG);
248
249
        $object = new self($this->db);
250
251
        $this->db->begin();
252
253
        // Load source object
254
        $result = $object->fetchCommon($fromid);
255
        if ($result > 0 && !empty($object->table_element_line)) {
256
            $object->fetchLines();
257
        }
258
259
        // get lines so they will be clone
260
        //foreach($this->lines as $line)
261
        //  $line->fetch_optionals();
262
263
        // Reset some properties
264
        unset($object->id);
265
        unset($object->fk_user_creat);
266
        unset($object->import_key);
267
268
        // Clear fields
269
        if (property_exists($object, 'ref')) {
270
            $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_" . $object->ref : $this->fields['ref']['default'];
271
        }
272
        if (property_exists($object, 'question')) {
273
            $object->question = empty($this->fields['question']['default']) ? $langs->trans("CopyOf") . " " . $object->question : $this->fields['question']['default'];
274
        }
275
        if (property_exists($object, 'status')) {
276
            $object->status = self::STATUS_DRAFT;
277
        }
278
        if (property_exists($object, 'date_creation')) {
279
            $object->date_creation = dol_now();
280
        }
281
        if (property_exists($object, 'date_modification')) {
282
            $object->date_modification = null;
283
        }
284
        // ...
285
        // Clear extrafields that are unique
286
        if (is_array($object->array_options) && count($object->array_options) > 0) {
287
            $extrafields->fetch_name_optionals_label($this->table_element);
288
            foreach ($object->array_options as $key => $option) {
289
                $shortkey = preg_replace('/options_/', '', $key);
290
                if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) {
291
                    //var_dump($key);
292
                    //var_dump($clonedObj->array_options[$key]); exit;
293
                    unset($object->array_options[$key]);
294
                }
295
            }
296
        }
297
298
        // Create clone
299
        $object->context['createfromclone'] = 'createfromclone';
300
        $result = $object->createCommon($user);
301
        if ($result < 0) {
302
            $error++;
303
            $this->error = $object->error;
304
            $this->errors = $object->errors;
305
        }
306
307
        if (!$error) {
308
            // copy internal contacts
309
            if ($this->copy_linked_contact($object, 'internal') < 0) {
310
                $error++;
311
            }
312
        }
313
314
        if (!$error) {
315
            // copy external contacts if same company
316
            if (property_exists($this, 'fk_soc') && $this->fk_soc == $object->socid) {
317
                if ($this->copy_linked_contact($object, 'external') < 0) {
318
                    $error++;
319
                }
320
            }
321
        }
322
323
        unset($object->context['createfromclone']);
324
325
        // End
326
        if (!$error) {
327
            $this->db->commit();
328
            return $object;
329
        } else {
330
            $this->db->rollback();
331
            return -1;
332
        }
333
    }
334
335
    /**
336
     * Load object in memory from the database
337
     *
338
     * @param int    $id   Id object
339
     * @param string $ref  Ref
340
     * @return int         Return integer <0 if KO, 0 if not found, >0 if OK
341
     */
342
    public function fetch($id, $ref = null)
343
    {
344
        $result = $this->fetchCommon($id, $ref);
345
        if ($result > 0 && !empty($this->table_element_line)) {
346
            $this->fetchLines();
347
        }
348
        return $result;
349
    }
350
351
    /**
352
     * Load object lines in memory from the database
353
     *
354
     * @return int         Return integer <0 if KO, 0 if not found, >0 if OK
355
     */
356
    public function fetchLines()
357
    {
358
        $this->lines = array();
359
360
        $result = $this->fetchLinesCommon();
361
        return $result;
362
    }
363
364
365
    /**
366
     * Load list of objects in memory from the database.
367
     *
368
     * @param  string           $sortorder      Sort Order
369
     * @param  string           $sortfield      Sort field
370
     * @param  int              $limit          Limit
371
     * @param  int              $offset         Offset
372
     * @param  string|array     $filter         Filter USF.
373
     * @param  string           $filtermode     Filter mode (AND or OR)
374
     * @return array|int                        int <0 if KO, array of pages if OK
375
     */
376
    public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, $filter = '', $filtermode = 'AND')
377
    {
378
        dol_syslog(__METHOD__, LOG_DEBUG);
379
380
        $records = array();
381
382
        $sql = 'SELECT ';
383
        $sql .= $this->getFieldList('t');
384
        $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t';
385
        if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
386
            $sql .= ' WHERE t.entity IN (' . getEntity($this->element) . ')';
387
        } else {
388
            $sql .= ' WHERE 1 = 1';
389
        }
390
391
        // Manage filter
392
        if (is_array($filter)) {
393
            $sqlwhere = array();
394
            if (count($filter) > 0) {
395
                foreach ($filter as $key => $value) {
396
                    if ($key == 't.rowid') {
397
                        $sqlwhere[] = $this->db->sanitize($key) . " = " . ((int) $value);
398
                    } elseif (array_key_exists($key, $this->fields) && in_array($this->fields[$key]['type'], array('date', 'datetime', 'timestamp'))) {
399
                        $sqlwhere[] = $this->db->sanitize($key) . " = '" . $this->db->idate($value) . "'";
400
                    } elseif (strpos($value, '%') === false) {
401
                        $sqlwhere[] = $this->db->sanitize($key) . ' IN (' . $this->db->sanitize($this->db->escape($value)) . ')';
402
                    } else {
403
                        $sqlwhere[] = $this->db->sanitize($key) . " LIKE '%" . $this->db->escape($this->db->escapeforlike($value)) . "%'";
404
                    }
405
                }
406
            }
407
            if (count($sqlwhere) > 0) {
408
                $sql .= ' AND (' . implode(' ' . $this->db->escape($filtermode) . ' ', $sqlwhere) . ')';
409
            }
410
411
            $filter = '';
412
        }
413
414
        // Manage filter
415
        $errormessage = '';
416
        $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
417
        if ($errormessage) {
418
            $this->errors[] = $errormessage;
419
            dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
420
            return -1;
421
        }
422
423
        if (!empty($sortfield)) {
424
            $sql .= $this->db->order($sortfield, $sortorder);
425
        }
426
        if (!empty($limit)) {
427
            $sql .= $this->db->plimit($limit, $offset);
428
        }
429
430
        $resql = $this->db->query($sql);
431
        if ($resql) {
432
            $num = $this->db->num_rows($resql);
433
            $i = 0;
434
            while ($i < ($limit ? min($limit, $num) : $num)) {
435
                $obj = $this->db->fetch_object($resql);
436
437
                $record = new self($this->db);
438
                $record->setVarsFromFetchObj($obj);
439
440
                $records[$record->id] = $record;
441
442
                $i++;
443
            }
444
            $this->db->free($resql);
445
446
            return $records;
447
        } else {
448
            $this->errors[] = 'Error ' . $this->db->lasterror();
449
            dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
450
451
            return -1;
452
        }
453
    }
454
455
    /**
456
     * Update object into database
457
     *
458
     * @param  User $user      User that modifies
459
     * @param  int  $notrigger 0=launch triggers after, 1=disable triggers
460
     * @return int             Return integer <0 if KO, >0 if OK
461
     */
462
    public function update(User $user, $notrigger = 0)
463
    {
464
        return $this->updateCommon($user, $notrigger);
465
    }
466
467
    /**
468
     * Delete object in database
469
     *
470
     * @param User  $user       User that deletes
471
     * @param int   $notrigger  0=launch triggers after, 1=disable triggers
472
     * @return int              Return integer <0 if KO, >0 if OK
473
     */
474
    public function delete(User $user, $notrigger = 0)
475
    {
476
        $error = 0;
477
        $sql = "DELETE FROM " . MAIN_DB_PREFIX . "categorie_knowledgemanagement WHERE fk_knowledgemanagement = " . ((int) $this->id);
478
        dol_syslog(get_class($this) . "::delete", LOG_DEBUG);
479
        $resql = $this->db->query($sql);
480
        if (!$resql) {
481
            $error++;
482
            $this->error .= $this->db->lasterror();
483
            $errorflag = -1;
484
        }
485
486
        // Delete all child tables
487
        if (!$error) {
488
            $elements = array('categorie_knowledgemanagement');
489
            foreach ($elements as $table) {
490
                if (!$error) {
491
                    $sql = "DELETE FROM " . MAIN_DB_PREFIX . $table;
492
                    $sql .= " WHERE fk_knowledgemanagement = " . (int) $this->id;
493
494
                    $result = $this->db->query($sql);
495
                    if (!$result) {
496
                        $error++;
497
                        $this->errors[] = $this->db->lasterror();
498
                    }
499
                }
500
            }
501
        }
502
503
        return $this->deleteCommon($user, $notrigger);
504
        //return $this->deleteCommon($user, $notrigger, 1);
505
    }
506
507
    /**
508
     *  Delete a line of object in database
509
     *
510
     *  @param  User    $user       User that delete
511
     *  @param  int     $idline     Id of line to delete
512
     *  @param  int     $notrigger  0=launch triggers after, 1=disable triggers
513
     *  @return int                 Return >0 if OK, <0 if KO
514
     */
515
    public function deleteLine(User $user, $idline, $notrigger = 0)
516
    {
517
        if ($this->status < 0) {
518
            $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
519
            return -2;
520
        }
521
522
        return $this->deleteLineCommon($user, $idline, $notrigger);
523
    }
524
525
526
    /**
527
     *  Validate object
528
     *
529
     *  @param      User    $user           User making status change
530
     *  @param      int     $notrigger      1=Does not execute triggers, 0= execute triggers
531
     *  @return     int                     Return integer <=0 if OK, 0=Nothing done, >0 if KO
532
     */
533
    public function validate($user, $notrigger = 0)
534
    {
535
        global $conf, $langs;
536
537
        require_once constant('DOL_DOCUMENT_ROOT') . '/core/lib/files.lib.php';
538
539
        $error = 0;
540
541
        // Protection
542
        if ($this->status == self::STATUS_VALIDATED) {
543
            dol_syslog(get_class($this) . "::validate action abandoned: already validated", LOG_WARNING);
544
            return 0;
545
        }
546
547
        /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->hasRight('knowledgemanagement', 'knowledgerecord', 'write'))
548
         || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->knowledgemanagement->knowledgerecord->knowledgerecord_advance->validate))))
549
         {
550
         $this->error='NotEnoughPermissions';
551
         dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
552
         return -1;
553
         }*/
554
555
        $now = dol_now();
556
557
        $this->db->begin();
558
559
        // Define new ref
560
        if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
561
            $num = $this->getNextNumRef();
562
        } else {
563
            $num = $this->ref;
564
        }
565
        $this->newref = $num;
566
567
        if (!empty($num)) {
568
            // Validate
569
            $sql = "UPDATE " . MAIN_DB_PREFIX . $this->table_element;
570
            $sql .= " SET ref = '" . $this->db->escape($num) . "',";
571
            $sql .= " status = " . self::STATUS_VALIDATED;
572
            if (!empty($this->fields['date_validation'])) {
573
                $sql .= ", date_validation = '" . $this->db->idate($now) . "'";
574
            }
575
            if (!empty($this->fields['fk_user_valid'])) {
576
                $sql .= ", fk_user_valid = " . ((int) $user->id);
577
            }
578
            $sql .= " WHERE rowid = " . ((int) $this->id);
579
580
            dol_syslog(get_class($this) . "::validate()", LOG_DEBUG);
581
            $resql = $this->db->query($sql);
582
            if (!$resql) {
583
                dol_print_error($this->db);
584
                $this->error = $this->db->lasterror();
585
                $error++;
586
            }
587
588
            if (!$error && !$notrigger) {
589
                // Call trigger
590
                $result = $this->call_trigger('KNOWLEDGERECORD_VALIDATE', $user);
591
                if ($result < 0) {
592
                    $error++;
593
                }
594
                // End call triggers
595
            }
596
        }
597
598
        if (!$error) {
599
            $this->oldref = $this->ref;
600
601
            // Rename directory if dir was a temporary ref
602
            if (preg_match('/^[\(]?PROV/i', $this->ref)) {
603
                // Now we rename also files into index
604
                $sql = 'UPDATE ' . MAIN_DB_PREFIX . "ecm_files set filename = CONCAT('" . $this->db->escape($this->newref) . "', SUBSTR(filename, " . (strlen($this->ref) + 1) . ")), filepath = 'knowledgerecord/" . $this->db->escape($this->newref) . "'";
605
                $sql .= " WHERE filename LIKE '" . $this->db->escape($this->ref) . "%' AND filepath = 'knowledgerecord/" . $this->db->escape($this->ref) . "' and entity = " . $conf->entity;
606
                $resql = $this->db->query($sql);
607
                if (!$resql) {
608
                    $error++;
609
                    $this->error = $this->db->lasterror();
610
                }
611
                $sql = 'UPDATE ' . MAIN_DB_PREFIX . "ecm_files set filepath = 'knowledgerecord/" . $this->db->escape($this->newref) . "'";
612
                $sql .= " WHERE filepath = 'knowledgerecord/" . $this->db->escape($this->ref) . "' and entity = " . $conf->entity;
613
                $resql = $this->db->query($sql);
614
                if (!$resql) {
615
                    $error++;
616
                    $this->error = $this->db->lasterror();
617
                }
618
619
                // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
620
                $oldref = dol_sanitizeFileName($this->ref);
621
                $newref = dol_sanitizeFileName($num);
622
                $dirsource = $conf->knowledgemanagement->dir_output . '/knowledgerecord/' . $oldref;
623
                $dirdest = $conf->knowledgemanagement->dir_output . '/knowledgerecord/' . $newref;
624
                if (!$error && file_exists($dirsource)) {
625
                    dol_syslog(get_class($this) . "::validate() rename dir " . $dirsource . " into " . $dirdest);
626
627
                    if (@rename($dirsource, $dirdest)) {
628
                        dol_syslog("Rename ok");
629
                        // Rename docs starting with $oldref with $newref
630
                        $listoffiles = dol_dir_list($conf->knowledgemanagement->dir_output . '/knowledgerecord/' . $newref, 'files', 1, '^' . preg_quote($oldref, '/'));
631
                        foreach ($listoffiles as $fileentry) {
632
                            $dirsource = $fileentry['name'];
633
                            $dirdest = preg_replace('/^' . preg_quote($oldref, '/') . '/', $newref, $dirsource);
634
                            $dirsource = $fileentry['path'] . '/' . $dirsource;
635
                            $dirdest = $fileentry['path'] . '/' . $dirdest;
636
                            @rename($dirsource, $dirdest);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for rename(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

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

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

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

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
637
                        }
638
                    }
639
                }
640
            }
641
        }
642
643
        // Set new ref and current status
644
        if (!$error) {
645
            $this->ref = $num;
646
            $this->status = self::STATUS_VALIDATED;
647
        }
648
649
        if (!$error) {
650
            $this->db->commit();
651
            return 1;
652
        } else {
653
            $this->db->rollback();
654
            return -1;
655
        }
656
    }
657
658
659
    /**
660
     *  Set draft status
661
     *
662
     *  @param  User    $user           Object user that modify
663
     *  @param  int     $notrigger      1=Does not execute triggers, 0=Execute triggers
664
     *  @return int                     Return integer <0 if KO, >0 if OK
665
     */
666
    public function setDraft($user, $notrigger = 0)
667
    {
668
        // Protection
669
        if ($this->status <= self::STATUS_DRAFT) {
670
            return 0;
671
        }
672
673
        /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->knowledgemanagement->write))
674
         || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->knowledgemanagement->knowledgemanagement_advance->validate))))
675
         {
676
         $this->error='Permission denied';
677
         return -1;
678
         }*/
679
680
        return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'KNOWLEDGERECORD_UNVALIDATE');
681
    }
682
683
    /**
684
     *  Set cancel status
685
     *
686
     *  @param  User    $user           Object user that modify
687
     *  @param  int     $notrigger      1=Does not execute triggers, 0=Execute triggers
688
     *  @return int                     Return integer <0 if KO, 0=Nothing done, >0 if OK
689
     */
690
    public function cancel($user, $notrigger = 0)
691
    {
692
        // Protection
693
        if ($this->status != self::STATUS_VALIDATED) {
694
            return 0;
695
        }
696
697
        /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->knowledgemanagement->write))
698
         || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->knowledgemanagement->knowledgemanagement_advance->validate))))
699
         {
700
         $this->error='Permission denied';
701
         return -1;
702
         }*/
703
704
        return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'KNOWLEDGERECORD_CANCEL');
705
    }
706
707
    /**
708
     *  Set back to validated status
709
     *
710
     *  @param  User    $user           Object user that modify
711
     *  @param  int     $notrigger      1=Does not execute triggers, 0=Execute triggers
712
     *  @return int                     Return integer <0 if KO, 0=Nothing done, >0 if OK
713
     */
714
    public function reopen($user, $notrigger = 0)
715
    {
716
        // Protection
717
        if ($this->status != self::STATUS_CANCELED) {
718
            return 0;
719
        }
720
721
        /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->knowledgemanagement->write))
722
         || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->knowledgemanagement->knowledgemanagement_advance->validate))))
723
         {
724
         $this->error='Permission denied';
725
         return -1;
726
         }*/
727
728
        return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'KNOWLEDGERECORD_REOPEN');
729
    }
730
731
    /**
732
     * getTooltipContentArray
733
     *
734
     * @param array $params ex option, infologin
735
     * @since v18
736
     * @return array
737
     */
738
    public function getTooltipContentArray($params)
739
    {
740
        global $conf, $langs;
741
742
        $langs->loadLangs(['knowledgemanagement', 'languages']);
743
744
        $datas = array();
745
        $nofetch = !empty($params['nofetch']);
746
747
        $datas['picto'] = img_picto('', $this->picto) . ' <u class="paddingrightonly">' . $langs->trans("KnowledgeRecord") . '</u>';
748
        if (isset($this->statut)) {
0 ignored issues
show
Deprecated Code introduced by
The property Dolibarr\Core\Base\CommonObject::$statut has been deprecated: Use $status instead. ( Ignorable by Annotation )

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

748
        if (isset(/** @scrutinizer ignore-deprecated */ $this->statut)) {

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
749
            $datas['picto'] .= ' ' . $this->getLibStatut(5);
750
        }
751
        $datas['label'] = '<br><b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;
752
        $datas['question'] = '<br><b>' . $langs->trans('Question') . ':</b> ' . $this->question;
753
        $labellang = ($this->lang ? $langs->trans('Language_' . $this->lang) : '');
754
        $datas['lang'] = '<br><b>' . $langs->trans('Language') . ':</b> ' . picto_from_langcode($this->lang, 'class="paddingrightonly saturatemedium opacitylow"') . $labellang;
755
        // show categories for this record only in ajax to not overload lists
756
        if (isModEnabled('category') && !$nofetch) {
757
            $form = new Form($this->db);
758
            $datas['categories'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_KNOWLEDGEMANAGEMENT, 1);
759
        }
760
761
        return $datas;
762
    }
763
764
    /**
765
     *  Return a link to the object card (with optionally the picto)
766
     *
767
     *  @param  int     $withpicto                  Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
768
     *  @param  string  $option                     On what the link point to ('nolink', ...)
769
     *  @param  int     $notooltip                  1=Disable tooltip
770
     *  @param  string  $morecss                    Add more css on link
771
     *  @param  int     $save_lastsearch_value      -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
772
     *  @return string                              String with URL
773
     */
774
    public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
775
    {
776
        global $conf, $langs, $hookmanager;
777
778
        if (!empty($conf->dol_no_mouse_hover)) {
779
            $notooltip = 1; // Force disable tooltips
780
        }
781
782
        $result = '';
783
784
        $params = [
785
            'id' => $this->id,
786
            'objecttype' => $this->element . ($this->module ? '@' . $this->module : ''),
787
            'option' => $option,
788
            'nofetch' => 1,
789
        ];
790
        $classfortooltip = 'classfortooltip';
791
        $dataparams = '';
792
        if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
793
            $classfortooltip = 'classforajaxtooltip';
794
            $dataparams = ' data-params="' . dol_escape_htmltag(json_encode($params)) . '"';
795
            $label = '';
796
        } else {
797
            $label = implode($this->getTooltipContentArray($params));
798
        }
799
800
        $url = dol_buildpath('/knowledgemanagement/knowledgerecord_card.php', 1) . '?id=' . $this->id;
801
802
        if ($option != 'nolink') {
803
            // Add param to save lastsearch_values or not
804
            $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
805
            if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
806
                $add_save_lastsearch_values = 1;
807
            }
808
            if ($add_save_lastsearch_values) {
809
                $url .= '&save_lastsearch_values=1';
810
            }
811
        }
812
813
        $linkclose = '';
814
        if (empty($notooltip)) {
815
            if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
816
                $label = $langs->trans("ShowKnowledgeRecord");
817
                $linkclose .= ' alt="' . dol_escape_htmltag($label, 1) . '"';
818
            }
819
            $linkclose .= ($label ? ' title="' . dol_escape_htmltag($label, 1) . '"' : ' title="tocomplete"');
820
            $linkclose .= $dataparams . ' class="' . $classfortooltip . ($morecss ? ' ' . $morecss : '') . '"';
821
        } else {
822
            $linkclose = ($morecss ? ' class="' . $morecss . '"' : '');
823
        }
824
825
        if ($option == 'nolink') {
826
            $linkstart = '<span';
827
        } else {
828
            $linkstart = '<a href="' . $url . '"';
829
        }
830
        $linkstart .= $linkclose . '>';
831
        if ($option == 'nolink') {
832
            $linkend = '</span>';
833
        } else {
834
            $linkend = '</a>';
835
        }
836
837
        $result .= $linkstart;
838
839
        if (empty($this->showphoto_on_popup)) {
840
            if ($withpicto) {
841
                $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : $dataparams . ' class="' . (($withpicto != 2) ? 'paddingright ' : '') . $classfortooltip . '"'), 0, 0, $notooltip ? 0 : 1);
842
            }
843
        } else {
844
            if ($withpicto) {
845
                require_once constant('DOL_DOCUMENT_ROOT') . '/core/lib/files.lib.php';
846
847
                list($class, $module) = explode('@', $this->picto);
848
                $upload_dir = $conf->$module->multidir_output[$conf->entity] . "/$class/" . dol_sanitizeFileName($this->ref);
849
                $filearray = dol_dir_list($upload_dir, "files");
850
                $filename = $filearray[0]['name'];
851
                if (!empty($filename)) {
852
                    $pospoint = strpos($filearray[0]['name'], '.');
853
854
                    $pathtophoto = $class . '/' . $this->ref . '/thumbs/' . substr($filename, 0, $pospoint) . '_mini' . substr($filename, $pospoint);
855
                    if (!getDolGlobalString(strtoupper($module . '_' . $class) . '_FORMATLISTPHOTOSASUSERS')) {
856
                        $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>';
857
                    } else {
858
                        $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>';
859
                    }
860
861
                    $result .= '</div>';
862
                } else {
863
                    $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (($withpicto != 2) ? 'class="paddingright"' : ''), 0, 0, $notooltip ? 0 : 1);
864
                }
865
            }
866
        }
867
868
        if ($withpicto != 2) {
869
            $result .= $this->ref;
870
        }
871
872
        $result .= $linkend;
873
        //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
874
875
        global $action, $hookmanager;
876
        $hookmanager->initHooks(array('knowledgerecorddao'));
877
        $parameters = array('id' => $this->id, 'getnomurl' => &$result);
878
        $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
879
        if ($reshook > 0) {
880
            $result = $hookmanager->resPrint;
881
        } else {
882
            $result .= $hookmanager->resPrint;
883
        }
884
885
        return $result;
886
    }
887
888
    /**
889
     *  Return the label of the status
890
     *
891
     *  @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
892
     *  @return string                 Label of status
893
     */
894
    public function getLibStatut($mode = 0)
895
    {
896
        return $this->LibStatut($this->status, $mode);
897
    }
898
899
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
900
    /**
901
     *  Return the status
902
     *
903
     *  @param  int     $status        Id status
904
     *  @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
905
     *  @return string                 Label of status
906
     */
907
    public function LibStatut($status, $mode = 0)
908
    {
909
		// phpcs:enable
910
        if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
911
            global $langs;
912
            //$langs->load("knowledgemanagement");
913
            $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
914
            $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Validated');
915
            $this->labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Obsolete');
916
            $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
917
            $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Validated');
918
            $this->labelStatusShort[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Obsolete');
919
        }
920
921
        $statusType = 'status' . $status;
922
        if ($status == self::STATUS_VALIDATED) {
923
            $statusType = 'status4';
924
        }
925
        if ($status == self::STATUS_CANCELED) {
926
            $statusType = 'status6';
927
        }
928
929
        return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
930
    }
931
932
    /**
933
     *  Load the info information in the object
934
     *
935
     *  @param  int     $id       Id of object
936
     *  @return void
937
     */
938
    public function info($id)
939
    {
940
        $sql = 'SELECT rowid, date_creation as datec, tms as datem,';
941
        $sql .= ' fk_user_creat, fk_user_modif';
942
        $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t';
943
        $sql .= ' WHERE t.rowid = ' . ((int) $id);
944
        $result = $this->db->query($sql);
945
        if ($result) {
946
            if ($this->db->num_rows($result)) {
947
                $obj = $this->db->fetch_object($result);
948
949
                $this->id = $obj->rowid;
950
951
                $this->user_creation_id = $obj->fk_user_creat;
952
                $this->user_modification_id = $obj->fk_user_modif;
953
                $this->date_creation     = $this->db->jdate($obj->datec);
954
                $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
955
            }
956
957
            $this->db->free($result);
958
        } else {
959
            dol_print_error($this->db);
960
        }
961
    }
962
963
    /**
964
     * Initialise object with example values
965
     * Id must be 0 if object instance is a specimen
966
     *
967
     * @return int
968
     */
969
    public function initAsSpecimen()
970
    {
971
        $this->question = "ABCD";
972
973
        return $this->initAsSpecimenCommon();
974
    }
975
976
    /**
977
     *  Create an array of lines
978
     *
979
     *  @return array|int       array of lines if OK, <0 if KO
980
     */
981
    public function getLinesArray()
982
    {
983
        $this->lines = array();
984
985
        $objectline = new KnowledgeRecordLine($this->db);
986
        $result = $objectline->fetchAll('ASC', 'position', 0, 0, '(fk_knowledgerecord:=:' . ((int) $this->id) . ')');
987
988
        if (is_numeric($result)) {
989
            $this->error = $objectline->error;
990
            $this->errors = $objectline->errors;
991
            return $result;
992
        } else {
993
            $this->lines = $result;
994
            return $this->lines;
995
        }
996
    }
997
998
    /**
999
     *  Returns the reference to the following non used object depending on the active numbering module.
1000
     *
1001
     *  @return string              Object free reference
1002
     */
1003
    public function getNextNumRef()
1004
    {
1005
        global $langs, $conf;
1006
        $langs->load("knowledgemanagement");
1007
1008
        if (!getDolGlobalString('KNOWLEDGEMANAGEMENT_KNOWLEDGERECORD_ADDON')) {
1009
            $conf->global->KNOWLEDGEMANAGEMENT_KNOWLEDGERECORD_ADDON = 'mod_knowledgerecord_standard';
1010
        }
1011
1012
        if (getDolGlobalString('KNOWLEDGEMANAGEMENT_KNOWLEDGERECORD_ADDON')) {
1013
            $mybool = false;
1014
1015
            $file = getDolGlobalString('KNOWLEDGEMANAGEMENT_KNOWLEDGERECORD_ADDON') . ".php";
1016
            $classname = getDolGlobalString('KNOWLEDGEMANAGEMENT_KNOWLEDGERECORD_ADDON');
1017
1018
            // Include file with class
1019
            $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
1020
            foreach ($dirmodels as $reldir) {
1021
                $dir = dol_buildpath($reldir . "core/modules/knowledgemanagement/");
1022
1023
                // Load file with numbering class (if found)
1024
                $mybool = ((bool) @include_once $dir . $file) || $mybool;
1025
            }
1026
1027
            if ($mybool === false) {
1028
                dol_print_error(null, "Failed to include file " . $file);
1029
                return '';
1030
            }
1031
1032
            if (class_exists($classname)) {
1033
                $obj = new $classname();
1034
                $numref = $obj->getNextValue($this);
1035
1036
                if ($numref != '' && $numref != '-1') {
1037
                    return $numref;
1038
                } else {
1039
                    $this->error = $obj->error;
1040
                    //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
1041
                    return "";
1042
                }
1043
            } else {
1044
                print $langs->trans("Error") . " " . $langs->trans("ClassNotFound") . ' ' . $classname;
1045
                return "";
1046
            }
1047
        } else {
1048
            print $langs->trans("ErrorNumberingModuleNotSetup", $this->element);
1049
            return "";
1050
        }
1051
    }
1052
1053
    /**
1054
     *  Create a document onto disk according to template module.
1055
     *
1056
     *  @param      string      $modele         Force template to use ('' to not force)
1057
     *  @param      Translate   $outputlangs    object lang a utiliser pour traduction
1058
     *  @param      int         $hidedetails    Hide details of lines
1059
     *  @param      int         $hidedesc       Hide description
1060
     *  @param      int         $hideref        Hide ref
1061
     *  @param      null|array  $moreparams     Array to provide more information
1062
     *  @return     int                         0 if KO, 1 if OK
1063
     */
1064
    public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
1065
    {
1066
        global $conf, $langs;
1067
1068
        $result = 0;
1069
        $includedocgeneration = 0;
1070
1071
        $langs->load("knowledgemanagement");
1072
1073
        if (!dol_strlen($modele)) {
1074
            $modele = 'standard_knowledgerecord';
1075
1076
            if (!empty($this->model_pdf)) {
1077
                $modele = $this->model_pdf;
1078
            } elseif (getDolGlobalString('KNOWLEDGERECORD_ADDON_PDF')) {
1079
                $modele = getDolGlobalString('KNOWLEDGERECORD_ADDON_PDF');
1080
            }
1081
        }
1082
1083
        $modelpath = "core/modules/knowledgemanagement/doc/";
1084
1085
        if ($includedocgeneration && !empty($modele)) {
1086
            $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
1087
        }
1088
1089
        return $result;
1090
    }
1091
1092
    /**
1093
     * Action executed by scheduler
1094
     * CAN BE A CRON TASK. In such a case, parameters come from the schedule job setup field 'Parameters'
1095
     * Use public function doScheduledJob($param1, $param2, ...) to get parameters
1096
     *
1097
     * @return  int         0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
1098
     */
1099
    public function doScheduledJob()
1100
    {
1101
        global $conf, $langs;
1102
1103
        //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
1104
1105
        $error = 0;
1106
        $this->output = '';
1107
        $this->error = '';
1108
1109
        dol_syslog(__METHOD__, LOG_DEBUG);
1110
1111
        $now = dol_now();
1112
1113
        $this->db->begin();
1114
1115
        // ...
1116
1117
        $this->db->commit();
1118
1119
        return $error;
1120
    }
1121
1122
    /**
1123
     * Sets object to supplied categories.
1124
     *
1125
     * Deletes object from existing categories not supplied.
1126
     * Adds it to non existing supplied categories.
1127
     * Existing categories are left untouch.
1128
     *
1129
     * @param   int[]|int   $categories     Category or categories IDs
1130
     * @return  int                         Return integer <0 if KO, >0 if OK
1131
     */
1132
    public function setCategories($categories)
1133
    {
1134
        return parent::setCategoriesCommon($categories, Categorie::TYPE_KNOWLEDGEMANAGEMENT);
1135
    }
1136
1137
    /**
1138
     *  Return clicable link of object (with eventually picto)
1139
     *
1140
     *  @param      string      $option                 Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
1141
     *  @param      array       $arraydata              Array of data
1142
     *  @return     string                              HTML Code for Kanban thumb.
1143
     */
1144
    public function getKanbanView($option = '', $arraydata = null)
1145
    {
1146
        $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
1147
1148
        $return = '<div class="box-flex-item box-flex-grow-zero">';
1149
        $return .= '<div class="info-box info-box-sm">';
1150
        $return .= '<span class="info-box-icon bg-infobox-action">';
1151
        $return .= img_picto('', $this->picto);
1152
        $return .= '</span>';
1153
        $return .= '<div class="info-box-content">';
1154
        $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">' . (method_exists($this, 'getNomUrl') ? $this->getNomUrl(1) : $this->ref) . '</span>';
1155
        if ($selected >= 0) {
1156
            $return .= '<input id="cb' . $this->id . '" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="' . $this->id . '"' . ($selected ? ' checked="checked"' : '') . '>';
1157
        }
1158
        if (property_exists($this, 'lang') && !empty($this->lang)) {
1159
            //$return .= '<br><span class="opacitymedium">'.$langs->trans("Language").'</span> : <span class="info-box-label" title="'.$langs->trans("Language_".$this->lang).'">'.$langs->trans("Language_".$this->lang, '', '', '', '', 12).'</span>';
1160
            $return .= '<br>' . picto_from_langcode($this->lang, 'class="paddingrightonly saturatemedium opacitylow paddingrightonly"');
1161
        }
1162
        if (property_exists($this, 'question')) {
1163
            $return .= '<div class="info-box-label tdoverflowmax150 classfortooltip" title="' . dolPrintHTMLForAttribute($this->question) . '">' . dolGetFirstLineOfText($this->question) . '</div>';
1164
        }
1165
        if (method_exists($this, 'getLibStatut')) {
1166
            $return .= '<div class="info-box-status">' . $this->getLibStatut(3) . '</div>';
1167
        }
1168
        $return .= '</div>';
1169
        $return .= '</div>';
1170
        $return .= '</div>';
1171
        return $return;
1172
    }
1173
}
1174