Passed
Pull Request — dev (#8)
by Rafael
58:47
created

RecruitmentCandidature::validate()   F

Complexity

Conditions 22
Paths 2801

Size

Total Lines 122
Code Lines 71

Duplication

Lines 0
Ratio 0 %

Importance

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

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