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

RecruitmentJobPosition::createFromClone()   F

Complexity

Conditions 22
Paths 13824

Size

Total Lines 90
Code Lines 47

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 22
eloc 47
nc 13824
nop 2
dl 0
loc 90
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) 2020       Laurent Destailleur         <[email protected]>
4
/* Copyright (C) 2022       Alexandre Spangaro          <[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\Recruitement\Classes;
24
25
use Dolibarr\Core\Base\CommonObject;
26
27
/**
28
 * \file        htdocs/recruitment/class/recruitmentjobposition.class.php
29
 * \ingroup     recruitment
30
 * \brief       This file is a CRUD class file for RecruitmentJobPosition (Create/Read/Update/Delete)
31
 */
32
33
// Put here all includes required by your class file
34
//use Dolibarr\Code\Societe\Classes\Societe;
35
//require_once constant('DOL_DOCUMENT_ROOT') . '/product/class/product.class.php';
36
37
/**
38
 * Class for RecruitmentJobPosition
39
 */
40
class RecruitmentJobPosition extends CommonObject
41
{
42
    /**
43
     * @var string ID of module.
44
     */
45
    public $module = 'recruitment';
46
47
    /**
48
     * @var string ID to identify managed object
49
     */
50
    public $element = 'recruitmentjobposition';
51
52
    /**
53
     * @var string Name of table without prefix where object is stored
54
     */
55
    public $table_element = 'recruitment_recruitmentjobposition';
56
57
    /**
58
     * @var string String with name of icon for recruitmentjobposition. Must be the part after the 'object_' into object_recruitmentjobposition.png
59
     */
60
    public $picto = 'recruitmentjobposition';
61
62
    /**
63
     * Draft status
64
     */
65
    const STATUS_DRAFT = 0;
66
67
    /**
68
     * Validated
69
     */
70
    const STATUS_VALIDATED = 1;
71
72
    /**
73
     * Recruited
74
     */
75
    const STATUS_RECRUITED = 3;
76
77
    /**
78
     * Canceled
79
     */
80
    const STATUS_CANCELED = 9;
81
82
83
    /**
84
     *  'type' if the field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password')
85
     *         Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
86
     *  'label' the translation key.
87
     *  'enabled' is a condition when the field must be managed (Example: 1 or 'getDolGlobalString("MY_SETUP_PARAM")'
88
     *  'position' is the sort order of field.
89
     *  'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
90
     *  '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)
91
     *  'noteditable' says if field is not editable (1 or 0)
92
     *  '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.
93
     *  'index' if we want an index in database.
94
     *  'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommended to name the field fk_...).
95
     *  'searchall' is 1 if we want to search in this field when making a search from the quick search button.
96
     *  '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).
97
     *  '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'
98
     *  'help' is a string visible as a tooltip on field
99
     *  'showoncombobox' if value of the field must be visible into the label of the combobox that list record
100
     *  '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.
101
     *  'arrayofkeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel")
102
     *  'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1.
103
     *  'comment' is not used. You can store here any text of your choice. It is not used by application.
104
     *
105
     *  Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
106
     */
107
108
    // BEGIN MODULEBUILDER PROPERTIES
109
    /**
110
     * @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...
111
     */
112
    public $fields = array(
113
        'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'position' => 1, 'notnull' => 1, 'visible' => 0, 'noteditable' => 1, 'index' => 1, 'comment' => "Id"),
114
        'entity' => array('type' => 'integer', 'label' => 'Entity', 'enabled' => 1, 'visible' => 0, 'position' => 5, 'notnull' => 1, 'default' => '1', 'index' => 1),
115
        'ref' => array('type' => 'varchar(128)', 'label' => 'Ref', 'enabled' => 1, 'position' => 10, 'notnull' => 1, 'visible' => 4, 'noteditable' => 1, 'default' => '(PROV)', 'index' => 1, 'searchall' => 1, 'showoncombobox' => 1, 'comment' => "Reference of object", 'css' => 'nowraponall'),
116
        'label' => array('type' => 'varchar(255)', 'label' => 'JobLabel', 'enabled' => 1, 'position' => 30, 'notnull' => 1, 'visible' => 1, 'searchall' => 1, 'css' => 'minwidth500', 'csslist' => 'tdoverflowmax300', 'showoncombobox' => '2', 'autofocusoncreate' => 1),
117
        'qty' => array('type' => 'integer', 'label' => 'NbOfEmployeesExpected', 'enabled' => 1, 'position' => 45, 'notnull' => 1, 'visible' => 1, 'default' => '1', 'isameasure' => 1, 'css' => 'maxwidth75imp'),
118
        'fk_project' => array('type' => 'integer:Project:projet/class/project.class.php:1', 'label' => 'Project', 'enabled' => '$conf->project->enabled', 'position' => 52, 'notnull' => -1, 'visible' => -1, 'index' => 1, 'css' => 'maxwidth500', 'picto' => 'project'),
119
        'fk_user_recruiter' => array('type' => 'integer:User:user/class/user.class.php:1:(statut:=:1)', 'label' => 'ResponsibleOfRecruitement', 'enabled' => 1, 'position' => 54, 'notnull' => 1, 'visible' => 1, 'foreignkey' => 'user.rowid', 'css' => 'maxwidth500', 'csslist' => 'tdoverflowmax150', 'picto' => 'user'),
120
        'email_recruiter' => array('type' => 'varchar(255)', 'label' => 'EmailRecruiter', 'enabled' => 1, 'position' => 54, 'notnull' => 0, 'visible' => -1, 'help' => 'ToUseAGenericEmail', 'picto' => 'email'),
121
        'fk_user_supervisor' => array('type' => 'integer:User:user/class/user.class.php:1:(statut:=:1)', 'label' => 'FutureManager', 'enabled' => 1, 'position' => 55, 'notnull' => 0, 'visible' => -1, 'foreignkey' => 'user.rowid', 'css' => 'maxwidth500', 'csslist' => 'tdoverflowmax150', 'picto' => 'user'),
122
        'fk_establishment' => array('type' => 'integer:Establishment:hrm/class/establishment.class.php', 'label' => 'Establishment', 'enabled' => '$conf->hrm->enabled', 'position' => 56, 'notnull' => 0, 'visible' => -1, 'foreignkey' => 'establishment.rowid',),
123
        'fk_soc' => array('type' => 'integer:Societe:societe/class/societe.class.php:1:((status:=:1) AND (entity:IN:__SHARED_ENTITIES__))', 'label' => 'WorkPlace', 'enabled' => 'isModEnabled("societe")', 'position' => 57, 'notnull' => -1, 'visible' => -1, 'css' => 'maxwidth500', 'index' => 1, 'help' => "IfJobIsLocatedAtAPartner", 'picto' => 'company'),
124
        'date_planned' => array('type' => 'date', 'label' => 'DateExpected', 'enabled' => 1, 'position' => 60, 'notnull' => 0, 'visible' => 1,),
125
        'remuneration_suggested' => array('type' => 'varchar(255)', 'label' => 'Remuneration', 'enabled' => 1, 'position' => 62, 'notnull' => 0, 'visible' => 1,),
126
        'description' => array('type' => 'html', 'label' => 'Description', 'enabled' => 1, 'position' => 65, 'notnull' => 0, 'visible' => 3,),
127
        'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'position' => 101, 'notnull' => 0, 'visible' => 0,),
128
        'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'position' => 102, 'notnull' => 0, 'visible' => 0,),
129
        'date_creation' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'position' => 500, 'notnull' => 1, 'visible' => -4,),
130
        'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'position' => 501, 'notnull' => 0, 'visible' => -2,),
131
        'fk_user_creat' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'enabled' => 1, 'position' => 510, 'notnull' => 1, 'visible' => -2, 'foreignkey' => 'user.rowid',),
132
        'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => 1, 'position' => 511, 'notnull' => -1, 'visible' => -2,),
133
        'last_main_doc' => array('type' => 'varchar(255)', 'label' => 'LastMainDoc', 'enabled' => 1, 'position' => 900, 'notnull' => 0, 'visible' => 0,),
134
        'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'position' => 1000, 'notnull' => -1, 'visible' => -2,),
135
        'model_pdf' => array('type' => 'varchar(255)', 'label' => 'Model pdf', 'enabled' => 1, 'position' => 1010, 'notnull' => -1, 'visible' => 0,),
136
        'status' => array('type' => 'smallint', 'label' => 'Status', 'enabled' => 1, 'position' => 1000, 'notnull' => 1, 'visible' => 5, 'default' => '0', 'index' => 1, 'arrayofkeyval' => array('0' => 'Draft', '1' => 'Validated', '3' => 'Recruited', '9' => 'Canceled'),),
137
    );
138
    public $rowid;
139
140
    /**
141
     * @var string ref
142
     */
143
    public $ref;
144
    public $entity;
145
146
    /**
147
     * @var string label
148
     */
149
    public $label;
150
151
    /**
152
     * @var float Quantity
153
     */
154
    public $qty;
155
156
    /**
157
     * @var int ID thirdparty
158
     */
159
    public $fk_soc;
160
161
    /**
162
     * @var int ID project
163
     */
164
    public $fk_project;
165
    public $fk_user_recruiter;
166
167
    /**
168
     * @var string recruiter email
169
     */
170
    public $email_recruiter;
171
172
    /**
173
     * @var string suggested remuneration
174
     */
175
    public $remuneration_suggested;
176
177
    public $fk_user_supervisor;
178
    public $fk_establishment;
179
    public $date_planned;
180
    public $description;
181
    public $note_public;
182
    public $note_private;
183
    public $date_creation;
184
    public $fk_user_creat;
185
    public $fk_user_modif;
186
    public $last_main_doc;
187
    public $import_key;
188
    public $model_pdf;
189
    public $status;
190
    // END MODULEBUILDER PROPERTIES
191
192
193
    /**
194
     * Constructor
195
     *
196
     * @param DoliDB $db Database handler
197
     */
198
    public function __construct(DoliDB $db)
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\Recruitement\Classes\DoliDB was not found. Did you mean DoliDB? If so, make sure to prefix the type with \.
Loading history...
199
    {
200
        global $conf, $langs;
201
202
        $this->db = $db;
203
204
        $this->ismultientitymanaged = 1;
205
        $this->isextrafieldmanaged = 1;
206
207
        if (!getDolGlobalString('MAIN_SHOW_TECHNICAL_ID') && isset($this->fields['rowid'])) {
208
            $this->fields['rowid']['visible'] = 0;
209
        }
210
        if (!isModEnabled('multicompany') && isset($this->fields['entity'])) {
211
            $this->fields['entity']['enabled'] = 0;
212
        }
213
214
        // Example to show how to set values of fields definition dynamically
215
        /*if ($user->hasRight('recruitment', 'recruitmentjobposition', 'read')) {
216
            $this->fields['myfield']['visible'] = 1;
217
            $this->fields['myfield']['noteditable'] = 0;
218
        }*/
219
220
        // Unset fields that are disabled
221
        foreach ($this->fields as $key => $val) {
222
            if (isset($val['enabled']) && empty($val['enabled'])) {
223
                unset($this->fields[$key]);
224
            }
225
        }
226
227
        // Translate some data of arrayofkeyval
228
        if (is_object($langs)) {
229
            foreach ($this->fields as $key => $val) {
230
                if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
231
                    foreach ($val['arrayofkeyval'] as $key2 => $val2) {
232
                        $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
233
                    }
234
                }
235
            }
236
        }
237
    }
238
239
    /**
240
     * Create object into database
241
     *
242
     * @param  User $user      User that creates
243
     * @param  int  $notrigger 0=launch triggers after, 1=disable triggers
244
     * @return int             Return integer <0 if KO, Id of created object if OK
245
     */
246
    public function create(User $user, $notrigger = 0)
247
    {
248
        return $this->createCommon($user, $notrigger);
249
    }
250
251
    /**
252
     * Clone an object into another one
253
     *
254
     * @param   User    $user       User that creates
255
     * @param   int     $fromid     Id of object to clone
256
     * @return  mixed               New object created, <0 if KO
257
     */
258
    public function createFromClone(User $user, $fromid)
259
    {
260
        global $langs, $extrafields;
261
        $error = 0;
262
263
        dol_syslog(__METHOD__, LOG_DEBUG);
264
265
        $object = new self($this->db);
266
267
        $this->db->begin();
268
269
        // Load source object
270
        $result = $object->fetchCommon($fromid);
271
        if ($result > 0 && !empty($object->table_element_line)) {
272
            $object->fetchLines();
273
        }
274
275
        // get lines so they will be clone
276
        //foreach($this->lines as $line)
277
        //  $line->fetch_optionals();
278
279
        // Reset some properties
280
        unset($object->id);
281
        unset($object->fk_user_creat);
282
        unset($object->import_key);
283
284
        // Clear fields
285
        if (property_exists($object, 'ref')) {
286
            $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_" . $object->ref : $this->fields['ref']['default'];
287
        }
288
        if (property_exists($object, 'label')) {
289
            $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf") . " " . $object->label : $this->fields['label']['default'];
290
        }
291
        if (property_exists($object, 'status')) {
292
            $object->status = self::STATUS_DRAFT;
293
        }
294
        if (property_exists($object, 'date_creation')) {
295
            $object->date_creation = dol_now();
296
        }
297
        if (property_exists($object, 'date_modification')) {
298
            $object->date_modification = null;
299
        }
300
        // ...
301
        // Clear extrafields that are unique
302
        if (is_array($object->array_options) && count($object->array_options) > 0) {
303
            $extrafields->fetch_name_optionals_label($this->table_element);
304
            foreach ($object->array_options as $key => $option) {
305
                $shortkey = preg_replace('/options_/', '', $key);
306
                if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey])) {
307
                    //var_dump($key);
308
                    //var_dump($clonedObj->array_options[$key]); exit;
309
                    unset($object->array_options[$key]);
310
                }
311
            }
312
        }
313
314
        // Create clone
315
        $object->context['createfromclone'] = 'createfromclone';
316
        $result = $object->createCommon($user);
317
        if ($result < 0) {
318
            $error++;
319
            $this->error = $object->error;
320
            $this->errors = $object->errors;
321
        }
322
323
        if (!$error) {
324
            // copy internal contacts
325
            if ($this->copy_linked_contact($object, 'internal') < 0) {
326
                $error++;
327
            }
328
        }
329
330
        if (!$error) {
331
            // copy external contacts if same company
332
            if (property_exists($this, 'socid') && $this->socid == $object->socid) {
333
                if ($this->copy_linked_contact($object, 'external') < 0) {
334
                    $error++;
335
                }
336
            }
337
        }
338
339
        unset($object->context['createfromclone']);
340
341
        // End
342
        if (!$error) {
343
            $this->db->commit();
344
            return $object;
345
        } else {
346
            $this->db->rollback();
347
            return -1;
348
        }
349
    }
350
351
    /**
352
     * Load object in memory from the database
353
     *
354
     * @param int    $id   Id object
355
     * @param string $ref  Ref
356
     * @return int         Return integer <0 if KO, 0 if not found, >0 if OK
357
     */
358
    public function fetch($id, $ref = null)
359
    {
360
        $result = $this->fetchCommon($id, $ref);
361
        if ($result > 0 && !empty($this->table_element_line)) {
362
            $this->fetchLines();
363
        }
364
        return $result;
365
    }
366
367
    /**
368
     * Load object lines in memory from the database
369
     *
370
     * @return int         Return integer <0 if KO, 0 if not found, >0 if OK
371
     */
372
    public function fetchLines()
373
    {
374
        $this->lines = array();
375
376
        $result = $this->fetchLinesCommon();
377
        return $result;
378
    }
379
380
381
    /**
382
     * Load list of objects in memory from the database.
383
     *
384
     * @param  string       $sortorder      Sort Order
385
     * @param  string       $sortfield      Sort field
386
     * @param  int          $limit          limit
387
     * @param  int          $offset         Offset
388
     * @param  string       $filter         Filter as an Universal Search string.
389
     *                                      Example: '((client:=:1) OR ((client:>=:2) AND (client:<=:3))) AND (client:!=:8) AND (nom:like:'a%')'
390
     * @param  string       $filtermode     No more used
391
     * @return array|int                    int <0 if KO, array of pages if OK
392
     */
393
    public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, $filter = '', $filtermode = 'AND')
394
    {
395
        dol_syslog(__METHOD__, LOG_DEBUG);
396
397
        $records = array();
398
399
        $sql = 'SELECT ';
400
        $sql .= $this->getFieldList();
401
        $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t';
402
        if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
403
            $sql .= ' WHERE t.entity IN (' . getEntity($this->element) . ')';
404
        } else {
405
            $sql .= ' WHERE 1 = 1';
406
        }
407
408
        // Manage filter
409
        $errormessage = '';
410
        $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
411
        if ($errormessage) {
412
            $this->errors[] = $errormessage;
413
            dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
414
            return -1;
415
        }
416
417
        if (!empty($sortfield)) {
418
            $sql .= $this->db->order($sortfield, $sortorder);
419
        }
420
        if (!empty($limit)) {
421
            $sql .= $this->db->plimit($limit, $offset);
422
        }
423
424
        $resql = $this->db->query($sql);
425
        if ($resql) {
426
            $num = $this->db->num_rows($resql);
427
            $i = 0;
428
            while ($i < ($limit ? min($limit, $num) : $num)) {
429
                $obj = $this->db->fetch_object($resql);
430
431
                $record = new self($this->db);
432
                $record->setVarsFromFetchObj($obj);
433
434
                $records[$record->id] = $record;
435
436
                $i++;
437
            }
438
            $this->db->free($resql);
439
440
            return $records;
441
        } else {
442
            $this->errors[] = 'Error ' . $this->db->lasterror();
443
            dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
444
445
            return -1;
446
        }
447
    }
448
449
    /**
450
     * Update object into database
451
     *
452
     * @param  User $user      User that modifies
453
     * @param  int  $notrigger 0=launch triggers after, 1=disable triggers
454
     * @return int             Return integer <0 if KO, >0 if OK
455
     */
456
    public function update(User $user, $notrigger = 0)
457
    {
458
        return $this->updateCommon($user, $notrigger);
459
    }
460
461
    /**
462
     * Delete object in database
463
     *
464
     * @param User  $user       User that deletes
465
     * @param int   $notrigger  0=launch triggers after, 1=disable triggers
466
     * @return int              Return integer <0 if KO, >0 if OK
467
     */
468
    public function delete(User $user, $notrigger = 0)
469
    {
470
        return $this->deleteCommon($user, $notrigger);
471
        //return $this->deleteCommon($user, $notrigger, 1);
472
    }
473
474
    /**
475
     *  Delete a line of object in database
476
     *
477
     *  @param  User    $user       User that delete
478
     *  @param  int     $idline     Id of line to delete
479
     *  @param  int     $notrigger  0=launch triggers after, 1=disable triggers
480
     *  @return int                 Return >0 if OK, <0 if KO
481
     */
482
    public function deleteLine(User $user, $idline, $notrigger = 0)
483
    {
484
        if ($this->status < 0) {
485
            $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
486
            return -2;
487
        }
488
489
        return $this->deleteLineCommon($user, $idline, $notrigger);
490
    }
491
492
493
    /**
494
     *  Validate object
495
     *
496
     *  @param      User    $user           User making status change
497
     *  @param      int     $notrigger      1=Does not execute triggers, 0= execute triggers
498
     *  @return     int                     Return integer <=0 if OK, 0=Nothing done, >0 if KO
499
     */
500
    public function validate($user, $notrigger = 0)
501
    {
502
        global $conf;
503
504
        require_once constant('DOL_DOCUMENT_ROOT') . '/core/lib/files.lib.php';
505
506
        $error = 0;
507
508
        // Protection
509
        if ($this->status == self::STATUS_VALIDATED) {
510
            dol_syslog(get_class($this) . "::validate action abandoned: already validated", LOG_WARNING);
511
            return 0;
512
        }
513
514
        /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->recruitmentjobposition->create))
515
         || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->recruitmentjobposition->recruitmentjobposition_advance->validate))))
516
         {
517
         $this->error='NotEnoughPermissions';
518
         dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
519
         return -1;
520
         }*/
521
522
        $now = dol_now();
523
524
        $this->db->begin();
525
526
        // Define new ref
527
        if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
528
            $num = $this->getNextNumRef();
529
        } else {
530
            $num = $this->ref;
531
        }
532
        $this->newref = $num;
533
534
        if (!empty($num)) {
535
            // Validate
536
            $sql = "UPDATE " . MAIN_DB_PREFIX . $this->table_element;
537
            $sql .= " SET ref = '" . $this->db->escape($num) . "',";
538
            $sql .= " status = " . self::STATUS_VALIDATED;
539
            if (!empty($this->fields['date_validation'])) {
540
                $sql .= ", date_validation = '" . $this->db->idate($now) . "',";
541
            }
542
            if (!empty($this->fields['fk_user_valid'])) {
543
                $sql .= ", fk_user_valid = " . $user->id;
544
            }
545
            $sql .= " WHERE rowid = " . ((int) $this->id);
546
547
            dol_syslog(get_class($this) . "::validate()", LOG_DEBUG);
548
            $resql = $this->db->query($sql);
549
            if (!$resql) {
550
                dol_print_error($this->db);
551
                $this->error = $this->db->lasterror();
552
                $error++;
553
            }
554
555
            if (!$error && !$notrigger) {
556
                // Call trigger
557
                $result = $this->call_trigger('RECRUITMENTJOBPOSITION_VALIDATE', $user);
558
                if ($result < 0) {
559
                    $error++;
560
                }
561
                // End call triggers
562
            }
563
        }
564
565
        if (!$error) {
566
            $this->oldref = $this->ref;
567
568
            // Rename directory if dir was a temporary ref
569
            if (preg_match('/^[\(]?PROV/i', $this->ref)) {
570
                // Now we rename also files into index
571
                $sql = 'UPDATE ' . MAIN_DB_PREFIX . "ecm_files set filename = CONCAT('" . $this->db->escape($this->newref) . "', SUBSTR(filename, " . (strlen($this->ref) + 1) . ")), filepath = 'recruitmentjobposition/" . $this->db->escape($this->newref) . "'";
572
                $sql .= " WHERE filename LIKE '" . $this->db->escape($this->ref) . "%' AND filepath = 'recruitmentjobposition/" . $this->db->escape($this->ref) . "' and entity = " . $conf->entity;
573
                $resql = $this->db->query($sql);
574
                if (!$resql) {
575
                    $error++;
576
                    $this->error = $this->db->lasterror();
577
                }
578
                $sql = 'UPDATE ' . MAIN_DB_PREFIX . "ecm_files set filepath = 'recruitmentjobposition/" . $this->db->escape($this->newref) . "'";
579
                $sql .= " WHERE filepath = 'recruitmentjobposition/" . $this->db->escape($this->ref) . "' and entity = " . $conf->entity;
580
                $resql = $this->db->query($sql);
581
                if (!$resql) {
582
                    $error++;
583
                    $this->error = $this->db->lasterror();
584
                }
585
586
                // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
587
                $oldref = dol_sanitizeFileName($this->ref);
588
                $newref = dol_sanitizeFileName($num);
589
                $dirsource = $conf->recruitment->dir_output . '/recruitmentjobposition/' . $oldref;
590
                $dirdest = $conf->recruitment->dir_output . '/recruitmentjobposition/' . $newref;
591
                if (!$error && file_exists($dirsource)) {
592
                    dol_syslog(get_class($this) . "::validate() rename dir " . $dirsource . " into " . $dirdest);
593
594
                    if (@rename($dirsource, $dirdest)) {
595
                        dol_syslog("Rename ok");
596
                        // Rename docs starting with $oldref with $newref
597
                        $listoffiles = dol_dir_list($conf->recruitment->dir_output . '/recruitmentjobposition/' . $newref, 'files', 1, '^' . preg_quote($oldref, '/'));
598
                        foreach ($listoffiles as $fileentry) {
599
                            $dirsource = $fileentry['name'];
600
                            $dirdest = preg_replace('/^' . preg_quote($oldref, '/') . '/', $newref, $dirsource);
601
                            $dirsource = $fileentry['path'] . '/' . $dirsource;
602
                            $dirdest = $fileentry['path'] . '/' . $dirdest;
603
                            @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

603
                            /** @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...
604
                        }
605
                    }
606
                }
607
            }
608
        }
609
610
        // Set new ref and current status
611
        if (!$error) {
612
            $this->ref = $num;
613
            $this->status = self::STATUS_VALIDATED;
614
        }
615
616
        if (!$error) {
617
            $this->db->commit();
618
            return 1;
619
        } else {
620
            $this->db->rollback();
621
            return -1;
622
        }
623
    }
624
625
626
    /**
627
     *  Set draft status
628
     *
629
     *  @param  User    $user           Object user that modify
630
     *  @param  int     $notrigger      1=Does not execute triggers, 0=Execute triggers
631
     *  @return int                     Return integer <0 if KO, >0 if OK
632
     */
633
    public function setDraft($user, $notrigger = 0)
634
    {
635
        // Protection
636
        if ($this->status <= self::STATUS_DRAFT) {
637
            return 0;
638
        }
639
640
        /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->recruitment->write))
641
         || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->recruitment->recruitment_advance->validate))))
642
         {
643
         $this->error='Permission denied';
644
         return -1;
645
         }*/
646
647
        return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'RECRUITMENTJOBPOSITION_UNVALIDATE');
648
    }
649
650
    /**
651
     *  Set cancel status
652
     *
653
     *  @param  User    $user           Object user that modify
654
     *  @param  int     $notrigger      1=Does not execute triggers, 0=Execute triggers
655
     *  @return int                     Return integer <0 if KO, 0=Nothing done, >0 if OK
656
     */
657
    public function cancel($user, $notrigger = 0)
658
    {
659
        // Protection
660
        if ($this->status != self::STATUS_VALIDATED) {
661
            return 0;
662
        }
663
664
        /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->recruitment->write))
665
         || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->recruitment->recruitment_advance->validate))))
666
         {
667
         $this->error='Permission denied';
668
         return -1;
669
         }*/
670
671
        return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'RECRUITMENTJOBPOSITION_CLOSE');
672
    }
673
674
    /**
675
     *  Close the recruitment
676
     *
677
     *  @param      User    $user       Object user that close
678
     *  @param      int     $status     Statut
679
     *  @param      string  $note       Complete private note with this note
680
     *  @param      int     $notrigger  1=Does not execute triggers, 0=Execute triggers
681
     *  @return     int                 Return integer <0 if KO, >0 if OK
682
     */
683
    public function cloture($user, $status, $note = "", $notrigger = 0)
684
    {
685
        global $langs, $conf;
686
687
        $error = 0;
688
        $now = dol_now();
689
690
        $this->db->begin();
691
692
        $newprivatenote = dol_concatdesc($this->note_private, $note);
693
694
        $sql = "UPDATE " . MAIN_DB_PREFIX . $this->table_element;
695
        $sql .= " SET status = " . ((int) $status) . ", note_private = '" . $this->db->escape($newprivatenote) . "'";
696
        //$sql .= ", date_cloture='".$this->db->idate($now)."', fk_user_cloture=".$user->id;
697
        $sql .= " WHERE rowid = " . ((int) $this->id);
698
699
        $resql = $this->db->query($sql);
700
        if ($resql) {
701
            $modelpdf = $this->model_pdf;
702
            $triggerName = 'RECRUITMENTJOB_CLOSE_REFUSED';
703
704
            if ($status == self::STATUS_RECRUITED) {
705
                $triggerName = 'RECRUITMENTJOB_CLOSE_RECRUITED';
706
                $modelpdf = $this->model_pdf;
707
            }
708
709
            if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
710
                // Define output language
711
                $outputlangs = $langs;
712
                if (getDolGlobalInt('MAIN_MULTILANGS')) {
713
                    $outputlangs = new Translate("", $conf);
714
                    $newlang = (GETPOST('lang_id', 'aZ09') ? GETPOST('lang_id', 'aZ09') : $this->thirdparty->default_lang);
715
                    $outputlangs->setDefaultLang($newlang);
716
                }
717
718
                // PDF
719
                $hidedetails = (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS') ? 1 : 0);
720
                $hidedesc = (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DESC') ? 1 : 0);
721
                $hideref = (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_REF') ? 1 : 0);
722
723
                //$ret=$object->fetch($id);    // Reload to get new records
724
                $this->generateDocument($modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
725
            }
726
727
            if (!$error) {
728
                $this->oldcopy = clone $this;
729
                $this->status = $status;
730
                $this->date_cloture = $now;
731
                $this->note_private = $newprivatenote;
732
            }
733
734
            if (!$notrigger && empty($error)) {
735
                // Call trigger
736
                $result = $this->call_trigger($triggerName, $user);
737
                if ($result < 0) {
738
                    $error++;
739
                }
740
                // End call triggers
741
            }
742
743
            if (!$error) {
744
                $this->db->commit();
745
                return 1;
746
            } else {
747
                $this->status = $this->oldcopy->status;
748
                $this->date_cloture = $this->oldcopy->date_cloture;
749
                $this->note_private = $this->oldcopy->note_private;
750
751
                $this->db->rollback();
752
                return -1;
753
            }
754
        } else {
755
            $this->error = $this->db->lasterror();
756
            $this->db->rollback();
757
            return -1;
758
        }
759
    }
760
761
    /**
762
     *  Set back to validated status
763
     *
764
     *  @param  User    $user           Object user that modify
765
     *  @param  int     $notrigger      1=Does not execute triggers, 0=Execute triggers
766
     *  @return int                     Return integer <0 if KO, 0=Nothing done, >0 if OK
767
     */
768
    public function reopen($user, $notrigger = 0)
769
    {
770
        // Protection
771
        if ($this->status != self::STATUS_CANCELED) {
772
            return 0;
773
        }
774
775
        /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->recruitment->write))
776
         || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->recruitment->recruitment_advance->validate))))
777
         {
778
         $this->error='Permission denied';
779
         return -1;
780
         }*/
781
782
        return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'RECRUITMENTJOBPOSITION_REOPEN');
783
    }
784
785
    /**
786
     *  Return a link to the object card (with optionally the picto)
787
     *
788
     *  @param  int     $withpicto                  Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
789
     *  @param  string  $option                     On what the link point to ('nolink', ...)
790
     *  @param  int     $notooltip                  1=Disable tooltip
791
     *  @param  string  $morecss                    Add more css on link
792
     *  @param  int     $save_lastsearch_value      -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
793
     *  @return string                              String with URL
794
     */
795
    public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
796
    {
797
        global $conf, $langs, $hookmanager;
798
799
        if (!empty($conf->dol_no_mouse_hover)) {
800
            $notooltip = 1; // Force disable tooltips
801
        }
802
803
        $result = '';
804
805
        $label = img_picto('', $this->picto) . ' <u class="paddingrightonly">' . $langs->trans("PositionToBeFilled") . '</u>';
806
        if (isset($this->status)) {
807
            $label .= ' ' . $this->getLibStatut(5);
808
        }
809
        $label .= '<br>';
810
        $label .= '<b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;
811
        $label .= '<br><b>' . $langs->trans('Label') . ':</b> ' . $this->label;
812
813
        $url = dol_buildpath('/recruitment/recruitmentjobposition_card.php', 1) . '?id=' . $this->id;
814
815
        if ($option != 'nolink') {
816
            // Add param to save lastsearch_values or not
817
            $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
818
            if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
819
                $add_save_lastsearch_values = 1;
820
            }
821
            if ($add_save_lastsearch_values) {
822
                $url .= '&save_lastsearch_values=1';
823
            }
824
        }
825
826
        $linkclose = '';
827
        if (empty($notooltip)) {
828
            if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
829
                $label = $langs->trans("ShowRecruitmentJobPosition");
830
                $linkclose .= ' alt="' . dol_escape_htmltag($label, 1) . '"';
831
            }
832
            $linkclose .= ' title="' . dol_escape_htmltag($label, 1) . '"';
833
            $linkclose .= ' class="classfortooltip' . ($morecss ? ' ' . $morecss : '') . '"';
834
        } else {
835
            $linkclose = ($morecss ? ' class="' . $morecss . '"' : '');
836
        }
837
838
        $linkstart = '<a href="' . $url . '"';
839
        $linkstart .= $linkclose . '>';
840
        $linkend = '</a>';
841
842
        $result .= $linkstart;
843
844
        if (empty($this->showphoto_on_popup)) {
845
            if ($withpicto) {
846
                $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);
847
            }
848
        } else {
849
            if ($withpicto) {
850
                require_once constant('DOL_DOCUMENT_ROOT') . '/core/lib/files.lib.php';
851
852
                list($class, $module) = explode('@', $this->picto);
853
                $upload_dir = $conf->$module->multidir_output[$conf->entity] . "/$class/" . dol_sanitizeFileName($this->ref);
854
                $filearray = dol_dir_list($upload_dir, "files");
855
                $filename = $filearray[0]['name'];
856
                if (!empty($filename)) {
857
                    $pospoint = strpos($filearray[0]['name'], '.');
858
859
                    $pathtophoto = $class . '/' . $this->ref . '/thumbs/' . substr($filename, 0, $pospoint) . '_mini' . substr($filename, $pospoint);
860
                    if (!getDolGlobalString(strtoupper($module . '_' . $class) . '_FORMATLISTPHOTOSASUSERS')) {
861
                        $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>';
862
                    } else {
863
                        $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>';
864
                    }
865
866
                    $result .= '</div>';
867
                } else {
868
                    $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);
869
                }
870
            }
871
        }
872
873
        if ($withpicto != 2) {
874
            $result .= $this->ref;
875
        }
876
877
        $result .= $linkend;
878
        //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
879
880
        global $action, $hookmanager;
881
        $hookmanager->initHooks(array('recruitmentjobpositiondao'));
882
        $parameters = array('id' => $this->id, 'getnomurl' => &$result);
883
        $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
884
        if ($reshook > 0) {
885
            $result = $hookmanager->resPrint;
886
        } else {
887
            $result .= $hookmanager->resPrint;
888
        }
889
890
        return $result;
891
    }
892
893
    /**
894
     *  Return label of the status
895
     *
896
     *  @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
897
     *  @return string                 Label of status
898
     */
899
    public function getLibStatut($mode = 0)
900
    {
901
        return $this->LibStatut($this->status, $mode);
902
    }
903
904
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
905
    /**
906
     *  Return the status
907
     *
908
     *  @param  int     $status        Id status
909
     *  @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
910
     *  @return string                 Label of status
911
     */
912
    public function LibStatut($status, $mode = 0)
913
    {
914
		// phpcs:enable
915
        if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
916
            global $langs;
917
            //$langs->load("recruitment");
918
            $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
919
            $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Validated');
920
            $this->labelStatus[self::STATUS_RECRUITED] = $langs->transnoentitiesnoconv('Recruited');
921
            $this->labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Canceled');
922
            $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
923
            $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Validated');
924
            $this->labelStatusShort[self::STATUS_RECRUITED] = $langs->transnoentitiesnoconv('Recruited');
925
            $this->labelStatusShort[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Canceled');
926
        }
927
928
        $statusType = 'status' . $status;
929
        if ($status == self::STATUS_VALIDATED) {
930
            $statusType = 'status4';
931
        }
932
        if ($status == self::STATUS_RECRUITED) {
933
            $statusType = 'status6';
934
        }
935
        if ($status == self::STATUS_CANCELED) {
936
            $statusType = 'status9';
937
        }
938
939
        return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
940
    }
941
942
    /**
943
     *  Load the info information in the object
944
     *
945
     *  @param  int     $id       Id of object
946
     *  @return void
947
     */
948
    public function info($id)
949
    {
950
        $sql = 'SELECT rowid, date_creation as datec, tms as datem,';
951
        $sql .= ' fk_user_creat, fk_user_modif';
952
        $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t';
953
        $sql .= ' WHERE t.rowid = ' . ((int) $id);
954
        $result = $this->db->query($sql);
955
        if ($result) {
956
            if ($this->db->num_rows($result)) {
957
                $obj = $this->db->fetch_object($result);
958
959
                $this->id = $obj->rowid;
960
961
                $this->user_creation_id = $obj->fk_user_creat;
962
                $this->user_modification_id = $obj->fk_user_modif;
963
                $this->date_creation     = $this->db->jdate($obj->datec);
964
                $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
965
            }
966
967
            $this->db->free($result);
968
        } else {
969
            dol_print_error($this->db);
970
        }
971
    }
972
973
    /**
974
     * Initialise object with example values
975
     * Id must be 0 if object instance is a specimen
976
     *
977
     * @return int
978
     */
979
    public function initAsSpecimen()
980
    {
981
        return $this->initAsSpecimenCommon();
982
    }
983
984
    /**
985
     *  Create an array of lines
986
     *
987
     *  @return array|int       array of lines if OK, <0 if KO
988
     */
989
    public function getLinesArray()
990
    {
991
        $this->lines = array();
992
993
        return $this->lines;
994
    }
995
996
    /**
997
     *  Returns the reference to the following non used object depending on the active numbering module.
998
     *
999
     *  @return string              Object free reference
1000
     */
1001
    public function getNextNumRef()
1002
    {
1003
        global $langs, $conf;
1004
        $langs->load("recruitment");
1005
1006
        if (!getDolGlobalString('RECRUITMENT_RECRUITMENTJOBPOSITION_ADDON')) {
1007
            $conf->global->RECRUITMENT_RECRUITMENTJOBPOSITION_ADDON = 'mod_recruitmentjobposition_standard';
1008
        }
1009
1010
        if (getDolGlobalString('RECRUITMENT_RECRUITMENTJOBPOSITION_ADDON')) {
1011
            $mybool = false;
1012
1013
            $file = getDolGlobalString('RECRUITMENT_RECRUITMENTJOBPOSITION_ADDON') . ".php";
1014
            $classname = getDolGlobalString('RECRUITMENT_RECRUITMENTJOBPOSITION_ADDON');
1015
1016
            // Include file with class
1017
            $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
1018
            foreach ($dirmodels as $reldir) {
1019
                $dir = dol_buildpath($reldir . "core/modules/recruitment/");
1020
1021
                // Load file with numbering class (if found)
1022
                $mybool = ((bool) @include_once $dir . $file) || $mybool;
1023
            }
1024
1025
            if ($mybool === false) {
1026
                dol_print_error(null, "Failed to include file " . $file);
1027
                return '';
1028
            }
1029
1030
            if (class_exists($classname)) {
1031
                $obj = new $classname();
1032
                $numref = $obj->getNextValue($this);
1033
1034
                if ($numref != '' && $numref != '-1') {
1035
                    return $numref;
1036
                } else {
1037
                    $this->error = $obj->error;
1038
                    //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
1039
                    return "";
1040
                }
1041
            } else {
1042
                print $langs->trans("Error") . " " . $langs->trans("ClassNotFound") . ' ' . $classname;
1043
                return "";
1044
            }
1045
        } else {
1046
            print $langs->trans("ErrorNumberingModuleNotSetup", $this->element);
1047
            return "";
1048
        }
1049
    }
1050
1051
    /**
1052
     *  Create a document onto disk according to template module.
1053
     *
1054
     *  @param      string      $modele         Force template to use ('' to not force)
1055
     *  @param      Translate   $outputlangs    object lang a utiliser pour traduction
1056
     *  @param      int         $hidedetails    Hide details of lines
1057
     *  @param      int         $hidedesc       Hide description
1058
     *  @param      int         $hideref        Hide ref
1059
     *  @param      null|array  $moreparams     Array to provide more information
1060
     *  @return     int                         0 if KO, 1 if OK
1061
     */
1062
    public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
1063
    {
1064
        global $conf, $langs;
1065
1066
        $result = 0;
1067
        $includedocgeneration = 1;
1068
1069
        $langs->load("recruitment");
1070
1071
        if (!dol_strlen($modele)) {
1072
            if (getDolGlobalString('RECRUITMENTJOBPOSITION_ADDON_PDF')) {
1073
                $modele = getDolGlobalString('RECRUITMENTJOBPOSITION_ADDON_PDF');
1074
            } else {
1075
                $modele = ''; // No default value. For job position, we allow to disable all PDF generation
1076
            }
1077
        }
1078
1079
        $modelpath = "core/modules/recruitment/doc/";
1080
1081
        if ($includedocgeneration && !empty($modele)) {
1082
            $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
1083
        }
1084
1085
        return $result;
1086
    }
1087
1088
    /**
1089
     * Action executed by scheduler
1090
     * CAN BE A CRON TASK. In such a case, parameters come from the schedule job setup field 'Parameters'
1091
     * Use public function doScheduledJob($param1, $param2, ...) to get parameters
1092
     *
1093
     * @return  int         0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
1094
     */
1095
    public function doScheduledJob()
1096
    {
1097
        //global $conf, $langs;
1098
1099
        //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
1100
1101
        $error = 0;
1102
        $this->output = '';
1103
        $this->error = '';
1104
1105
        dol_syslog(__METHOD__, LOG_DEBUG);
1106
1107
        $now = dol_now();
1108
1109
        $this->db->begin();
1110
1111
        // ...
1112
1113
        $this->db->commit();
1114
1115
        return $error;
1116
    }
1117
1118
1119
    /**
1120
     *  Return clicable link of object (with eventually picto)
1121
     *
1122
     *  @param      string      $option                 Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
1123
     *  @param      array       $arraydata              Array of data
1124
     *  @return     string                              HTML Code for Kanban thumb.
1125
     */
1126
    public function getKanbanView($option = '', $arraydata = null)
1127
    {
1128
        global $langs;
1129
1130
        $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
1131
1132
        $return = '<div class="box-flex-item box-flex-grow-zero">';
1133
        $return .= '<div class="info-box info-box-sm">';
1134
        $return .= '<span class="info-box-icon bg-infobox-action">';
1135
        $return .= img_picto('', $this->picto);
1136
        $return .= '</span>';
1137
        $return .= '<div class="info-box-content">';
1138
        $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">' . (method_exists($this, 'getNomUrl') ? $this->getNomUrl(1) : $this->ref) . ($this->qty > 1 ? ' <span title="' . $langs->trans("NbOfEmployeesExpected") . '">(' . $this->qty . ')</span>' : '') . '</span>';
1139
        if ($selected >= 0) {
1140
            $return .= '<input id="cb' . $this->id . '" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="' . $this->id . '"' . ($selected ? ' checked="checked"' : '') . '>';
1141
        }
1142
        /*
1143
        if (property_exists($this, 'date_planned')) {
1144
            $return .= '<br><span class="opacitymedium">'.$langs->trans("Date").'</span> : <span class="info-box-label">'.dol_print_date($this->db->jdate($this->date_planned), 'day').'</span>';
1145
        }*/
1146
        if (property_exists($this, 'remuneration_suggested')) {
1147
            $return .= '<br><span class="opacitymedium">' . $langs->trans("Remuneration") . '</span> : <span class="info-box-label">' . $this->remuneration_suggested . '</span>';
1148
        }
1149
        if (method_exists($this, 'getLibStatut')) {
1150
            $return .= '<br><div class="info-box-status">' . $this->getLibStatut(3) . ' &nbsp; <span class="opacitymedium" title="' . $langs->trans("RecruitmentCandidatures") . '">' . $langs->trans("RecruitmentCandidatures", '', '', '', '', 5) . '</span> : <span>';
1151
            $return .= $arraydata['nbapplications'];
1152
            $return .= '</span></div>';
1153
        }
1154
        $return .= '</div>';
1155
        $return .= '</div>';
1156
        $return .= '</div>';
1157
        return $return;
1158
    }
1159
}
1160