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

Availabilities::validate()   F

Complexity

Conditions 22
Paths 2801

Size

Total Lines 114
Code Lines 71

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 22
eloc 71
nc 2801
nop 2
dl 0
loc 114
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/* Copyright (C) 2017       Laurent Destailleur         <[email protected]>
4
 * Copyright (C) 2022       Alice Adminson              <[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\BookCal\Classes;
24
25
/**
26
 * \file        htdocs/bookcal/class/availabilities.class.php
27
 * \ingroup     bookcal
28
 * \brief       This file is a CRUD class file for Availabilities (Create/Read/Update/Delete)
29
 */
30
31
// Put here all includes required by your class file
32
use Dolibarr\Core\Base\CommonObject;
33
//require_once constant('DOL_DOCUMENT_ROOT') . '/societe/class/societe.class.php';
34
//require_once constant('DOL_DOCUMENT_ROOT') . '/product/class/product.class.php';
35
36
/**
37
 * Class for Availabilities
38
 */
39
class Availabilities extends CommonObject
40
{
41
    /**
42
     * @var string ID of module.
43
     */
44
    public $module = 'bookcal';
45
46
    /**
47
     * @var string ID to identify managed object.
48
     */
49
    public $element = 'availabilities';
50
51
    /**
52
     * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management.
53
     */
54
    public $table_element = 'bookcal_availabilities';
55
56
    /**
57
     * @var string String with name of icon for availabilities. Must be a 'fa-xxx' fontawesome code (or 'fa-xxx_fa_color_size') or 'availabilities@bookcal' if picto is file 'img/object_availabilities.png'.
58
     */
59
    public $picto = 'fa-calendar-check';
60
61
62
    const STATUS_DRAFT = 0;
63
    const STATUS_VALIDATED = 1;
64
    const STATUS_CANCELED = 9;
65
66
67
    /**
68
     *  'type' field format:
69
     *      'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',
70
     *      'select' (list of values are in 'options'),
71
     *      'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter[:Sortfield]]]]',
72
     *      'chkbxlst:...',
73
     *      'varchar(x)',
74
     *      'text', 'text:none', 'html',
75
     *      'double(24,8)', 'real', 'price',
76
     *      'date', 'datetime', 'timestamp', 'duration',
77
     *      'boolean', 'checkbox', 'radio', 'array',
78
     *      'mail', 'phone', 'url', 'password', 'ip'
79
     *      Note: Filter must be a Dolibarr Universal Filter syntax string. Example: "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.status:!=:0) or (t.nature:is:NULL)"
80
     *  'label' the translation key.
81
     *  'picto' is code of a picto to show before value in forms
82
     *  'enabled' is a condition when the field must be managed (Example: 1 or 'getDolGlobalInt('MY_SETUP_PARAM') or 'isModEnabled("multicurrency")' ...)
83
     *  'position' is the sort order of field.
84
     *  'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
85
     *  'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing)
86
     *  'noteditable' says if field is not editable (1 or 0)
87
     *  'alwayseditable' says if field can be modified also when status is not draft ('1' or '0')
88
     *  '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.
89
     *  'index' if we want an index in database.
90
     *  'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommended to name the field fk_...).
91
     *  'searchall' is 1 if we want to search in this field when making a search from the quick search button.
92
     *  '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)
93
     *  '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'
94
     *  'help' and 'helplist' is a 'TranslationString' to use to show a tooltip on field. You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
95
     *  'showoncombobox' if value of the field must be visible into the label of the combobox that list record
96
     *  '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.
97
     *  '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'
98
     *  'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1.
99
     *  'comment' is not used. You can store here any text of your choice. It is not used by application.
100
     *  'validate' is 1 if need to validate with $this->validateField()
101
     *  'copytoclipboard' is 1 or 2 to allow to add a picto to copy value into clipboard (1=picto after label, 2=picto after value)
102
     *
103
     *  Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
104
     */
105
106
    // BEGIN MODULEBUILDER PROPERTIES
107
    /**
108
     * @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...
109
     */
110
    public $fields = array(
111
        'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'position' => 1, 'notnull' => 1, 'visible' => 2, 'noteditable' => 1, 'index' => 1, 'css' => 'left', 'comment' => "Id"),
112
        'label' => array('type' => 'varchar(255)', 'label' => 'Label', 'enabled' => 1, 'position' => 20, 'notnull' => 0, 'visible' => 1, 'searchall' => 1, 'css' => 'minwidth300', 'csslist' => 'tdoverflowmax150', 'cssview' => 'wordbreak', 'help' => "BookcalLabelAvailabilityHelp", 'showoncombobox' => 2, 'validate' => 1,),
113
        'fk_bookcal_calendar' => array('type' => 'integer:Calendar:bookcal/class/calendar.class.php:1', 'label' => 'Calendar', 'enabled' => 1, 'position' => 25, 'notnull' => 1, 'visible' => 1, 'css' => 'maxwidth500 widthcentpercentminusxx', 'csslist' => 'tdoverflowmax100'),
114
        'description' => array('type' => 'text', 'label' => 'Description', 'enabled' => 1, 'position' => 60, 'notnull' => 0, 'visible' => 3, 'validate' => 1,),
115
        'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'position' => 61, 'notnull' => 0, 'visible' => 0, 'cssview' => 'wordbreak', 'validate' => 1,),
116
        'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'position' => 62, 'notnull' => 0, 'visible' => 0, 'cssview' => 'wordbreak', 'validate' => 1,),
117
        'date_creation' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'position' => 500, 'notnull' => 1, 'visible' => -2,),
118
        'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'position' => 501, 'notnull' => 0, 'visible' => -2,),
119
        'fk_user_creat' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'picto' => 'user', 'enabled' => 1, 'position' => 510, 'notnull' => 1, 'visible' => -2, 'css' => 'maxwidth500 widthcentpercentminusxx', 'csslist' => 'tdoverflowmax150'),
120
        'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'picto' => 'user', 'enabled' => 1, 'position' => 511, 'notnull' => -1, 'visible' => -2, 'css' => 'maxwidth500 widthcentpercentminusxx', 'csslist' => 'tdoverflowmax150'),
121
        'last_main_doc' => array('type' => 'varchar(255)', 'label' => 'LastMainDoc', 'enabled' => 1, 'position' => 600, 'notnull' => 0, 'visible' => 0,),
122
        'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'position' => 1000, 'notnull' => -1, 'visible' => -2,),
123
        'model_pdf' => array('type' => 'varchar(255)', 'label' => 'Model pdf', 'enabled' => 1, 'position' => 1010, 'notnull' => -1, 'visible' => 0,),
124
        'start' => array('type' => 'date', 'label' => 'Start Date', 'enabled' => 1, 'position' => 40, 'notnull' => 1, 'visible' => 1, 'searchall' => 1,),
125
        'end' => array('type' => 'date', 'label' => 'End Date', 'enabled' => 1, 'position' => 45, 'notnull' => 1, 'visible' => 1, 'searchall' => 1,),
126
        'duration' => array('type' => 'integer', 'label' => 'DurationOfRange', 'enabled' => 1, 'position' => 47, 'notnull' => 1, 'visible' => 1, 'default' => '30', 'css' => 'width50 right'),
127
        'startHour' => array('type' => 'integer', 'label' => 'Start Hour', 'enabled' => 1, 'position' => 46, 'notnull' => 1, 'visible' => 1,),
128
        'endHour' => array('type' => 'integer', 'label' => 'End Hour', 'enabled' => 1, 'position' => 46.5, 'notnull' => 1, 'visible' => 1,),
129
        'status' => array('type' => 'integer', 'label' => 'Status', 'enabled' => 1, 'position' => 2000, 'notnull' => 1, 'visible' => 1, 'index' => 1, 'arrayofkeyval' => array('0' => 'Draft', '1' => 'Validated', '9' => 'Closed'), 'default' => '1', 'validate' => 1),
130
    );
131
    public $rowid;
132
    public $label;
133
    public $description;
134
    public $note_public;
135
    public $note_private;
136
    public $date_creation;
137
    public $fk_user_creat;
138
    public $fk_user_modif;
139
    public $last_main_doc;
140
    public $import_key;
141
    public $model_pdf;
142
    public $status;
143
    public $start;
144
    public $end;
145
    public $duration;
146
    public $startHour;
147
    public $endHour;
148
    public $fk_bookcal_calendar;
149
    // END MODULEBUILDER PROPERTIES
150
151
152
    // If this object has a subtable with lines
153
154
    // /**
155
    //  * @var string    Name of subtable line
156
    //  */
157
    // public $table_element_line = 'bookcal_availabilitiesline';
158
159
    // /**
160
    //  * @var string    Field with ID of parent key if this object has a parent
161
    //  */
162
    // public $fk_element = 'fk_availabilities';
163
164
    // /**
165
    //  * @var string    Name of subtable class that manage subtable lines
166
    //  */
167
    // public $class_element_line = 'Availabilitiesline';
168
169
    // /**
170
    //  * @var array    List of child tables. To test if we can delete object.
171
    //  */
172
    // protected $childtables = array();
173
174
    // /**
175
    //  * @var array    List of child tables. To know object to delete on cascade.
176
    //  *               If name matches '@ClassNAme:FilePathClass;ParentFkFieldName' it will
177
    //  *               call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object
178
    //  */
179
    // protected $childtablesoncascade = array('bookcal_availabilitiesdet');
180
181
    // /**
182
    //  * @var AvailabilitiesLine[]     Array of subtable lines
183
    //  */
184
    // public $lines = array();
185
186
187
188
    /**
189
     * Constructor
190
     *
191
     * @param DoliDB $db Database handler
192
     */
193
    public function __construct(DoliDB $db)
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\BookCal\Classes\DoliDB was not found. Did you mean DoliDB? If so, make sure to prefix the type with \.
Loading history...
194
    {
195
        global $conf, $langs;
196
197
        $this->db = $db;
198
199
        $this->ismultientitymanaged = 'fk_bookcal_calendar@bookcal_calendar';
0 ignored issues
show
Documentation Bug introduced by
The property $ismultientitymanaged was declared of type integer, but 'fk_bookcal_calendar@bookcal_calendar' is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
200
        $this->isextrafieldmanaged = 1;
201
202
        if (!getDolGlobalString('MAIN_SHOW_TECHNICAL_ID') && isset($this->fields['rowid']) && !empty($this->fields['ref'])) {
203
            $this->fields['rowid']['visible'] = 0;
204
        }
205
        if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) {
206
            $this->fields['entity']['enabled'] = 0;
207
        }
208
209
        // Example to show how to set values of fields definition dynamically
210
        /*if ($user->hasRight('bookcal', 'availabilities', 'read')) {
211
            $this->fields['myfield']['visible'] = 1;
212
            $this->fields['myfield']['noteditable'] = 0;
213
        }*/
214
215
        // Unset fields that are disabled
216
        foreach ($this->fields as $key => $val) {
217
            if (isset($val['enabled']) && empty($val['enabled'])) {
218
                unset($this->fields[$key]);
219
            }
220
        }
221
222
        // Translate some data of arrayofkeyval
223
        if (is_object($langs)) {
224
            foreach ($this->fields as $key => $val) {
225
                if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
226
                    foreach ($val['arrayofkeyval'] as $key2 => $val2) {
227
                        $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
228
                    }
229
                }
230
            }
231
        }
232
    }
233
234
    /**
235
     * Create object into database
236
     *
237
     * @param  User $user      User that creates
238
     * @param  int  $notrigger 0=launch triggers after, 1=disable triggers
239
     * @return int             Return integer <0 if KO, Id of created object if OK
240
     */
241
    public function create(User $user, $notrigger = 0)
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\BookCal\Classes\User was not found. Did you mean User? If so, make sure to prefix the type with \.
Loading history...
242
    {
243
        $resultcreate = $this->createCommon($user, $notrigger);
244
245
        //$resultvalidate = $this->validate($user, $notrigger);
246
247
        return $resultcreate;
248
    }
249
250
    /**
251
     * Clone an object into another one
252
     *
253
     * @param   User    $user       User that creates
254
     * @param   int     $fromid     Id of object to clone
255
     * @return  mixed               New object created, <0 if KO
256
     */
257
    public function createFromClone(User $user, $fromid)
258
    {
259
        global $langs, $extrafields;
260
        $error = 0;
261
262
        dol_syslog(__METHOD__, LOG_DEBUG);
263
264
        $object = new self($this->db);
265
266
        $this->db->begin();
267
268
        // Load source object
269
        $result = $object->fetchCommon($fromid);
270
        if ($result > 0 && !empty($object->table_element_line)) {
271
            $object->fetchLines();
272
        }
273
274
        // get lines so they will be clone
275
        //foreach($this->lines as $line)
276
        //  $line->fetch_optionals();
277
278
        // Reset some properties
279
        unset($object->id);
280
        unset($object->fk_user_creat);
281
        unset($object->import_key);
282
283
        // Clear fields
284
        if (property_exists($object, 'ref')) {
285
            $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_" . $object->ref : $this->fields['ref']['default'];
286
        }
287
        if (property_exists($object, 'label')) {
288
            $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf") . " " . $object->label : $this->fields['label']['default'];
289
        }
290
        if (property_exists($object, 'status')) {
291
            $object->status = self::STATUS_DRAFT;
292
        }
293
        if (property_exists($object, 'date_creation')) {
294
            $object->date_creation = dol_now();
295
        }
296
        if (property_exists($object, 'date_modification')) {
297
            $object->date_modification = null;
298
        }
299
        // ...
300
        // Clear extrafields that are unique
301
        if (is_array($object->array_options) && count($object->array_options) > 0) {
302
            $extrafields->fetch_name_optionals_label($this->table_element);
303
            foreach ($object->array_options as $key => $option) {
304
                $shortkey = preg_replace('/options_/', '', $key);
305
                if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) {
306
                    //var_dump($key);
307
                    //var_dump($clonedObj->array_options[$key]); exit;
308
                    unset($object->array_options[$key]);
309
                }
310
            }
311
        }
312
313
        // Create clone
314
        $object->context['createfromclone'] = 'createfromclone';
315
        $result = $object->createCommon($user);
316
        if ($result < 0) {
317
            $error++;
318
            $this->error = $object->error;
319
            $this->errors = $object->errors;
320
        }
321
322
        if (!$error) {
323
            // copy internal contacts
324
            if ($this->copy_linked_contact($object, 'internal') < 0) {
325
                $error++;
326
            }
327
        }
328
329
        if (!$error) {
330
            // copy external contacts if same company
331
            if (!empty($object->socid) && property_exists($this, 'fk_soc') && $this->fk_soc == $object->socid) {
332
                if ($this->copy_linked_contact($object, 'external') < 0) {
333
                    $error++;
334
                }
335
            }
336
        }
337
338
        unset($object->context['createfromclone']);
339
340
        // End
341
        if (!$error) {
342
            $this->db->commit();
343
            return $object;
344
        } else {
345
            $this->db->rollback();
346
            return -1;
347
        }
348
    }
349
350
    /**
351
     * Load object in memory from the database
352
     *
353
     * @param int    $id   Id object
354
     * @param string $ref  Ref
355
     * @return int         Return integer <0 if KO, 0 if not found, >0 if OK
356
     */
357
    public function fetch($id, $ref = null)
358
    {
359
        $result = $this->fetchCommon($id, $ref);
360
        if ($result > 0 && !empty($this->table_element_line)) {
361
            $this->fetchLines();
362
        }
363
        return $result;
364
    }
365
366
    /**
367
     * Load object lines in memory from the database
368
     *
369
     * @return int         Return integer <0 if KO, 0 if not found, >0 if OK
370
     */
371
    public function fetchLines()
372
    {
373
        $this->lines = array();
374
375
        $result = $this->fetchLinesCommon();
376
        return $result;
377
    }
378
379
380
    /**
381
     * Load list of objects in memory from the database.
382
     *
383
     * @param  string       $sortorder      Sort Order
384
     * @param  string       $sortfield      Sort field
385
     * @param  int          $limit          limit
386
     * @param  int          $offset         Offset
387
     * @param  string       $filter         Filter as an Universal Search string.
388
     *                                      Example: '((client:=:1) OR ((client:>=:2) AND (client:<=:3))) AND (client:!=:8) AND (nom:like:'a%')'
389
     * @param  string       $filtermode     No more used
390
     * @return array|int                    int <0 if KO, array of pages if OK
391
     */
392
    public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, $filter = '', $filtermode = 'AND')
393
    {
394
        dol_syslog(__METHOD__, LOG_DEBUG);
395
396
        $records = array();
397
398
        $sql = "SELECT ";
399
        $sql .= $this->getFieldList('t');
400
        $sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element . " as t";
401
        if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
402
            $sql .= " WHERE t.entity IN (" . getEntity($this->element) . ")";
403
        } else {
404
            $sql .= " WHERE 1 = 1";
405
        }
406
407
        // Manage filter
408
        $errormessage = '';
409
        $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
410
        if ($errormessage) {
411
            $this->errors[] = $errormessage;
412
            dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
413
            return -1;
414
        }
415
416
        if (!empty($sortfield)) {
417
            $sql .= $this->db->order($sortfield, $sortorder);
418
        }
419
        if (!empty($limit)) {
420
            $sql .= $this->db->plimit($limit, $offset);
421
        }
422
423
        $resql = $this->db->query($sql);
424
        if ($resql) {
425
            $num = $this->db->num_rows($resql);
426
            $i = 0;
427
            while ($i < ($limit ? min($limit, $num) : $num)) {
428
                $obj = $this->db->fetch_object($resql);
429
430
                $record = new self($this->db);
431
                $record->setVarsFromFetchObj($obj);
432
433
                $records[$record->id] = $record;
434
435
                $i++;
436
            }
437
            $this->db->free($resql);
438
439
            return $records;
440
        } else {
441
            $this->errors[] = 'Error ' . $this->db->lasterror();
442
            dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
443
444
            return -1;
445
        }
446
    }
447
448
    /**
449
     * Update object into database
450
     *
451
     * @param  User $user       User that modifies
452
     * @param  int $notrigger   false=launch triggers after, true=disable triggers
453
     * @return int              Return integer <0 if KO, >0 if OK
454
     */
455
    public function update(User $user, $notrigger = 0)
456
    {
457
        return $this->updateCommon($user, $notrigger);
458
    }
459
460
    /**
461
     * Delete object in database
462
     *
463
     * @param User  $user       User that deletes
464
     * @param int   $notrigger  0=launch triggers after, 1=disable triggers
465
     * @return int              Return integer <0 if KO, >0 if OK
466
     */
467
    public function delete(User $user, $notrigger = 0)
468
    {
469
        return $this->deleteCommon($user, $notrigger);
470
        //return $this->deleteCommon($user, $notrigger, 1);
471
    }
472
473
    /**
474
     *  Delete a line of object in database
475
     *
476
     *  @param  User    $user       User that delete
477
     *  @param  int     $idline     Id of line to delete
478
     *  @param  int     $notrigger  0=launch triggers after, 1=disable triggers
479
     *  @return int                 >0 if OK, <0 if KO
480
     */
481
    public function deleteLine(User $user, $idline, $notrigger = 0)
482
    {
483
        if ($this->status < 0) {
484
            $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
485
            return -2;
486
        }
487
488
        return $this->deleteLineCommon($user, $idline, $notrigger);
489
    }
490
491
492
    /**
493
     *  Validate object
494
     *
495
     *  @param      User    $user           User making status change
496
     *  @param      int     $notrigger      1=Does not execute triggers, 0= execute triggers
497
     *  @return     int                     Return integer <=0 if OK, 0=Nothing done, >0 if KO
498
     */
499
    public function validate($user, $notrigger = 0)
500
    {
501
        global $conf, $langs;
502
503
        require_once constant('DOL_DOCUMENT_ROOT') . '/core/lib/files.lib.php';
504
505
        $error = 0;
506
507
        // Protection
508
        if ($this->status == self::STATUS_VALIDATED) {
509
            dol_syslog(get_class($this) . "::validate action abandoned: already validated", LOG_WARNING);
510
            return 0;
511
        }
512
513
        $now = dol_now();
514
515
        $this->db->begin();
516
517
        // Define new ref
518
        if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
519
            $num = $this->getNextNumRef();
520
        } else {
521
            $num = $this->ref;
522
        }
523
        $this->newref = $num;
524
525
        if (!empty($num)) {
526
            // Validate
527
            $sql = "UPDATE " . MAIN_DB_PREFIX . $this->table_element;
528
            $sql .= " SET label = '" . $this->db->escape($num) . "',";
529
            $sql .= " status = " . self::STATUS_VALIDATED;
530
            if (!empty($this->fields['date_validation'])) {
531
                $sql .= ", date_validation = '" . $this->db->idate($now) . "'";
532
            }
533
            if (!empty($this->fields['fk_user_valid'])) {
534
                $sql .= ", fk_user_valid = " . ((int) $user->id);
535
            }
536
            $sql .= " WHERE rowid = " . ((int) $this->id);
537
538
            dol_syslog(get_class($this) . "::validate()", LOG_DEBUG);
539
            $resql = $this->db->query($sql);
540
            if (!$resql) {
541
                dol_print_error($this->db);
542
                $this->error = $this->db->lasterror();
543
                $error++;
544
            }
545
546
            if (!$error && !$notrigger) {
547
                // Call trigger
548
                $result = $this->call_trigger('AVAILABILITIES_VALIDATE', $user);
549
                if ($result < 0) {
550
                    $error++;
551
                }
552
                // End call triggers
553
            }
554
        }
555
556
        if (!$error) {
557
            $this->oldref = $this->ref;
558
559
            // Rename directory if dir was a temporary ref
560
            if (preg_match('/^[\(]?PROV/i', $this->ref)) {
561
                // Now we rename also files into index
562
                $sql = 'UPDATE ' . MAIN_DB_PREFIX . "ecm_files set filename = CONCAT('" . $this->db->escape($this->newref) . "', SUBSTR(filename, " . (strlen($this->ref) + 1) . ")), filepath = 'availabilities/" . $this->db->escape($this->newref) . "'";
563
                $sql .= " WHERE filename LIKE '" . $this->db->escape($this->ref) . "%' AND filepath = 'availabilities/" . $this->db->escape($this->ref) . "' and entity = " . $conf->entity;
564
                $resql = $this->db->query($sql);
565
                if (!$resql) {
566
                    $error++;
567
                    $this->error = $this->db->lasterror();
568
                }
569
                $sql = 'UPDATE ' . MAIN_DB_PREFIX . "ecm_files set filepath = 'availabilities/" . $this->db->escape($this->newref) . "'";
570
                $sql .= " WHERE filepath = 'availabilities/" . $this->db->escape($this->ref) . "' and entity = " . $conf->entity;
571
                $resql = $this->db->query($sql);
572
                if (!$resql) {
573
                    $error++;
574
                    $this->error = $this->db->lasterror();
575
                }
576
577
                // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
578
                $oldref = dol_sanitizeFileName($this->ref);
579
                $newref = dol_sanitizeFileName($num);
580
                $dirsource = $conf->bookcal->dir_output . '/availabilities/' . $oldref;
581
                $dirdest = $conf->bookcal->dir_output . '/availabilities/' . $newref;
582
                if (!$error && file_exists($dirsource)) {
583
                    dol_syslog(get_class($this) . "::validate() rename dir " . $dirsource . " into " . $dirdest);
584
585
                    if (@rename($dirsource, $dirdest)) {
586
                        dol_syslog("Rename ok");
587
                        // Rename docs starting with $oldref with $newref
588
                        $listoffiles = dol_dir_list($conf->bookcal->dir_output . '/availabilities/' . $newref, 'files', 1, '^' . preg_quote($oldref, '/'));
589
                        foreach ($listoffiles as $fileentry) {
590
                            $dirsource = $fileentry['name'];
591
                            $dirdest = preg_replace('/^' . preg_quote($oldref, '/') . '/', $newref, $dirsource);
592
                            $dirsource = $fileentry['path'] . '/' . $dirsource;
593
                            $dirdest = $fileentry['path'] . '/' . $dirdest;
594
                            @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

594
                            /** @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...
595
                        }
596
                    }
597
                }
598
            }
599
        }
600
601
        // Set new ref and current status
602
        if (!$error) {
603
            $this->ref = $num;
604
            $this->status = self::STATUS_VALIDATED;
605
        }
606
607
        if (!$error) {
608
            $this->db->commit();
609
            return 1;
610
        } else {
611
            $this->db->rollback();
612
            return -1;
613
        }
614
    }
615
616
617
    /**
618
     *  Set draft status
619
     *
620
     *  @param  User    $user           Object user that modify
621
     *  @param  int     $notrigger      1=Does not execute triggers, 0=Execute triggers
622
     *  @return int                     Return integer <0 if KO, >0 if OK
623
     */
624
    public function setDraft($user, $notrigger = 0)
625
    {
626
        // Protection
627
        if ($this->status <= self::STATUS_DRAFT) {
628
            return 0;
629
        }
630
631
        return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'AVAILABILITIES_UNVALIDATE');
632
    }
633
634
    /**
635
     *  Set cancel status
636
     *
637
     *  @param  User    $user           Object user that modify
638
     *  @param  int     $notrigger      1=Does not execute triggers, 0=Execute triggers
639
     *  @return int                     Return integer <0 if KO, 0=Nothing done, >0 if OK
640
     */
641
    public function cancel($user, $notrigger = 0)
642
    {
643
        // Protection
644
        if ($this->status != self::STATUS_VALIDATED) {
645
            return 0;
646
        }
647
648
        return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'AVAILABILITIES_CANCEL');
649
    }
650
651
    /**
652
     *  Set back to validated status
653
     *
654
     *  @param  User    $user           Object user that modify
655
     *  @param  int     $notrigger      1=Does not execute triggers, 0=Execute triggers
656
     *  @return int                     Return integer <0 if KO, 0=Nothing done, >0 if OK
657
     */
658
    public function reopen($user, $notrigger = 0)
659
    {
660
        // Protection
661
        if ($this->status != self::STATUS_CANCELED) {
662
            return 0;
663
        }
664
665
        return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'AVAILABILITIES_REOPEN');
666
    }
667
668
    /**
669
     *  Return a link to the object card (with optionally the picto)
670
     *
671
     *  @param  int     $withpicto                  Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
672
     *  @param  string  $option                     On what the link point to ('nolink', ...)
673
     *  @param  int     $notooltip                  1=Disable tooltip
674
     *  @param  string  $morecss                    Add more css on link
675
     *  @param  int     $save_lastsearch_value      -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
676
     *  @return string                              String with URL
677
     */
678
    public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
679
    {
680
        global $conf, $langs, $hookmanager;
681
682
        if (!empty($conf->dol_no_mouse_hover)) {
683
            $notooltip = 1; // Force disable tooltips
684
        }
685
686
        $result = '';
687
688
        $label = img_picto('', $this->picto) . ' <u>' . $langs->trans("Availabilities") . '</u>';
689
        if (isset($this->status)) {
690
            $label .= ' ' . $this->getLibStatut(5);
691
        }
692
        $label .= '<br>';
693
        $label .= '<b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;
694
695
        $url = dol_buildpath('/bookcal/availabilities_card.php', 1) . '?id=' . $this->id;
696
697
        if ($option != 'nolink') {
698
            // Add param to save lastsearch_values or not
699
            $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
700
            if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
701
                $add_save_lastsearch_values = 1;
702
            }
703
            if ($url && $add_save_lastsearch_values) {
704
                $url .= '&save_lastsearch_values=1';
705
            }
706
        }
707
708
        $linkclose = '';
709
        if (empty($notooltip)) {
710
            if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
711
                $label = $langs->trans("ShowAvailabilities");
712
                $linkclose .= ' alt="' . dol_escape_htmltag($label, 1) . '"';
713
            }
714
            $linkclose .= ' title="' . dol_escape_htmltag($label, 1) . '"';
715
            $linkclose .= ' class="classfortooltip' . ($morecss ? ' ' . $morecss : '') . '"';
716
        } else {
717
            $linkclose = ($morecss ? ' class="' . $morecss . '"' : '');
718
        }
719
720
        if ($option == 'nolink' || empty($url)) {
721
            $linkstart = '<span';
722
        } else {
723
            $linkstart = '<a href="' . $url . '"';
724
        }
725
        $linkstart .= $linkclose . '>';
726
        if ($option == 'nolink' || empty($url)) {
727
            $linkend = '</span>';
728
        } else {
729
            $linkend = '</a>';
730
        }
731
732
        $result .= $linkstart;
733
734
        if (empty($this->showphoto_on_popup)) {
735
            if ($withpicto) {
736
                $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);
737
            }
738
        } else {
739
            if ($withpicto) {
740
                require_once constant('DOL_DOCUMENT_ROOT') . '/core/lib/files.lib.php';
741
742
                list($class, $module) = explode('@', $this->picto);
743
                $upload_dir = $conf->$module->multidir_output[$conf->entity] . "/$class/" . dol_sanitizeFileName($this->ref);
744
                $filearray = dol_dir_list($upload_dir, "files");
745
                $filename = $filearray[0]['name'];
746
                if (!empty($filename)) {
747
                    $pospoint = strpos($filearray[0]['name'], '.');
748
749
                    $pathtophoto = $class . '/' . $this->ref . '/thumbs/' . substr($filename, 0, $pospoint) . '_mini' . substr($filename, $pospoint);
750
                    if (!getDolGlobalString(strtoupper($module . '_' . $class) . '_FORMATLISTPHOTOSASUSERS')) {
751
                        $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>';
752
                    } else {
753
                        $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>';
754
                    }
755
756
                    $result .= '</div>';
757
                } else {
758
                    $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);
759
                }
760
            }
761
        }
762
763
        if ($withpicto != 2) {
764
            $result .= $this->ref;
765
        }
766
767
        $result .= $linkend;
768
        //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
769
770
        global $action, $hookmanager;
771
        $hookmanager->initHooks(array('availabilitiesdao'));
772
        $parameters = array('id' => $this->id, 'getnomurl' => &$result);
773
        $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
774
        if ($reshook > 0) {
775
            $result = $hookmanager->resPrint;
776
        } else {
777
            $result .= $hookmanager->resPrint;
778
        }
779
780
        return $result;
781
    }
782
783
    /**
784
     *  Return a thumb for kanban views
785
     *
786
     *  @param      string      $option                 Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
787
     *  @param      array       $arraydata              Array of data
788
     *  @return     string                              HTML Code for Kanban thumb.
789
     */
790
    public function getKanbanView($option = '', $arraydata = null)
791
    {
792
        global $conf, $langs;
793
794
        $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
795
796
        $return = '<div class="box-flex-item box-flex-grow-zero">';
797
        $return .= '<div class="info-box info-box-sm">';
798
        $return .= '<span class="info-box-icon bg-infobox-action">';
799
        $return .= img_picto('', $this->picto);
800
        $return .= '</span>';
801
        $return .= '<div class="info-box-content">';
802
        $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">' . (method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref) . '</span>';
803
        if ($selected >= 0) {
804
            $return .= '<input id="cb' . $this->id . '" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="' . $this->id . '"' . ($selected ? ' checked="checked"' : '') . '>';
805
        }
806
        if (property_exists($this, 'label')) {
807
            $return .= ' <div class="inline-block opacitymedium valignmiddle tdoverflowmax100">' . $this->label . '</div>';
808
        }
809
        if (property_exists($this, 'amount')) {
810
            $return .= '<br>';
811
            $return .= '<span class="info-box-label amount">' . price($this->amount, 0, $langs, 1, -1, -1, $conf->currency) . '</span>';
0 ignored issues
show
Bug Best Practice introduced by
The property amount does not exist on Dolibarr\Code\BookCal\Classes\Availabilities. Since you implemented __get, consider adding a @property annotation.
Loading history...
812
        }
813
        if (method_exists($this, 'getLibStatut')) {
814
            $return .= '<br><div class="info-box-status">' . $this->getLibStatut(3) . '</div>';
815
        }
816
        $return .= '</div>';
817
        $return .= '</div>';
818
        $return .= '</div>';
819
820
        return $return;
821
    }
822
823
    /**
824
     *  Return the label of the status
825
     *
826
     *  @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
827
     *  @return string                 Label of status
828
     */
829
    public function getLabelStatus($mode = 0)
830
    {
831
        return $this->LibStatut($this->status, $mode);
832
    }
833
834
    /**
835
     *  Return the label of the status
836
     *
837
     *  @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
838
     *  @return string                 Label of status
839
     */
840
    public function getLibStatut($mode = 0)
841
    {
842
        return $this->LibStatut($this->status, $mode);
843
    }
844
845
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
846
    /**
847
     *  Return the status
848
     *
849
     *  @param  int     $status        Id status
850
     *  @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
851
     *  @return string                 Label of status
852
     */
853
    public function LibStatut($status, $mode = 0)
854
    {
855
		// phpcs:enable
856
        if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
857
            global $langs;
858
            //$langs->load("agenda");
859
            $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
860
            $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
861
            $this->labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
862
            $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
863
            $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
864
            $this->labelStatusShort[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
865
        }
866
867
        $statusType = 'status' . $status;
868
        if ($status == self::STATUS_VALIDATED) {
869
            $statusType = 'status4';
870
        }
871
        if ($status == self::STATUS_CANCELED) {
872
            $statusType = 'status6';
873
        }
874
875
        return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
876
    }
877
878
    /**
879
     *  Load the info information in the object
880
     *
881
     *  @param  int     $id       Id of object
882
     *  @return void
883
     */
884
    public function info($id)
885
    {
886
        $sql = "SELECT rowid,";
887
        $sql .= " date_creation as datec, tms as datem,";
888
        $sql .= " fk_user_creat, fk_user_modif";
889
        $sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element . " as t";
890
        $sql .= " WHERE t.rowid = " . ((int) $id);
891
892
        $result = $this->db->query($sql);
893
        if ($result) {
894
            if ($this->db->num_rows($result)) {
895
                $obj = $this->db->fetch_object($result);
896
897
                $this->id = $obj->rowid;
898
899
                $this->user_creation_id = $obj->fk_user_creat;
900
                $this->user_modification_id = $obj->fk_user_modif;
901
                $this->date_creation     = $this->db->jdate($obj->datec);
902
                $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
903
            }
904
905
            $this->db->free($result);
906
        } else {
907
            dol_print_error($this->db);
908
        }
909
    }
910
911
    /**
912
     * Initialise object with example values
913
     * Id must be 0 if object instance is a specimen
914
     *
915
     * @return int
916
     */
917
    public function initAsSpecimen()
918
    {
919
        // Set here init that are not commonf fields
920
        // $this->property1 = ...
921
        // $this->property2 = ...
922
923
        return $this->initAsSpecimenCommon();
924
    }
925
926
    /**
927
     *  Create an array of lines
928
     *
929
     *  @return array|int       array of lines if OK, <0 if KO
930
     */
931
    public function getLinesArray()
932
    {
933
        $this->lines = array();
934
935
        $objectline = new AvailabilitiesLine($this->db);
936
        $result = $objectline->fetchAll('ASC', 'position', 0, 0, '(fk_availabilities:=:' . ((int) $this->id) . ')');
937
938
        if (is_numeric($result)) {
939
            $this->error = $objectline->error;
940
            $this->errors = $objectline->errors;
941
            return $result;
942
        } else {
943
            $this->lines = $result;
944
            return $this->lines;
945
        }
946
    }
947
948
    /**
949
     *  Returns the reference to the following non used object depending on the active numbering module.
950
     *
951
     *  @return string              Object free reference
952
     */
953
    public function getNextNumRef()
954
    {
955
        global $langs, $conf;
956
        $langs->load("agenda");
957
958
        if (!getDolGlobalString('BOOKCAL_AVAILABILITIES_ADDON')) {
959
            $conf->global->BOOKCAL_AVAILABILITIES_ADDON = 'mod_availabilities_standard';
960
        }
961
962
        if (getDolGlobalString('BOOKCAL_AVAILABILITIES_ADDON')) {
963
            $mybool = false;
964
965
            $file = getDolGlobalString('BOOKCAL_AVAILABILITIES_ADDON') . ".php";
966
            $classname = getDolGlobalString('BOOKCAL_AVAILABILITIES_ADDON');
967
968
            // Include file with class
969
            $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
970
            foreach ($dirmodels as $reldir) {
971
                $dir = dol_buildpath($reldir . "core/modules/bookcal/");
972
973
                // Load file with numbering class (if found)
974
                $mybool = ((bool) @include_once $dir . $file) || $mybool;
975
            }
976
977
            if ($mybool === false) {
978
                dol_print_error(null, "Failed to include file " . $file);
979
                return '';
980
            }
981
982
            if (class_exists($classname)) {
983
                $obj = new $classname();
984
                $numref = $obj->getNextValue($this);
985
986
                if ($numref != '' && $numref != '-1') {
987
                    return $numref;
988
                } else {
989
                    $this->error = $obj->error;
990
                    //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
991
                    return "";
992
                }
993
            } else {
994
                print $langs->trans("Error") . " " . $langs->trans("ClassNotFound") . ' ' . $classname;
995
                return "";
996
            }
997
        } else {
998
            print $langs->trans("ErrorNumberingModuleNotSetup", $this->element);
999
            return "";
1000
        }
1001
    }
1002
1003
    /**
1004
     *  Create a document onto disk according to template module.
1005
     *
1006
     *  @param      string      $modele         Force template to use ('' to not force)
1007
     *  @param      Translate   $outputlangs    object lang a utiliser pour traduction
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\BookCal\Classes\Translate was not found. Did you mean Translate? If so, make sure to prefix the type with \.
Loading history...
1008
     *  @param      int         $hidedetails    Hide details of lines
1009
     *  @param      int         $hidedesc       Hide description
1010
     *  @param      int         $hideref        Hide ref
1011
     *  @param      null|array  $moreparams     Array to provide more information
1012
     *  @return     int                         0 if KO, 1 if OK
1013
     */
1014
    public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
1015
    {
1016
        global $conf, $langs;
1017
1018
        $result = 0;
1019
        $includedocgeneration = 0;
1020
1021
        $langs->load("agenda");
1022
1023
        if (!dol_strlen($modele)) {
1024
            $modele = 'standard_availabilities';
1025
1026
            if (!empty($this->model_pdf)) {
1027
                $modele = $this->model_pdf;
1028
            } elseif (getDolGlobalString('AVAILABILITIES_ADDON_PDF')) {
1029
                $modele = getDolGlobalString('AVAILABILITIES_ADDON_PDF');
1030
            }
1031
        }
1032
1033
        $modelpath = "core/modules/bookcal/doc/";
1034
1035
        if ($includedocgeneration && !empty($modele)) {
1036
            $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
1037
        }
1038
1039
        return $result;
1040
    }
1041
1042
    /**
1043
     * Action executed by scheduler
1044
     * CAN BE A CRON TASK. In such a case, parameters come from the schedule job setup field 'Parameters'
1045
     * Use public function doScheduledJob($param1, $param2, ...) to get parameters
1046
     *
1047
     * @return  int         0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
1048
     */
1049
    public function doScheduledJob()
1050
    {
1051
        global $conf, $langs;
1052
1053
        //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
1054
1055
        $error = 0;
1056
        $this->output = '';
1057
        $this->error = '';
1058
1059
        dol_syslog(__METHOD__, LOG_DEBUG);
1060
1061
        $now = dol_now();
1062
1063
        $this->db->begin();
1064
1065
        // ...
1066
1067
        $this->db->commit();
1068
1069
        return $error;
1070
    }
1071
}
1072
1073
1074
use Dolibarr\Core\Base\CommonObjectLine;
1075
1076
/**
1077
 * Class AvailabilitiesLine. You can also remove this and generate a CRUD class for lines objects.
1078
 */
1079
class AvailabilitiesLine extends CommonObjectLine
1080
{
1081
    // To complete with content of an object AvailabilitiesLine
1082
    // We should have a field rowid, fk_availabilities and position
1083
1084
    /**
1085
     * Constructor
1086
     *
1087
     * @param DoliDB $db Database handler
1088
     */
1089
    public function __construct(DoliDB $db)
1090
    {
1091
        $this->db = $db;
1092
        $this->isextrafieldmanaged = 0;
1093
    }
1094
}
1095