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

RecruitmentCandidature::createFromClone()   F

Complexity

Conditions 22
Paths 13824

Size

Total Lines 91
Code Lines 47

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 22
eloc 47
nc 13824
nop 2
dl 0
loc 91
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
//require_once constant('DOL_DOCUMENT_ROOT') . '/product/class/product.class.php';
36
37
/**
38
 * Class for RecruitmentCandidature
39
 */
40
class RecruitmentCandidature 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 = 'recruitmentcandidature';
51
52
    /**
53
     * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management.
54
     */
55
    public $table_element = 'recruitment_recruitmentcandidature';
56
57
    /**
58
     * @var string String with name of icon for recruitmentcandidature. Must be the part after the 'object_' into object_recruitmentcandidature.png
59
     */
60
    public $picto = 'recruitmentcandidature';
61
62
    /**
63
     * @var int     Do not exploit fields email_xxx into triggers.
64
     */
65
    public $email_fields_no_propagate_in_actioncomm;
66
67
68
    const STATUS_DRAFT = 0;
69
    const STATUS_VALIDATED = 1;
70
    //const STATUS_INTERVIEW_SCHEDULED = 2;
71
    const STATUS_CONTRACT_PROPOSED = 3;
72
    const STATUS_CONTRACT_SIGNED = 5;
73
    const STATUS_CONTRACT_REFUSED = 6;
74
    const STATUS_REFUSED = 8;
75
    const STATUS_CANCELED = 9;
76
77
78
    /**
79
     *  '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')
80
     *         Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
81
     *  'label' the translation key.
82
     *  'enabled' is a condition when the field must be managed (Example: 1 or 'getDolGlobalString("MY_SETUP_PARAM")'
83
     *  'position' is the sort order of field.
84
     *  'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
85
     *  'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing)
86
     *  'noteditable' says if field is not editable (1 or 0)
87
     *  '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.
88
     *  'index' if we want an index in database.
89
     *  'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommended to name the field fk_...).
90
     *  'searchall' is 1 if we want to search in this field when making a search from the quick search button.
91
     *  '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).
92
     *  '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'
93
     *  'help' is a string visible as a tooltip on field
94
     *  'showoncombobox' if value of the field must be visible into the label of the combobox that list record
95
     *  '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.
96
     *  'arrayofkeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel")
97
     *  'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1.
98
     *  'comment' is not used. You can store here any text of your choice. It is not used by application.
99
     *
100
     *  Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
101
     */
102
103
    // BEGIN MODULEBUILDER PROPERTIES
104
    /**
105
     * @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...
106
     */
107
    public $fields = array(
108
        'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'position' => 1, 'notnull' => 1, 'visible' => 0, 'noteditable' => 1, 'index' => 1, 'comment' => "Id"),
109
        'entity' => array('type' => 'integer', 'label' => 'Entity', 'enabled' => 1, 'visible' => 0, 'position' => 5, 'notnull' => 1, 'default' => '1', 'index' => 1),
110
        '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'),
111
        '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'),
112
        'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'position' => 61, 'notnull' => 0, 'visible' => 0,),
113
        'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'position' => 62, 'notnull' => 0, 'visible' => 0,),
114
        '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'),
115
        'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => 1, 'position' => 511, 'notnull' => -1, 'visible' => -2, 'csslist' => 'tdoverflowmax100'),
116
        'lastname' => array('type' => 'varchar(128)', 'label' => 'Lastname', 'enabled' => 1, 'position' => 20, 'notnull' => 0, 'visible' => 1, 'csslist' => 'tdoverflowmax150'),
117
        'firstname' => array('type' => 'varchar(128)', 'label' => 'Firstname', 'enabled' => 1, 'position' => 21, 'notnull' => 0, 'visible' => 1, 'csslist' => 'tdoverflowmax150'),
118
        'email' => array('type' => 'email', 'label' => 'EMail', 'enabled' => 1, 'position' => 30, 'notnull' => 1, 'visible' => 1, 'picto' => 'email', 'csslist' => 'tdoverflowmax150'),
119
        'phone' => array('type' => 'phone', 'label' => 'Phone', 'enabled' => 1, 'position' => 31, 'notnull' => 0, 'visible' => 1, 'picto' => 'phone', 'csslist' => 'tdoverflowmax150'),
120
        'date_birth' => array('type' => 'date', 'label' => 'DateOfBirth', 'enabled' => 1, 'position' => 70, 'visible' => -1,),
121
        'email_msgid' => array('type' => 'varchar(255)', 'label' => 'EmailMsgID', 'visible' => -2, 'enabled' => 1, 'position' => 540, 'notnull' => -1, 'help' => 'EmailMsgIDDesc'),
122
        'email_date' => array('type' => 'datetime', 'label' => 'EmailDate', 'visible' => -2, 'enabled' => 1, 'position' => 541),
123
        //'fk_recruitment_origin' => array('type'=>'integer:CRecruitmentOrigin:recruitment/class/crecruitmentorigin.class.php', 'label'=>'Origin', 'enabled'=>'1', 'position'=>45, 'visible'=>1, 'index'=>1),
124
        'remuneration_requested' => array('type' => 'integer', 'label' => 'RequestedRemuneration', 'enabled' => 1, 'position' => 80, 'notnull' => 0, 'visible' => -1,),
125
        'remuneration_proposed' => array('type' => 'integer', 'label' => 'ProposedRemuneration', 'enabled' => 1, 'position' => 81, 'notnull' => 0, 'visible' => -1,),
126
        'description' => array('type' => 'html', 'label' => 'Description', 'enabled' => 1, 'position' => 300, 'notnull' => 0, 'visible' => 3, 'cssview' => 'wordbreak'),
127
        'date_creation' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'position' => 500, 'notnull' => 1, 'visible' => -4, 'csslist' => 'nowraponall'),
128
        'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'position' => 501, 'notnull' => 0, 'visible' => -2, 'csslist' => 'nowraponall'),
129
        'fk_user' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'LinkedToDolibarrUser', 'enabled' => 1, 'position' => 600, 'notnull' => 0, 'visible' => -1, 'csslist' => 'tdoverflowmax100'),
130
        'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'position' => 1000, 'notnull' => -1, 'visible' => -2,),
131
        'model_pdf' => array('type' => 'varchar(255)', 'label' => 'Model pdf', 'enabled' => 1, 'position' => 1010, 'notnull' => -1, 'visible' => 0,),
132
        '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')),
133
    );
134
    public $rowid;
135
    public $entity;
136
    public $ref;
137
    public $fk_recruitmentjobposition;
138
    public $description;
139
    public $note_public;
140
    public $note_private;
141
    public $date_creation;
142
    public $fk_user_creat;
143
    public $fk_user_modif;
144
    public $fk_user;
145
    public $lastname;
146
    public $firstname;
147
    public $email;
148
    public $phone;
149
    public $date_birth;
150
    public $email_msgid;
151
    public $email_date;
152
    public $remuneration_requested;
153
    public $remuneration_proposed;
154
    public $fk_recruitment_origin;
155
    public $import_key;
156
    public $model_pdf;
157
    public $status;
158
    // END MODULEBUILDER PROPERTIES
159
160
161
    /**
162
     * Constructor
163
     *
164
     * @param DoliDB $db Database handler
165
     */
166
    public function __construct(DoliDB $db)
167
    {
168
        global $conf, $langs;
169
170
        $this->db = $db;
0 ignored issues
show
Documentation Bug introduced by
It seems like $db of type DoliDB is incompatible with the declared type Dolibarr\Core\Base\DoliDB of property $db.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

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

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