Completed
Branch develop (4017a9)
by
unknown
27:45
created

Holiday::deleteCPuser()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 8
rs 10
c 0
b 0
f 0
1
<?php
2
/* Copyright (C) 2011		Dimitri Mouillard	<[email protected]>
3
 * Copyright (C) 2012-2014	Laurent Destailleur	<[email protected]>
4
 * Copyright (C) 2012-2016	Regis Houssin		<[email protected]>
5
 * Copyright (C) 2013		Florian Henry		<[email protected]>
6
 * Copyright (C) 2016       Juanjo Menent       <[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 <http://www.gnu.org/licenses/>.
20
 */
21
22
/**
23
 *    \file       holiday.class.php
24
 *    \ingroup    holiday
25
 *    \brief      Class file of the module paid holiday.
26
 */
27
require_once DOL_DOCUMENT_ROOT .'/core/class/commonobject.class.php';
28
29
30
/**
31
 *	Class of the module paid holiday. Developed by Teclib ( http://www.teclib.com/ )
32
 */
33
class Holiday extends CommonObject
34
{
35
	/**
36
	 * @var string ID to identify managed object
37
	 */
38
	public $element='holiday';
39
40
	/**
41
	 * @var string Name of table without prefix where object is stored
42
	 */
43
	public $table_element='holiday';
44
45
	public $ismultientitymanaged = 0;	// 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
46
	var $fk_element = 'fk_holiday';
47
	public $picto = 'holiday';
48
49
	/**
50
	 * @deprecated
51
	 * @see id
52
	 */
53
	var $rowid;
54
55
	/**
56
	 * @var int User ID
57
	 */
58
	public $fk_user;
59
60
	var $date_create='';
61
62
	/**
63
	 * @var string description
64
	 */
65
	public $description;
66
67
	var $date_debut='';			// Date start in PHP server TZ
68
	var $date_fin='';			// Date end in PHP server TZ
69
	var $date_debut_gmt='';		// Date start in GMT
70
	var $date_fin_gmt='';		// Date end in GMT
71
	var $halfday='';			// 0:Full days, 2:Start afternoon end morning, -1:Start afternoon end afternoon, 1:Start morning end morning
72
	var $statut='';				// 1=draft, 2=validated, 3=approved
73
	var $fk_validator;
74
	var $date_valid='';
75
	var $fk_user_valid;
76
	var $date_refuse='';
77
	var $fk_user_refuse;
78
	var $date_cancel='';
79
	var $fk_user_cancel;
80
	var $detail_refuse='';
81
	var $fk_type;
82
83
	var $holiday = array();
84
	var $events = array();
85
	var $logs = array();
86
87
	var $optName = '';
88
	var $optValue = '';
89
	var $optRowid = '';
90
91
	/**
92
	 * Draft status
93
	 */
94
	const STATUS_DRAFT = 1;
95
	/**
96
	 * Validated status
97
	 */
98
	const STATUS_VALIDATED = 2;
99
	/**
100
	 * Approved
101
	 */
102
	const STATUS_APPROVED = 3;
103
	/**
104
	 * Canceled
105
	 */
106
	const STATUS_CANCELED = 4;
107
	/**
108
	 * Refused
109
	 */
110
	const STATUS_REFUSED = 5;
111
112
113
	/**
114
	 *   Constructor
115
	 *
116
	 *   @param		DoliDB		$db      Database handler
117
	 */
118
	function __construct($db)
119
	{
120
		$this->db = $db;
121
	}
122
123
124
	/**
125
	 * Update balance of vacations and check table of users for holidays is complete. If not complete.
126
	 *
127
	 * @return	int			<0 if KO, >0 if OK
128
	 */
129
	function updateBalance()
130
	{
131
		$this->db->begin();
132
133
		// Update sold of vocations
134
		$result = $this->updateSoldeCP();
135
136
		// Check nb of users into table llx_holiday_users and update with empty lines
137
		//if ($result > 0) $result = $this->verifNbUsers($this->countActiveUsersWithoutCP(), $this->getConfCP('nbUser'));
138
139
		if ($result >= 0)
140
		{
141
			$this->db->commit();
142
			return 1;
143
		}
144
		else
145
		{
146
			$this->db->rollback();
147
			return -1;
148
		}
149
	}
150
151
	/**
152
	 *   Créer un congés payés dans la base de données
153
	 *
154
	 *   @param		User	$user        	User that create
155
	 *   @param     int		$notrigger	    0=launch triggers after, 1=disable triggers
156
	 *   @return    int			         	<0 if KO, Id of created object if OK
157
	 */
158
	function create($user, $notrigger=0)
159
	{
160
		global $conf;
161
		$error=0;
162
163
		$now=dol_now();
164
165
		// Check parameters
166
		if (empty($this->fk_user) || ! is_numeric($this->fk_user) || $this->fk_user < 0) { $this->error="ErrorBadParameterFkUser"; return -1; }
167
		if (empty($this->fk_validator) || ! is_numeric($this->fk_validator) || $this->fk_validator < 0)  { $this->error="ErrorBadParameterFkValidator"; return -1; }
168
		if (empty($this->fk_type) || ! is_numeric($this->fk_type) || $this->fk_type < 0) { $this->error="ErrorBadParameterFkType"; return -1; }
169
170
		// Insert request
171
		$sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday(";
172
		$sql.= "fk_user,";
173
		$sql.= "date_create,";
174
		$sql.= "description,";
175
		$sql.= "date_debut,";
176
		$sql.= "date_fin,";
177
		$sql.= "halfday,";
178
		$sql.= "statut,";
179
		$sql.= "fk_validator,";
180
		$sql.= "fk_type,";
181
		$sql.= "fk_user_create,";
182
		$sql.= "entity";
183
		$sql.= ") VALUES (";
184
		$sql.= "'".$this->db->escape($this->fk_user)."',";
185
		$sql.= " '".$this->db->idate($now)."',";
186
		$sql.= " '".$this->db->escape($this->description)."',";
187
		$sql.= " '".$this->db->idate($this->date_debut)."',";
188
		$sql.= " '".$this->db->idate($this->date_fin)."',";
189
		$sql.= " ".$this->halfday.",";
190
		$sql.= " '1',";
191
		$sql.= " '".$this->db->escape($this->fk_validator)."',";
192
		$sql.= " ".$this->fk_type.",";
193
		$sql.= " ".$user->id.",";
194
		$sql.= " ".$conf->entity;
195
		$sql.= ")";
196
197
		$this->db->begin();
198
199
		dol_syslog(get_class($this)."::create", LOG_DEBUG);
200
		$resql=$this->db->query($sql);
201
		if (! $resql) {
202
			$error++; $this->errors[]="Error ".$this->db->lasterror();
203
		}
204
205
		if (! $error)
206
		{
207
			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."holiday");
208
209
			if (! $notrigger)
210
			{
211
				// Call trigger
212
				$result=$this->call_trigger('HOLIDAY_CREATE',$user);
213
				if ($result < 0) { $error++; }
214
				// End call triggers
215
			}
216
		}
217
218
		// Commit or rollback
219
		if ($error)
220
		{
221
			foreach($this->errors as $errmsg)
222
			{
223
				dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
224
				$this->error.=($this->error?', '.$errmsg:$errmsg);
225
			}
226
			$this->db->rollback();
227
			return -1*$error;
228
		}
229
		else
230
		{
231
			$this->db->commit();
232
			return $this->id;
233
		}
234
	}
235
236
237
	/**
238
	 *	Load object in memory from database
239
	 *
240
	 *  @param	int		$id         Id object
241
	 *  @return int         		<0 if KO, >0 if OK
242
	 */
243
	function fetch($id)
244
	{
245
		global $langs;
246
247
		$sql = "SELECT";
248
		$sql.= " cp.rowid,";
249
		$sql.= " cp.fk_user,";
250
		$sql.= " cp.date_create,";
251
		$sql.= " cp.description,";
252
		$sql.= " cp.date_debut,";
253
		$sql.= " cp.date_fin,";
254
		$sql.= " cp.halfday,";
255
		$sql.= " cp.statut,";
256
		$sql.= " cp.fk_validator,";
257
		$sql.= " cp.date_valid,";
258
		$sql.= " cp.fk_user_valid,";
259
		$sql.= " cp.date_refuse,";
260
		$sql.= " cp.fk_user_refuse,";
261
		$sql.= " cp.date_cancel,";
262
		$sql.= " cp.fk_user_cancel,";
263
		$sql.= " cp.detail_refuse,";
264
		$sql.= " cp.note_private,";
265
		$sql.= " cp.note_public,";
266
		$sql.= " cp.fk_user_create,";
267
		$sql.= " cp.fk_type,";
268
		$sql.= " cp.entity";
269
		$sql.= " FROM ".MAIN_DB_PREFIX."holiday as cp";
270
		$sql.= " WHERE cp.rowid = ".$id;
271
272
		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
273
		$resql=$this->db->query($sql);
274
		if ($resql)
275
		{
276
			if ($this->db->num_rows($resql))
277
			{
278
				$obj = $this->db->fetch_object($resql);
279
280
				$this->id    = $obj->rowid;
281
				$this->rowid = $obj->rowid;	// deprecated
282
				$this->ref   = $obj->rowid;
283
				$this->fk_user = $obj->fk_user;
284
				$this->date_create = $this->db->jdate($obj->date_create);
285
				$this->description = $obj->description;
286
				$this->date_debut = $this->db->jdate($obj->date_debut);
287
				$this->date_fin = $this->db->jdate($obj->date_fin);
288
				$this->date_debut_gmt = $this->db->jdate($obj->date_debut,1);
289
				$this->date_fin_gmt = $this->db->jdate($obj->date_fin,1);
290
				$this->halfday = $obj->halfday;
291
				$this->statut = $obj->statut;
292
				$this->fk_validator = $obj->fk_validator;
293
				$this->date_valid = $this->db->jdate($obj->date_valid);
294
				$this->fk_user_valid = $obj->fk_user_valid;
295
				$this->date_refuse = $this->db->jdate($obj->date_refuse);
296
				$this->fk_user_refuse = $obj->fk_user_refuse;
297
				$this->date_cancel = $this->db->jdate($obj->date_cancel);
298
				$this->fk_user_cancel = $obj->fk_user_cancel;
299
				$this->detail_refuse = $obj->detail_refuse;
300
				$this->note_private = $obj->note_private;
301
				$this->note_public = $obj->note_public;
302
				$this->fk_user_create = $obj->fk_user_create;
303
				$this->fk_type = $obj->fk_type;
304
				$this->entity = $obj->entity;
305
			}
306
			$this->db->free($resql);
307
308
			return 1;
309
		}
310
		else
311
		{
312
			$this->error="Error ".$this->db->lasterror();
313
			return -1;
314
		}
315
	}
316
317
	/**
318
	 *	List holidays for a particular user or list of users
319
	 *
320
	 *  @param		int|string		$user_id    ID of user to list, or comma separated list of IDs of users to list
321
	 *  @param      string			$order      Sort order
322
	 *  @param      string			$filter     SQL Filter
323
	 *  @return     int      					-1 if KO, 1 if OK, 2 if no result
324
	 */
325
	function fetchByUser($user_id, $order='', $filter='')
326
	{
327
		global $langs, $conf;
328
329
		$sql = "SELECT";
330
		$sql.= " cp.rowid,";
331
332
		$sql.= " cp.fk_user,";
333
		$sql.= " cp.fk_type,";
334
		$sql.= " cp.date_create,";
335
		$sql.= " cp.description,";
336
		$sql.= " cp.date_debut,";
337
		$sql.= " cp.date_fin,";
338
		$sql.= " cp.halfday,";
339
		$sql.= " cp.statut,";
340
		$sql.= " cp.fk_validator,";
341
		$sql.= " cp.date_valid,";
342
		$sql.= " cp.fk_user_valid,";
343
		$sql.= " cp.date_refuse,";
344
		$sql.= " cp.fk_user_refuse,";
345
		$sql.= " cp.date_cancel,";
346
		$sql.= " cp.fk_user_cancel,";
347
		$sql.= " cp.detail_refuse,";
348
349
		$sql.= " uu.lastname as user_lastname,";
350
		$sql.= " uu.firstname as user_firstname,";
351
		$sql.= " uu.login as user_login,";
352
		$sql.= " uu.statut as user_statut,";
353
		$sql.= " uu.photo as user_photo,";
354
355
		$sql.= " ua.lastname as validator_lastname,";
356
		$sql.= " ua.firstname as validator_firstname,";
357
		$sql.= " ua.login as validator_login,";
358
		$sql.= " ua.statut as validator_statut,";
359
		$sql.= " ua.photo as validator_photo";
360
361
		$sql.= " FROM ".MAIN_DB_PREFIX."holiday as cp, ".MAIN_DB_PREFIX."user as uu, ".MAIN_DB_PREFIX."user as ua";
362
		$sql.= " WHERE cp.entity IN (".getEntity('holiday').")";
363
		$sql.= " AND cp.fk_user = uu.rowid AND cp.fk_validator = ua.rowid"; // Hack pour la recherche sur le tableau
364
		$sql.= " AND cp.fk_user IN (".$user_id.")";
365
366
		// Selection filter
367
		if(!empty($filter)) {
368
			$sql.= $filter;
369
		}
370
371
		// Order of display of the result
372
		if(!empty($order)) {
373
			$sql.= $order;
374
		}
375
376
		dol_syslog(get_class($this)."::fetchByUser", LOG_DEBUG);
377
		$resql=$this->db->query($sql);
378
379
		// If no SQL error
380
		if ($resql) {
381
382
			$i = 0;
383
			$tab_result = $this->holiday;
384
			$num = $this->db->num_rows($resql);
385
386
			// If no registration
387
			if(!$num) {
388
				return 2;
389
			}
390
391
			// List the records and add them to the table
392
			while($i < $num) {
393
394
				$obj = $this->db->fetch_object($resql);
395
396
				$tab_result[$i]['rowid'] = $obj->rowid;
397
				$tab_result[$i]['ref'] = $obj->rowid;
398
				$tab_result[$i]['fk_user'] = $obj->fk_user;
399
				$tab_result[$i]['fk_type'] = $obj->fk_type;
400
				$tab_result[$i]['date_create'] = $this->db->jdate($obj->date_create);
401
				$tab_result[$i]['description'] = $obj->description;
402
				$tab_result[$i]['date_debut'] = $this->db->jdate($obj->date_debut);
403
				$tab_result[$i]['date_fin'] = $this->db->jdate($obj->date_fin);
404
				$tab_result[$i]['date_debut_gmt'] = $this->db->jdate($obj->date_debut,1);
405
				$tab_result[$i]['date_fin_gmt'] = $this->db->jdate($obj->date_fin,1);
406
				$tab_result[$i]['halfday'] = $obj->halfday;
407
				$tab_result[$i]['statut'] = $obj->statut;
408
				$tab_result[$i]['fk_validator'] = $obj->fk_validator;
409
				$tab_result[$i]['date_valid'] = $this->db->jdate($obj->date_valid);
410
				$tab_result[$i]['fk_user_valid'] = $obj->fk_user_valid;
411
				$tab_result[$i]['date_refuse'] = $this->db->jdate($obj->date_refuse);
412
				$tab_result[$i]['fk_user_refuse'] = $obj->fk_user_refuse;
413
				$tab_result[$i]['date_cancel'] = $this->db->jdate($obj->date_cancel);
414
				$tab_result[$i]['fk_user_cancel'] = $obj->fk_user_cancel;
415
				$tab_result[$i]['detail_refuse'] = $obj->detail_refuse;
416
417
				$tab_result[$i]['user_firstname'] = $obj->user_firstname;
418
				$tab_result[$i]['user_lastname'] = $obj->user_lastname;
419
				$tab_result[$i]['user_login'] = $obj->user_login;
420
				$tab_result[$i]['user_statut'] = $obj->user_statut;
421
				$tab_result[$i]['user_photo'] = $obj->user_photo;
422
423
				$tab_result[$i]['validator_firstname'] = $obj->validator_firstname;
424
				$tab_result[$i]['validator_lastname'] = $obj->validator_lastname;
425
				$tab_result[$i]['validator_login'] = $obj->validator_login;
426
				$tab_result[$i]['validator_statut'] = $obj->validator_statut;
427
				$tab_result[$i]['validator_photo'] = $obj->validator_photo;
428
429
				$i++;
430
			}
431
432
			// Returns 1 with the filled array
433
			$this->holiday = $tab_result;
434
			return 1;
435
		}
436
		else
437
		{
438
			// SQL Error
439
			$this->error="Error ".$this->db->lasterror();
440
			return -1;
441
		}
442
	}
443
444
	/**
445
	 *	List all holidays of all users
446
	 *
447
	 *  @param      string	$order      Sort order
448
	 *  @param      string	$filter     SQL Filter
449
	 *  @return     int      			-1 if KO, 1 if OK, 2 if no result
450
	 */
451
	function fetchAll($order,$filter)
452
	{
453
		global $langs;
454
455
		$sql = "SELECT";
456
		$sql.= " cp.rowid,";
457
458
		$sql.= " cp.fk_user,";
459
		$sql.= " cp.fk_type,";
460
		$sql.= " cp.date_create,";
461
		$sql.= " cp.description,";
462
		$sql.= " cp.date_debut,";
463
		$sql.= " cp.date_fin,";
464
		$sql.= " cp.halfday,";
465
		$sql.= " cp.statut,";
466
		$sql.= " cp.fk_validator,";
467
		$sql.= " cp.date_valid,";
468
		$sql.= " cp.fk_user_valid,";
469
		$sql.= " cp.date_refuse,";
470
		$sql.= " cp.fk_user_refuse,";
471
		$sql.= " cp.date_cancel,";
472
		$sql.= " cp.fk_user_cancel,";
473
		$sql.= " cp.detail_refuse,";
474
475
		$sql.= " uu.lastname as user_lastname,";
476
		$sql.= " uu.firstname as user_firstname,";
477
		$sql.= " uu.login as user_login,";
478
		$sql.= " uu.statut as user_statut,";
479
		$sql.= " uu.photo as user_photo,";
480
481
		$sql.= " ua.lastname as validator_lastname,";
482
		$sql.= " ua.firstname as validator_firstname,";
483
		$sql.= " ua.login as validator_login,";
484
		$sql.= " ua.statut as validator_statut,";
485
		$sql.= " ua.photo as validator_photo";
486
487
		$sql.= " FROM ".MAIN_DB_PREFIX."holiday as cp, ".MAIN_DB_PREFIX."user as uu, ".MAIN_DB_PREFIX."user as ua";
488
		$sql.= " WHERE cp.entity IN (".getEntity('holiday').")";
489
		$sql.= " AND cp.fk_user = uu.rowid AND cp.fk_validator = ua.rowid "; // Hack pour la recherche sur le tableau
490
491
		// Selection filtering
492
		if(!empty($filter)) {
493
			$sql.= $filter;
494
		}
495
496
		// order of display
497
		if(!empty($order)) {
498
			$sql.= $order;
499
		}
500
501
		dol_syslog(get_class($this)."::fetchAll", LOG_DEBUG);
502
		$resql=$this->db->query($sql);
503
504
		// If no SQL error
505
		if ($resql) {
506
507
			$i = 0;
508
			$tab_result = $this->holiday;
509
			$num = $this->db->num_rows($resql);
510
511
			// If no registration
512
			if(!$num) {
513
				return 2;
514
			}
515
516
			// List the records and add them to the table
517
			while($i < $num) {
518
519
				$obj = $this->db->fetch_object($resql);
520
521
				$tab_result[$i]['rowid'] = $obj->rowid;
522
				$tab_result[$i]['ref'] = $obj->rowid;
523
				$tab_result[$i]['fk_user'] = $obj->fk_user;
524
				$tab_result[$i]['fk_type'] = $obj->fk_type;
525
				$tab_result[$i]['date_create'] = $this->db->jdate($obj->date_create);
526
				$tab_result[$i]['description'] = $obj->description;
527
				$tab_result[$i]['date_debut'] = $this->db->jdate($obj->date_debut);
528
				$tab_result[$i]['date_fin'] = $this->db->jdate($obj->date_fin);
529
				$tab_result[$i]['date_debut_gmt'] = $this->db->jdate($obj->date_debut,1);
530
				$tab_result[$i]['date_fin_gmt'] = $this->db->jdate($obj->date_fin,1);
531
				$tab_result[$i]['halfday'] = $obj->halfday;
532
				$tab_result[$i]['statut'] = $obj->statut;
533
				$tab_result[$i]['fk_validator'] = $obj->fk_validator;
534
				$tab_result[$i]['date_valid'] = $this->db->jdate($obj->date_valid);
535
				$tab_result[$i]['fk_user_valid'] = $obj->fk_user_valid;
536
				$tab_result[$i]['date_refuse'] = $obj->date_refuse;
537
				$tab_result[$i]['fk_user_refuse'] = $obj->fk_user_refuse;
538
				$tab_result[$i]['date_cancel'] = $obj->date_cancel;
539
				$tab_result[$i]['fk_user_cancel'] = $obj->fk_user_cancel;
540
				$tab_result[$i]['detail_refuse'] = $obj->detail_refuse;
541
542
				$tab_result[$i]['user_firstname'] = $obj->user_firstname;
543
				$tab_result[$i]['user_lastname'] = $obj->user_lastname;
544
				$tab_result[$i]['user_login'] = $obj->user_login;
545
				$tab_result[$i]['user_statut'] = $obj->user_statut;
546
				$tab_result[$i]['user_photo'] = $obj->user_photo;
547
548
				$tab_result[$i]['validator_firstname'] = $obj->validator_firstname;
549
				$tab_result[$i]['validator_lastname'] = $obj->validator_lastname;
550
				$tab_result[$i]['validator_login'] = $obj->validator_login;
551
				$tab_result[$i]['validator_statut'] = $obj->validator_statut;
552
				$tab_result[$i]['validator_photo'] = $obj->validator_photo;
553
554
				$i++;
555
			}
556
			// Returns 1 and adds the array to the variable
557
			$this->holiday = $tab_result;
558
			return 1;
559
		}
560
		else
561
		{
562
			// SQL Error
563
			$this->error="Error ".$this->db->lasterror();
564
			return -1;
565
		}
566
	}
567
568
	/**
569
	 *	Update database
570
	 *
571
	 *  @param	User	$user        	User that modify
572
	 *  @param  int		$notrigger	    0=launch triggers after, 1=disable triggers
573
	 *  @return int         			<0 if KO, >0 if OK
574
	 */
575
	function update($user=null, $notrigger=0)
576
	{
577
		global $conf, $langs;
578
		$error=0;
579
580
		// Update request
581
		$sql = "UPDATE ".MAIN_DB_PREFIX."holiday SET";
582
583
		$sql.= " description= '".$this->db->escape($this->description)."',";
584
585
		if(!empty($this->date_debut)) {
586
			$sql.= " date_debut = '".$this->db->idate($this->date_debut)."',";
587
		} else {
588
			$error++;
589
		}
590
		if(!empty($this->date_fin)) {
591
			$sql.= " date_fin = '".$this->db->idate($this->date_fin)."',";
592
		} else {
593
			$error++;
594
		}
595
		$sql.= " halfday = ".$this->halfday.",";
596
		if(!empty($this->statut) && is_numeric($this->statut)) {
597
			$sql.= " statut = ".$this->statut.",";
598
		} else {
599
			$error++;
600
		}
601
		if(!empty($this->fk_validator)) {
602
			$sql.= " fk_validator = '".$this->db->escape($this->fk_validator)."',";
603
		} else {
604
			$error++;
605
		}
606
		if(!empty($this->date_valid)) {
607
			$sql.= " date_valid = '".$this->db->idate($this->date_valid)."',";
608
		} else {
609
			$sql.= " date_valid = NULL,";
610
		}
611
		if(!empty($this->fk_user_valid)) {
612
			$sql.= " fk_user_valid = '".$this->db->escape($this->fk_user_valid)."',";
613
		} else {
614
			$sql.= " fk_user_valid = NULL,";
615
		}
616
		if(!empty($this->date_refuse)) {
617
			$sql.= " date_refuse = '".$this->db->idate($this->date_refuse)."',";
618
		} else {
619
			$sql.= " date_refuse = NULL,";
620
		}
621
		if(!empty($this->fk_user_refuse)) {
622
			$sql.= " fk_user_refuse = '".$this->db->escape($this->fk_user_refuse)."',";
623
		} else {
624
			$sql.= " fk_user_refuse = NULL,";
625
		}
626
		if(!empty($this->date_cancel)) {
627
			$sql.= " date_cancel = '".$this->db->idate($this->date_cancel)."',";
628
		} else {
629
			$sql.= " date_cancel = NULL,";
630
		}
631
		if(!empty($this->fk_user_cancel)) {
632
			$sql.= " fk_user_cancel = '".$this->db->escape($this->fk_user_cancel)."',";
633
		} else {
634
			$sql.= " fk_user_cancel = NULL,";
635
		}
636
		if(!empty($this->detail_refuse)) {
637
			$sql.= " detail_refuse = '".$this->db->escape($this->detail_refuse)."'";
638
		} else {
639
			$sql.= " detail_refuse = NULL";
640
		}
641
642
		$sql.= " WHERE rowid= ".$this->id;
643
644
		$this->db->begin();
645
646
		dol_syslog(get_class($this)."::update", LOG_DEBUG);
647
		$resql = $this->db->query($sql);
648
		if (! $resql) {
649
			$error++; $this->errors[]="Error ".$this->db->lasterror();
650
		}
651
652
		if (! $error)
653
		{
654
			if (! $notrigger)
655
			{
656
				// Call trigger
657
				$result=$this->call_trigger('HOLIDAY_MODIFY',$user);
658
				if ($result < 0) { $error++; }
659
				// End call triggers
660
			}
661
		}
662
663
		// Commit or rollback
664
		if ($error)
665
		{
666
			foreach($this->errors as $errmsg)
667
			{
668
				dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
669
				$this->error.=($this->error?', '.$errmsg:$errmsg);
670
			}
671
			$this->db->rollback();
672
			return -1*$error;
673
		}
674
		else
675
		{
676
			$this->db->commit();
677
			return 1;
678
		}
679
	}
680
681
682
	/**
683
	 *   Delete object in database
684
	 *
685
	 *	 @param		User	$user        	User that delete
686
	 *   @param     int		$notrigger	    0=launch triggers after, 1=disable triggers
687
	 *	 @return	int						<0 if KO, >0 if OK
688
	 */
689
	function delete($user, $notrigger=0)
690
	{
691
		global $conf, $langs;
692
		$error=0;
693
694
		$sql = "DELETE FROM ".MAIN_DB_PREFIX."holiday";
695
		$sql.= " WHERE rowid=".$this->id;
696
697
		$this->db->begin();
698
699
		dol_syslog(get_class($this)."::delete", LOG_DEBUG);
700
		$resql = $this->db->query($sql);
701
		if (! $resql) {
702
			$error++; $this->errors[]="Error ".$this->db->lasterror();
703
		}
704
705
		if (! $error)
706
		{
707
			if (! $notrigger)
708
			{
709
				// Call trigger
710
				$result=$this->call_trigger('HOLIDAY_DELETE',$user);
711
				if ($result < 0) { $error++; }
712
				// End call triggers
713
			}
714
		}
715
716
		// Commit or rollback
717
		if ($error)
718
		{
719
			foreach($this->errors as $errmsg)
720
			{
721
				dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
722
				$this->error.=($this->error?', '.$errmsg:$errmsg);
723
			}
724
			$this->db->rollback();
725
			return -1*$error;
726
		}
727
		else
728
		{
729
			$this->db->commit();
730
			return 1;
731
		}
732
	}
733
734
	/**
735
	 *	Check if a user is on holiday (partially or completely) into a period.
736
	 *  This function can be used to avoid to have 2 leave requests on same period for example.
737
	 *  Warning: It consumes a lot of memory because it load in ->holiday all holiday of a dedicated user at each call.
738
	 *
739
	 * 	@param 	int		$fk_user		Id user
740
	 * 	@param 	date	$dateStart		Start date of period to check
741
	 * 	@param 	date	$dateEnd		End date of period to check
742
	 *  @param	int		$halfday		Tag to define how start and end the period to check:
743
	 *  	    						0:Full days, 2:Start afternoon end morning, -1:Start afternoon end afternoon, 1:Start morning end morning
744
	 * 	@return boolean					False = New range overlap an existing holiday, True = no overlapping (is never on holiday during checked period).
745
	 *  @see verifDateHolidayForTimestamp
746
	 */
747
	function verifDateHolidayCP($fk_user, $dateStart, $dateEnd, $halfday=0)
748
	{
749
		$this->fetchByUser($fk_user,'','');
750
751
		foreach($this->holiday as $infos_CP)
752
		{
753
			if ($infos_CP['statut'] == 4) continue;		// ignore not validated holidays
754
			if ($infos_CP['statut'] == 5) continue;		// ignore not validated holidays
755
			/*
756
			 var_dump("--");
757
			 var_dump("old: ".dol_print_date($infos_CP['date_debut'],'dayhour').' '.dol_print_date($infos_CP['date_fin'],'dayhour').' '.$infos_CP['halfday']);
758
			 var_dump("new: ".dol_print_date($dateStart,'dayhour').' '.dol_print_date($dateEnd,'dayhour').' '.$halfday);
759
			 */
760
761
			if ($halfday == 0)
762
			{
763
				if ($dateStart >= $infos_CP['date_debut'] && $dateStart <= $infos_CP['date_fin'])
764
				{
765
					return false;
766
				}
767
				if ($dateEnd <= $infos_CP['date_fin'] && $dateEnd >= $infos_CP['date_debut'])
768
				{
769
					return false;
770
				}
771
			}
772
			elseif ($halfday == -1)
773
			{
774
				// new start afternoon, new end afternoon
775
				if ($dateStart >= $infos_CP['date_debut'] && $dateStart <= $infos_CP['date_fin'])
776
				{
777
					if ($dateStart < $infos_CP['date_fin'] || in_array($infos_CP['halfday'], array(0, -1))) return false;
778
				}
779
				if ($dateEnd <= $infos_CP['date_fin'] && $dateEnd >= $infos_CP['date_debut'])
780
				{
781
					if ($dateStart < $dateEnd) return false;
782
					if ($dateEnd < $infos_CP['date_fin'] || in_array($infos_CP['halfday'], array(0, -1))) return false;
783
				}
784
			}
785
			elseif ($halfday == 1)
786
			{
787
				// new start morning, new end morning
788
				if ($dateStart >= $infos_CP['date_debut'] && $dateStart <= $infos_CP['date_fin'])
789
				{
790
					if ($dateStart < $dateEnd) return false;
791
					if ($dateStart > $infos_CP['date_debut'] || in_array($infos_CP['halfday'], array(0, 1))) return false;
792
				}
793
				if ($dateEnd <= $infos_CP['date_fin'] && $dateEnd >= $infos_CP['date_debut'])
794
				{
795
					if ($dateEnd > $infos_CP['date_debut'] || in_array($infos_CP['halfday'], array(0, 1))) return false;
796
				}
797
			}
798
			elseif ($halfday == 2)
799
			{
800
				// new start afternoon, new end morning
801
				if ($dateStart >= $infos_CP['date_debut'] && $dateStart <= $infos_CP['date_fin'])
802
				{
803
					if ($dateStart < $infos_CP['date_fin'] || in_array($infos_CP['halfday'], array(0, -1))) return false;
804
				}
805
				if ($dateEnd <= $infos_CP['date_fin'] && $dateEnd >= $infos_CP['date_debut'])
806
				{
807
					if ($dateEnd > $infos_CP['date_debut'] || in_array($infos_CP['halfday'], array(0, 1))) return false;
808
				}
809
			}
810
			else
811
			{
812
				dol_print_error('', 'Bad value of parameter halfday when calling function verifDateHolidayCP');
813
			}
814
		}
815
816
		return true;
817
	}
818
819
820
	/**
821
	 *	Check that a user is not on holiday for a particular timestamp
822
	 *
823
	 * 	@param 	int			$fk_user				Id user
824
	 *  @param	timestamp	$timestamp				Time stamp date for a day (YYYY-MM-DD) without hours  (= 12:00AM in english and not 12:00PM that is 12:00)
825
	 *  @param	string		$status					Filter on holiday status. '-1' = no filter.
826
	 * 	@return array								array('morning'=> ,'afternoon'=> ), Boolean is true if user is available for day timestamp.
827
	 *  @see verifDateHolidayCP
828
	 */
829
	function verifDateHolidayForTimestamp($fk_user, $timestamp, $status='-1')
830
	{
831
		global $langs, $conf;
832
833
		$isavailablemorning=true;
834
		$isavailableafternoon=true;
835
836
		$sql = "SELECT cp.rowid, cp.date_debut as date_start, cp.date_fin as date_end, cp.halfday, cp.statut";
837
		$sql.= " FROM ".MAIN_DB_PREFIX."holiday as cp";
838
		$sql.= " WHERE cp.entity IN (".getEntity('holiday').")";
839
		$sql.= " AND cp.fk_user = ".(int) $fk_user;
840
		$sql.= " AND cp.date_debut <= '".$this->db->idate($timestamp)."' AND cp.date_fin >= '".$this->db->idate($timestamp)."'";
841
		if ($status != '-1') $sql.=" AND cp.statut IN (".$this->db->escape($status).")";
842
843
		$resql = $this->db->query($sql);
844
		if ($resql)
845
		{
846
			$num_rows = $this->db->num_rows($resql);	// Note, we can have 2 records if on is morning and the other one is afternoon
847
			if ($num_rows > 0)
848
			{
849
				$arrayofrecord=array();
850
				$i=0;
851
				while ($i < $num_rows)
852
				{
853
					$obj = $this->db->fetch_object($resql);
854
855
					// Note: $obj->halfday is  0:Full days, 2:Sart afternoon end morning, -1:Start afternoon, 1:End morning
856
					$arrayofrecord[$obj->rowid]=array('date_start'=>$this->db->jdate($obj->date_start), 'date_end'=>$this->db->jdate($obj->date_end), 'halfday'=>$obj->halfday);
857
					$i++;
858
				}
859
860
				// We found a record, user is on holiday by default, so is not available is true.
861
				$isavailablemorning = true;
862
				foreach($arrayofrecord as $record)
863
				{
864
					if ($timestamp == $record['date_start'] && $record['halfday'] == 2)  continue;
865
					if ($timestamp == $record['date_start'] && $record['halfday'] == -1) continue;
866
					$isavailablemorning = false;
867
					break;
868
				}
869
				$isavailableafternoon = true;
870
				foreach($arrayofrecord as $record)
871
				{
872
					if ($timestamp == $record['date_end'] && $record['halfday'] == 2) continue;
873
					if ($timestamp == $record['date_end'] && $record['halfday'] == 1) continue;
874
					$isavailableafternoon = false;
875
					break;
876
				}
877
			}
878
		}
879
		else dol_print_error($this->db);
880
881
		return array('morning'=>$isavailablemorning, 'afternoon'=>$isavailableafternoon);
882
	}
883
884
885
	/**
886
	 *	Return clicable name (with picto eventually)
887
	 *
888
	 *	@param	int			$withpicto					0=_No picto, 1=Includes the picto in the linkn, 2=Picto only
889
	 *  @param  int     	$save_lastsearch_value    	-1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
890
	 *	@return	string									String with URL
891
	 */
892
	function getNomUrl($withpicto=0, $save_lastsearch_value=-1)
893
	{
894
		global $langs;
895
896
		$result='';
897
898
		$label=$langs->trans("Show").': '.$this->ref;
899
900
		$url = DOL_URL_ROOT.'/holiday/card.php?id='.$this->id;
901
902
		//if ($option != 'nolink')
903
		//{
904
		// Add param to save lastsearch_values or not
905
		$add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
906
		if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
907
		if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1';
908
		//}
909
910
		$linkstart = '<a href="'.$url.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
911
		$linkend='</a>';
912
913
		$result .= $linkstart;
914
		if ($withpicto) $result.=img_object(($notooltip?'':$label), $this->picto, ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip?0:1);
0 ignored issues
show
Bug introduced by
The variable $notooltip does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
915
		if ($withpicto != 2) $result.= $this->ref;
916
		$result .= $linkend;
917
918
		return $result;
919
	}
920
921
922
	/**
923
	 *	Returns the label status
924
	 *
925
	 *	@param      int		$mode       0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
926
	 *	@return     string      		Label
927
	 */
928
	function getLibStatut($mode=0)
929
	{
930
		return $this->LibStatut($this->statut, $mode, $this->date_debut);
931
	}
932
933
	/**
934
	 *	Returns the label of a statut
935
	 *
936
	 *	@param      int		$statut     id statut
937
	 *	@param      int		$mode       0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
938
	 *  @param		date	$startdate	Date holiday should start
939
	 *	@return     string      		Label
940
	 */
941
    // phpcs:ignore PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
942
	function LibStatut($statut, $mode=0, $startdate='')
943
	{
944
		global $langs;
945
946
		if ($mode == 0)
947
		{
948
			if ($statut == 1) return $langs->trans('DraftCP');
949
			elseif ($statut == 2) return $langs->trans('ToReviewCP');
950
			elseif ($statut == 3) return $langs->trans('ApprovedCP');
951
			elseif ($statut == 4) return $langs->trans('CancelCP');
952
			elseif ($statut == 5) return $langs->trans('RefuseCP');
953
		}
954
		elseif ($mode == 2)
955
		{
956
			$pictoapproved='statut6';
957
			if (! empty($startdate) && $startdate > dol_now()) $pictoapproved='statut4';
958
			if ($statut == 1) return img_picto($langs->trans('DraftCP'),'statut0').' '.$langs->trans('DraftCP');				// Draft
959
			elseif ($statut == 2) return img_picto($langs->trans('ToReviewCP'),'statut1').' '.$langs->trans('ToReviewCP');		// Waiting approval
960
			elseif ($statut == 3) return img_picto($langs->trans('ApprovedCP'),$pictoapproved).' '.$langs->trans('ApprovedCP');
961
			elseif ($statut == 4) return img_picto($langs->trans('CancelCP'),'statut5').' '.$langs->trans('CancelCP');
962
			elseif ($statut == 5) return img_picto($langs->trans('RefuseCP'),'statut5').' '.$langs->trans('RefuseCP');
963
		}
964
		elseif ($mode == 3)
965
		{
966
			$pictoapproved='statut6';
967
			if (! empty($startdate) && $startdate > dol_now()) $pictoapproved='statut4';
968
			if ($statut == 1) return img_picto($langs->trans('DraftCP'),'statut0');
969
			elseif ($statut == 2) return img_picto($langs->trans('ToReviewCP'),'statut1');
970
			elseif ($statut == 3) return img_picto($langs->trans('ApprovedCP'),$pictoapproved);
971
			elseif ($statut == 4) return img_picto($langs->trans('CancelCP'),'statut5');
972
			elseif ($statut == 5) return img_picto($langs->trans('RefuseCP'),'statut5');
973
		}
974
		elseif ($mode == 5)
975
		{
976
			$pictoapproved='statut6';
977
			if (! empty($startdate) && $startdate > dol_now()) $pictoapproved='statut4';
978
			if ($statut == 1) return $langs->trans('DraftCP').' '.img_picto($langs->trans('DraftCP'),'statut0');				// Draft
979
			elseif ($statut == 2) return $langs->trans('ToReviewCP').' '.img_picto($langs->trans('ToReviewCP'),'statut1');		// Waiting approval
980
			elseif ($statut == 3) return $langs->trans('ApprovedCP').' '.img_picto($langs->trans('ApprovedCP'),$pictoapproved);
981
			elseif ($statut == 4) return $langs->trans('CancelCP').' '.img_picto($langs->trans('CancelCP'),'statut5');
982
			elseif ($statut == 5) return $langs->trans('RefuseCP').' '.img_picto($langs->trans('RefuseCP'),'statut5');
983
		}
984
		elseif ($mode == 6)
985
		{
986
			$pictoapproved='statut6';
987
			if (! empty($startdate) && $startdate > dol_now()) $pictoapproved='statut4';
988
			if ($statut == 1) return $langs->trans('DraftCP').' '.img_picto($langs->trans('DraftCP'),'statut0');				// Draft
989
			elseif ($statut == 2) return $langs->trans('ToReviewCP').' '.img_picto($langs->trans('ToReviewCP'),'statut1');		// Waiting approval
990
			elseif ($statut == 3) return $langs->trans('ApprovedCP').' '.img_picto($langs->trans('ApprovedCP'),$pictoapproved);
991
			elseif ($statut == 4) return $langs->trans('CancelCP').' '.img_picto($langs->trans('CancelCP'),'statut5');
992
			elseif ($statut == 5) return $langs->trans('RefuseCP').' '.img_picto($langs->trans('RefuseCP'),'statut5');
993
		}
994
995
		else return $statut;
996
	}
997
998
999
	/**
1000
	 *   Affiche un select HTML des statuts de congés payés
1001
	 *
1002
	 *   @param 	int		$selected   	Id of preselected status
1003
	 *   @param		string	$htmlname		Name of HTML select field
1004
	 *   @return    string					Show select of status
1005
	 */
1006
    function selectStatutCP($selected='', $htmlname='select_statut')
1007
    {
1008
1009
		global $langs;
1010
1011
		// Liste des statuts
1012
		$name = array('DraftCP','ToReviewCP','ApprovedCP','CancelCP','RefuseCP');
1013
		$nb = count($name)+1;
1014
1015
		// Select HTML
1016
		$statut = '<select name="'.$htmlname.'" class="flat">'."\n";
1017
		$statut.= '<option value="-1">&nbsp;</option>'."\n";
1018
1019
		// Boucle des statuts
1020
		for($i=1; $i < $nb; $i++) {
1021
			if($i==$selected) {
1022
				$statut.= '<option value="'.$i.'" selected>'.$langs->trans($name[$i-1]).'</option>'."\n";
1023
			}
1024
			else {
1025
				$statut.= '<option value="'.$i.'">'.$langs->trans($name[$i-1]).'</option>'."\n";
1026
			}
1027
		}
1028
1029
		$statut.= '</select>'."\n";
1030
		print $statut;
1031
	}
1032
1033
	/**
1034
	 *  Met à jour une option du module Holiday Payés
1035
	 *
1036
	 *  @param	string	$name       name du paramètre de configuration
1037
	 *  @param	string	$value      vrai si mise à jour OK sinon faux
1038
	 *  @return boolean				ok or ko
1039
	 */
1040
    function updateConfCP($name,$value)
1041
    {
1042
1043
		$sql = "UPDATE ".MAIN_DB_PREFIX."holiday_config SET";
1044
		$sql.= " value = '".$value."'";
1045
		$sql.= " WHERE name = '".$name."'";
1046
1047
		dol_syslog(get_class($this).'::updateConfCP name='.$name.'', LOG_DEBUG);
1048
		$result = $this->db->query($sql);
1049
		if($result) {
1050
			return true;
1051
		}
1052
1053
		return false;
1054
	}
1055
1056
	/**
1057
	 *  Return value of a conf parameterfor leave module
1058
	 *  TODO Move this into llx_const table
1059
	 *
1060
	 *  @param	string	$name                 Name of parameter
1061
	 *  @param  string  $createifnotfound     'stringvalue'=Create entry with string value if not found. For example 'YYYYMMDDHHMMSS'.
1062
	 *  @return string      		          Value of parameter. Example: 'YYYYMMDDHHMMSS' or < 0 if error
1063
	 */
1064
	function getConfCP($name, $createifnotfound='')
1065
	{
1066
		$sql = "SELECT value";
1067
		$sql.= " FROM ".MAIN_DB_PREFIX."holiday_config";
1068
		$sql.= " WHERE name = '".$this->db->escape($name)."'";
1069
1070
		dol_syslog(get_class($this).'::getConfCP name='.$name.' createifnotfound='.$createifnotfound, LOG_DEBUG);
1071
		$result = $this->db->query($sql);
1072
1073
		if($result) {
1074
1075
			$obj = $this->db->fetch_object($result);
1076
			// Return value
1077
			if (empty($obj))
1078
			{
1079
				if ($createifnotfound)
1080
				{
1081
					$sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_config(name, value)";
1082
					$sql.= " VALUES('".$this->db->escape($name)."', '".$this->db->escape($createifnotfound)."')";
1083
					$result = $this->db->query($sql);
1084
					if ($result)
1085
					{
1086
						return $createifnotfound;
1087
					}
1088
					else
1089
					{
1090
						$this->error=$this->db->lasterror();
1091
						return -2;
1092
					}
1093
				}
1094
				else
1095
				{
1096
					return '';
1097
				}
1098
			}
1099
			else
1100
			{
1101
				return $obj->value;
1102
			}
1103
		} else {
1104
1105
			// Erreur SQL
1106
			$this->error=$this->db->lasterror();
1107
			return -1;
1108
		}
1109
	}
1110
1111
	/**
1112
	 *	Met à jour le timestamp de la dernière mise à jour du solde des CP
1113
	 *
1114
	 *	@param		int		$userID		Id of user
1115
	 *	@param		int		$nbHoliday	Nb of days
1116
	 *  @param		int		$fk_type	Type of vacation
1117
	 *  @return     int					0=Nothing done, 1=OK, -1=KO
1118
	 */
1119
	function updateSoldeCP($userID='',$nbHoliday='', $fk_type='')
1120
	{
1121
		global $user, $langs;
1122
1123
		$error = 0;
1124
1125
		if (empty($userID) && empty($nbHoliday) && empty($fk_type))
1126
		{
1127
			$langs->load("holiday");
1128
1129
			// Si mise à jour pour tout le monde en début de mois
1130
			$now=dol_now();
1131
1132
			$month = date('m',$now);
1133
			$newdateforlastupdate = dol_print_date($now, '%Y%m%d%H%M%S');
1134
1135
			// Get month of last update
1136
			$lastUpdate = $this->getConfCP('lastUpdate', $newdateforlastupdate);
1137
			$monthLastUpdate = $lastUpdate[4].$lastUpdate[5];
1138
			//print 'month: '.$month.' lastUpdate:'.$lastUpdate.' monthLastUpdate:'.$monthLastUpdate;exit;
1139
1140
			// Si la date du mois n'est pas la même que celle sauvegardée, on met à jour le timestamp
1141
			if ($month != $monthLastUpdate)
1142
			{
1143
				$this->db->begin();
1144
1145
				$users = $this->fetchUsers(false,false);
1146
				$nbUser = count($users);
1147
1148
				$sql = "UPDATE ".MAIN_DB_PREFIX."holiday_config SET";
1149
				$sql.= " value = '".$this->db->escape($newdateforlastupdate)."'";
1150
				$sql.= " WHERE name = 'lastUpdate'";
1151
				$result = $this->db->query($sql);
1152
1153
				$typeleaves=$this->getTypes(1,1);
1154
				foreach($typeleaves as $key => $val)
1155
				{
1156
					// On ajoute x jours à chaque utilisateurs
1157
					$nb_holiday = $val['newByMonth'];
1158
					if (empty($nb_holiday)) $nb_holiday=0;
1159
1160
					if ($nb_holiday > 0)
1161
					{
1162
						dol_syslog("We update leavefor everybody for type ".$key, LOG_DEBUG);
1163
1164
						$i = 0;
1165
						while ($i < $nbUser)
1166
						{
1167
							$now_holiday = $this->getCPforUser($users[$i]['rowid'], $val['rowid']);
1168
							$new_solde = $now_holiday + $nb_holiday;
1169
1170
							// We add a log for each user
1171
							$this->addLogCP($user->id, $users[$i]['rowid'], $langs->trans('HolidaysMonthlyUpdate'), $new_solde, $val['rowid']);
1172
1173
							$i++;
1174
						}
1175
1176
						// Now we update counter for all users at once
1177
						$sql2 = "UPDATE ".MAIN_DB_PREFIX."holiday_users SET";
1178
						$sql2.= " nb_holiday = nb_holiday + ".$nb_holiday;
1179
						$sql2.= " WHERE fk_type = ".$val['rowid'];
1180
1181
						$result= $this->db->query($sql2);
1182
1183
						if (! $result)
1184
						{
1185
							dol_print_error($this->db);
1186
							break;
1187
						}
1188
					}
1189
					else dol_syslog("No change for leave of type ".$key, LOG_DEBUG);
1190
				}
1191
1192
				if ($result)
1193
				{
1194
					$this->db->commit();
1195
					return 1;
1196
				}
1197
				else
1198
				{
1199
					$this->db->rollback();
1200
					return -1;
1201
				}
1202
			}
1203
1204
			return 0;
1205
		}
1206
		else
1207
		{
1208
			// Mise à jour pour un utilisateur
1209
			$nbHoliday = price2num($nbHoliday,5);
1210
1211
			$sql = "SELECT nb_holiday FROM ".MAIN_DB_PREFIX."holiday_users";
1212
			$sql.= " WHERE fk_user = '".$userID."' AND fk_type = ".$fk_type;
1213
			$resql = $this->db->query($sql);
1214
			if ($resql)
1215
			{
1216
				$num = $this->db->num_rows($resql);
1217
1218
				if ($num > 0)
1219
				{
1220
					// Update for user
1221
					$sql = "UPDATE ".MAIN_DB_PREFIX."holiday_users SET";
1222
					$sql.= " nb_holiday = ".$nbHoliday;
1223
					$sql.= " WHERE fk_user = '".$userID."' AND fk_type = ".$fk_type;
1224
					$result = $this->db->query($sql);
1225
					if (! $result)
1226
					{
1227
						$error++;
1228
						$this->errors[]=$this->db->lasterror();
1229
					}
1230
				}
1231
				else
1232
				{
1233
					// Insert for user
1234
					$sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_users(nb_holiday, fk_user, fk_type) VALUES (";
1235
					$sql.= $nbHoliday;
1236
					$sql.= ", '".$userID."', ".$fk_type.")";
1237
					$result = $this->db->query($sql);
1238
					if (! $result)
1239
					{
1240
						$error++;
1241
						$this->errors[]=$this->db->lasterror();
1242
					}
1243
				}
1244
			}
1245
			else
1246
			{
1247
				$this->errors[]=$this->db->lasterror();
1248
				$error++;
1249
			}
1250
1251
			if (! $error)
1252
			{
1253
				return 1;
1254
			}
1255
			else
1256
			{
1257
				return -1;
1258
			}
1259
		}
1260
	}
1261
1262
	/**
1263
	 *	Retourne un checked si vrai
1264
	 *
1265
	 *  @param	string	$name       name du paramètre de configuration
1266
	 *  @return string      		retourne checked si > 0
1267
	 */
1268
    function getCheckOption($name)
1269
    {
1270
1271
		$sql = "SELECT value";
1272
		$sql.= " FROM ".MAIN_DB_PREFIX."holiday_config";
1273
		$sql.= " WHERE name = '".$name."'";
1274
1275
		$result = $this->db->query($sql);
1276
1277
		if($result) {
1278
			$obj = $this->db->fetch_object($result);
1279
1280
			// Si la valeur est 1 on retourne checked
1281
			if($obj->value) {
1282
				return 'checked';
1283
			}
1284
		}
1285
	}
1286
1287
1288
	/**
1289
	 *  Créer les entrées pour chaque utilisateur au moment de la configuration
1290
	 *
1291
	 *  @param	boolean		$single		Single
1292
	 *  @param	int			$userid		Id user
1293
	 *  @return void
1294
	 */
1295
	function createCPusers($single=false,$userid='')
1296
	{
1297
		// Si c'est l'ensemble des utilisateurs à ajouter
1298
		if (! $single)
1299
		{
1300
			dol_syslog(get_class($this).'::createCPusers');
1301
			$arrayofusers = $this->fetchUsers(false,true);
1302
1303
			foreach($arrayofusers as $users)
1304
			{
1305
				$sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_users";
1306
				$sql.= " (fk_user, nb_holiday)";
1307
				$sql.= " VALUES ('".$users['rowid']."','0')";
1308
1309
				$resql=$this->db->query($sql);
1310
				if (! $resql) dol_print_error($this->db);
1311
			}
1312
		}
1313
		else
1314
		{
1315
			$sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_users";
1316
			$sql.= " (fk_user, nb_holiday)";
1317
			$sql.= " VALUES ('".$userid."','0')";
1318
1319
			$resql=$this->db->query($sql);
1320
			if (! $resql) dol_print_error($this->db);
1321
		}
1322
	}
1323
1324
	/**
1325
	 *  Supprime un utilisateur du module Congés Payés
1326
	 *
1327
	 *  @param	int		$user_id        ID de l'utilisateur à supprimer
1328
	 *  @return boolean      			Vrai si pas d'erreur, faut si Erreur
1329
	 */
1330
    function deleteCPuser($user_id)
1331
    {
1332
1333
		$sql = "DELETE FROM ".MAIN_DB_PREFIX."holiday_users";
1334
		$sql.= " WHERE fk_user = '".$user_id."'";
1335
1336
		$this->db->query($sql);
1337
	}
1338
1339
1340
	/**
1341
	 *  Retourne le solde de congés payés pour un utilisateur
1342
	 *
1343
	 *  @param	int		$user_id    ID de l'utilisateur
1344
	 *  @param	int		$fk_type	Filter on type
1345
	 *  @return float        		Retourne le solde de congés payés de l'utilisateur
1346
	 */
1347
	function getCPforUser($user_id, $fk_type=0)
1348
	{
1349
		$sql = "SELECT nb_holiday";
1350
		$sql.= " FROM ".MAIN_DB_PREFIX."holiday_users";
1351
		$sql.= " WHERE fk_user = '".$user_id."'";
1352
		if ($fk_type > 0) $sql.=" AND fk_type = ".$fk_type;
1353
1354
		dol_syslog(get_class($this).'::getCPforUser', LOG_DEBUG);
1355
		$result = $this->db->query($sql);
1356
		if($result)
1357
		{
1358
			$obj = $this->db->fetch_object($result);
1359
			//return number_format($obj->nb_holiday,2);
1360
			if ($obj) return $obj->nb_holiday;
1361
			else return null;
1362
		}
1363
		else
1364
		{
1365
			return null;
1366
		}
1367
	}
1368
1369
	/**
1370
	 *    Get list of Users or list of vacation balance.
1371
	 *
1372
	 *    @param      boolean			$stringlist	    If true return a string list of id. If false, return an array with detail.
1373
	 *    @param      boolean   		$type			If true, read Dolibarr user list, if false, return vacation balance list.
1374
	 *    @param      string            $filters        Filters
1375
	 *    @return     array|string|int      			Return an array
1376
	 */
1377
	function fetchUsers($stringlist=true, $type=true, $filters='')
1378
	{
1379
		global $conf;
1380
1381
		dol_syslog(get_class($this)."::fetchUsers", LOG_DEBUG);
1382
1383
		if ($stringlist)
1384
		{
1385
			if ($type)
1386
			{
1387
				// Si utilisateur de Dolibarr
1388
1389
				$sql = "SELECT u.rowid";
1390
				$sql.= " FROM ".MAIN_DB_PREFIX."user as u";
1391
1392
				if (! empty($conf->multicompany->enabled) && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))
1393
				{
1394
					$sql.= ", ".MAIN_DB_PREFIX."usergroup_user as ug";
1395
					$sql.= " WHERE (ug.fk_user = u.rowid";
1396
					$sql.= " AND ug.entity = ".$conf->entity.")";
1397
					$sql.= " OR u.admin = 1";
1398
				}
1399
				else
1400
				{
1401
					$sql.= " WHERE u.entity IN (0,".$conf->entity.")";
1402
				}
1403
				$sql.= " AND u.statut > 0";
1404
				if ($filters) $sql.=$filters;
1405
1406
				$resql=$this->db->query($sql);
1407
1408
				// Si pas d'erreur SQL
1409
				if ($resql) {
1410
1411
					$i = 0;
1412
					$num = $this->db->num_rows($resql);
1413
					$stringlist = '';
1414
1415
					// Boucles du listage des utilisateurs
1416
					while($i < $num)
1417
					{
1418
						$obj = $this->db->fetch_object($resql);
1419
1420
						if ($i == 0) {
1421
							$stringlist.= $obj->rowid;
1422
						} else {
1423
							$stringlist.= ', '.$obj->rowid;
1424
						}
1425
1426
						$i++;
1427
					}
1428
					// Retoune le tableau des utilisateurs
1429
					return $stringlist;
1430
				}
1431
				else
1432
				{
1433
					// Erreur SQL
1434
					$this->error="Error ".$this->db->lasterror();
1435
					return -1;
1436
				}
1437
1438
			}
1439
			else
1440
			{
1441
				// We want only list of vacation balance for user ids
1442
				$sql = "SELECT DISTINCT cpu.fk_user";
1443
				$sql.= " FROM ".MAIN_DB_PREFIX."holiday_users as cpu, ".MAIN_DB_PREFIX."user as u";
1444
				$sql.= " WHERE cpu.fk_user = u.user";
1445
				if ($filters) $sql.=$filters;
1446
1447
				$resql=$this->db->query($sql);
1448
1449
				// Si pas d'erreur SQL
1450
				if ($resql) {
1451
1452
					$i = 0;
1453
					$num = $this->db->num_rows($resql);
1454
					$stringlist = '';
1455
1456
					// Boucles du listage des utilisateurs
1457
					while($i < $num)
1458
					{
1459
						$obj = $this->db->fetch_object($resql);
1460
1461
						if($i == 0) {
1462
							$stringlist.= $obj->fk_user;
1463
						} else {
1464
							$stringlist.= ', '.$obj->fk_user;
1465
						}
1466
1467
						$i++;
1468
					}
1469
					// Retoune le tableau des utilisateurs
1470
					return $stringlist;
1471
				}
1472
				else
1473
				{
1474
					// Erreur SQL
1475
					$this->error="Error ".$this->db->lasterror();
1476
					return -1;
1477
				}
1478
			}
1479
1480
		}
1481
		else
1482
		{ // Si faux donc return array
1483
1484
			// List for Dolibarr users
1485
			if ($type)
1486
			{
1487
				$sql = "SELECT u.rowid, u.lastname, u.firstname, u.gender, u.photo, u.employee, u.statut, u.fk_user";
1488
				$sql.= " FROM ".MAIN_DB_PREFIX."user as u";
1489
1490
				if (! empty($conf->multicompany->enabled) && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))
1491
				{
1492
					$sql.= ", ".MAIN_DB_PREFIX."usergroup_user as ug";
1493
					$sql.= " WHERE (ug.fk_user = u.rowid";
1494
					$sql.= " AND ug.entity = ".$conf->entity.")";
1495
					$sql.= " OR u.admin = 1";
1496
				}
1497
				else
1498
					$sql.= " WHERE u.entity IN (0,".$conf->entity.")";
1499
1500
					$sql.= " AND u.statut > 0";
1501
					if ($filters) $sql.=$filters;
1502
1503
					$resql=$this->db->query($sql);
1504
1505
					// Si pas d'erreur SQL
1506
					if ($resql)
1507
					{
1508
						$i = 0;
1509
						$tab_result = $this->holiday;
1510
						$num = $this->db->num_rows($resql);
1511
1512
						// Boucles du listage des utilisateurs
1513
						while($i < $num) {
1514
1515
							$obj = $this->db->fetch_object($resql);
1516
1517
							$tab_result[$i]['rowid'] = $obj->rowid;
1518
							$tab_result[$i]['name'] = $obj->lastname;       // deprecated
1519
							$tab_result[$i]['lastname'] = $obj->lastname;
1520
							$tab_result[$i]['firstname'] = $obj->firstname;
1521
							$tab_result[$i]['gender'] = $obj->gender;
1522
							$tab_result[$i]['status'] = $obj->statut;
1523
							$tab_result[$i]['employee'] = $obj->employee;
1524
							$tab_result[$i]['photo'] = $obj->photo;
1525
							$tab_result[$i]['fk_user'] = $obj->fk_user;
1526
							//$tab_result[$i]['type'] = $obj->type;
1527
							//$tab_result[$i]['nb_holiday'] = $obj->nb_holiday;
1528
1529
							$i++;
1530
						}
1531
						// Retoune le tableau des utilisateurs
1532
						return $tab_result;
1533
					}
1534
					else
1535
					{
1536
						// Erreur SQL
1537
						$this->errors[]="Error ".$this->db->lasterror();
1538
						return -1;
1539
					}
1540
			}
1541
			else
1542
			{
1543
				// List of vacation balance users
1544
				$sql = "SELECT cpu.fk_user, cpu.fk_type, cpu.nb_holiday, u.lastname, u.firstname, u.gender, u.photo, u.employee, u.statut, u.fk_user";
1545
				$sql.= " FROM ".MAIN_DB_PREFIX."holiday_users as cpu, ".MAIN_DB_PREFIX."user as u";
1546
				$sql.= " WHERE cpu.fk_user = u.rowid";
1547
				if ($filters) $sql.=$filters;
1548
1549
				$resql=$this->db->query($sql);
1550
1551
				// Si pas d'erreur SQL
1552
				if ($resql)
1553
				{
1554
					$i = 0;
1555
					$tab_result = $this->holiday;
1556
					$num = $this->db->num_rows($resql);
1557
1558
					// Boucles du listage des utilisateurs
1559
					while($i < $num)
1560
					{
1561
						$obj = $this->db->fetch_object($resql);
1562
1563
						$tab_result[$i]['rowid'] = $obj->fk_user;
1564
						$tab_result[$i]['name'] = $obj->lastname;			// deprecated
1565
						$tab_result[$i]['lastname'] = $obj->lastname;
1566
						$tab_result[$i]['firstname'] = $obj->firstname;
1567
						$tab_result[$i]['gender'] = $obj->gender;
1568
						$tab_result[$i]['status'] = $obj->statut;
1569
						$tab_result[$i]['employee'] = $obj->employee;
1570
						$tab_result[$i]['photo'] = $obj->photo;
1571
						$tab_result[$i]['fk_user'] = $obj->fk_user;
1572
1573
						$tab_result[$i]['type'] = $obj->type;
1574
						$tab_result[$i]['nb_holiday'] = $obj->nb_holiday;
1575
1576
						$i++;
1577
					}
1578
					// Retoune le tableau des utilisateurs
1579
					return $tab_result;
1580
				}
1581
				else
1582
				{
1583
					// Erreur SQL
1584
					$this->error="Error ".$this->db->lasterror();
1585
					return -1;
1586
				}
1587
			}
1588
		}
1589
	}
1590
1591
1592
	/**
1593
	 * Return list of people with permission to validate leave requests.
1594
	 * Search for permission "approve leave requests"
1595
	 *
1596
	 * @return  array       Array of user ids
1597
	 */
1598
    // phpcs:ignore PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1599
	function fetch_users_approver_holiday()
1600
	{
1601
		$users_validator=array();
1602
1603
		$sql = "SELECT DISTINCT ur.fk_user";
1604
		$sql.= " FROM ".MAIN_DB_PREFIX."user_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd";
1605
		$sql.= " WHERE ur.fk_id = rd.id and rd.module = 'holiday' AND rd.perms = 'approve'";                                              // Permission 'Approve';
1606
		$sql.= "UNION";
1607
		$sql.= " SELECT DISTINCT ugu.fk_user";
1608
		$sql.= " FROM ".MAIN_DB_PREFIX."usergroup_user as ugu, ".MAIN_DB_PREFIX."usergroup_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd";
1609
		$sql.= " WHERE ugu.fk_usergroup = ur.fk_usergroup AND ur.fk_id = rd.id and rd.module = 'holiday' AND rd.perms = 'approve'";       // Permission 'Approve';
1610
		//print $sql;
1611
1612
		dol_syslog(get_class($this)."::fetch_users_approver_holiday sql=".$sql);
1613
		$result = $this->db->query($sql);
1614
		if($result)
1615
		{
1616
			$num_lignes = $this->db->num_rows($result); $i = 0;
1617
			while ($i < $num_lignes)
1618
			{
1619
				$objp = $this->db->fetch_object($result);
1620
				array_push($users_validator,$objp->fk_user);
1621
				$i++;
1622
			}
1623
			return $users_validator;
1624
		}
1625
		else
1626
		{
1627
			$this->error=$this->db->lasterror();
1628
			dol_syslog(get_class($this)."::fetch_users_approver_holiday  Error ".$this->error, LOG_ERR);
1629
			return -1;
1630
		}
1631
	}
1632
1633
1634
	/**
1635
	 *	Compte le nombre d'utilisateur actifs dans Dolibarr
1636
	 *
1637
	 *  @return     int      retourne le nombre d'utilisateur
1638
	 */
1639
	function countActiveUsers()
1640
	{
1641
		$sql = "SELECT count(u.rowid) as compteur";
1642
		$sql.= " FROM ".MAIN_DB_PREFIX."user as u";
1643
		$sql.= " WHERE u.statut > 0";
1644
1645
		$result = $this->db->query($sql);
1646
		$objet = $this->db->fetch_object($result);
1647
1648
		return $objet->compteur;
1649
	}
1650
	/**
1651
	 *	Compte le nombre d'utilisateur actifs dans Dolibarr sans CP
1652
	 *
1653
	 *  @return     int      retourne le nombre d'utilisateur
1654
	 */
1655
    function countActiveUsersWithoutCP()
1656
    {
1657
1658
		$sql = "SELECT count(u.rowid) as compteur";
1659
		$sql.= " FROM ".MAIN_DB_PREFIX."user as u LEFT OUTER JOIN ".MAIN_DB_PREFIX."holiday_users hu ON (hu.fk_user=u.rowid)";
1660
		$sql.= " WHERE u.statut > 0 AND hu.fk_user IS NULL";
1661
1662
		$result = $this->db->query($sql);
1663
		$objet = $this->db->fetch_object($result);
1664
1665
		return $objet->compteur;
1666
	}
1667
1668
	/**
1669
	 *  Compare le nombre d'utilisateur actif de Dolibarr à celui des utilisateurs des congés payés
1670
	 *
1671
	 *  @param    int	$userDolibarrWithoutCP	Number of active users in Dolibarr without holidays
1672
	 *  @param    int	$userCP    				Number of active users into table of holidays
1673
	 *  @return   int							<0 if KO, >0 if OK
1674
	 */
1675
	function verifNbUsers($userDolibarrWithoutCP, $userCP)
1676
	{
1677
		if (empty($userCP)) $userCP=0;
1678
		dol_syslog(get_class($this).'::verifNbUsers userDolibarr='.$userDolibarrWithoutCP.' userCP='.$userCP);
1679
		return 1;
1680
	}
1681
1682
1683
	/**
1684
	 * addLogCP
1685
	 *
1686
	 * @param 	int		$fk_user_action		Id user creation
1687
	 * @param 	int		$fk_user_update		Id user update
1688
	 * @param 	string	$label				Label
1689
	 * @param 	int		$new_solde			New value
1690
	 * @param	int		$fk_type			Type of vacation
1691
	 * @return 	int							Id of record added, 0 if nothing done, < 0 if KO
1692
	 */
1693
	function addLogCP($fk_user_action, $fk_user_update, $label, $new_solde, $fk_type)
1694
	{
1695
		global $conf, $langs;
1696
1697
		$error=0;
1698
1699
		$prev_solde = price2num($this->getCPforUser($fk_user_update, $fk_type), 5);
1700
		$new_solde = price2num($new_solde, 5);
1701
		//print "$prev_solde == $new_solde";
1702
1703
		if ($prev_solde == $new_solde) return 0;
1704
1705
		$this->db->begin();
1706
1707
		// Insert request
1708
		$sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_logs (";
1709
		$sql.= "date_action,";
1710
		$sql.= "fk_user_action,";
1711
		$sql.= "fk_user_update,";
1712
		$sql.= "type_action,";
1713
		$sql.= "prev_solde,";
1714
		$sql.= "new_solde,";
1715
		$sql.= "fk_type";
1716
		$sql.= ") VALUES (";
1717
		$sql.= " '".$this->db->idate(dol_now())."',";
1718
		$sql.= " '".$fk_user_action."',";
1719
		$sql.= " '".$fk_user_update."',";
1720
		$sql.= " '".$this->db->escape($label)."',";
1721
		$sql.= " '".$prev_solde."',";
1722
		$sql.= " '".$new_solde."',";
1723
		$sql.= " ".$fk_type;
1724
		$sql.= ")";
1725
1726
		$resql=$this->db->query($sql);
1727
		if (! $resql)
1728
		{
1729
			$error++; $this->errors[]="Error ".$this->db->lasterror();
1730
		}
1731
1732
		if (! $error)
1733
		{
1734
			$this->optRowid = $this->db->last_insert_id(MAIN_DB_PREFIX."holiday_logs");
1735
		}
1736
1737
		// Commit or rollback
1738
		if ($error)
1739
		{
1740
			foreach($this->errors as $errmsg)
1741
			{
1742
				dol_syslog(get_class($this)."::addLogCP ".$errmsg, LOG_ERR);
1743
				$this->error.=($this->error?', '.$errmsg:$errmsg);
1744
			}
1745
			$this->db->rollback();
1746
			return -1*$error;
1747
		}
1748
		else
1749
		{
1750
			$this->db->commit();
1751
			return $this->optRowid;
1752
		}
1753
	}
1754
1755
	/**
1756
	 *  Liste le log des congés payés
1757
	 *
1758
	 *  @param	string	$order      Filtrage par ordre
1759
	 *  @param  string	$filter     Filtre de séléction
1760
	 *  @return int         		-1 si erreur, 1 si OK et 2 si pas de résultat
1761
	 */
1762
	function fetchLog($order,$filter)
1763
	{
1764
		global $langs;
1765
1766
		$sql = "SELECT";
1767
		$sql.= " cpl.rowid,";
1768
		$sql.= " cpl.date_action,";
1769
		$sql.= " cpl.fk_user_action,";
1770
		$sql.= " cpl.fk_user_update,";
1771
		$sql.= " cpl.type_action,";
1772
		$sql.= " cpl.prev_solde,";
1773
		$sql.= " cpl.new_solde,";
1774
		$sql.= " cpl.fk_type";
1775
		$sql.= " FROM ".MAIN_DB_PREFIX."holiday_logs as cpl";
1776
		$sql.= " WHERE cpl.rowid > 0"; // To avoid error with other search and criteria
1777
1778
		// Filtrage de séléction
1779
		if(!empty($filter)) {
1780
			$sql.= " ".$filter;
1781
		}
1782
1783
		// Ordre d'affichage
1784
		if(!empty($order)) {
1785
			$sql.= " ".$order;
1786
		}
1787
1788
		dol_syslog(get_class($this)."::fetchLog", LOG_DEBUG);
1789
		$resql=$this->db->query($sql);
1790
1791
		// Si pas d'erreur SQL
1792
		if ($resql) {
1793
1794
			$i = 0;
1795
			$tab_result = $this->logs;
1796
			$num = $this->db->num_rows($resql);
1797
1798
			// Si pas d'enregistrement
1799
			if(!$num) {
1800
				return 2;
1801
			}
1802
1803
			// On liste les résultats et on les ajoutent dans le tableau
1804
			while($i < $num) {
1805
1806
				$obj = $this->db->fetch_object($resql);
1807
1808
				$tab_result[$i]['rowid'] = $obj->rowid;
1809
				$tab_result[$i]['date_action'] = $obj->date_action;
1810
				$tab_result[$i]['fk_user_action'] = $obj->fk_user_action;
1811
				$tab_result[$i]['fk_user_update'] = $obj->fk_user_update;
1812
				$tab_result[$i]['type_action'] = $obj->type_action;
1813
				$tab_result[$i]['prev_solde'] = $obj->prev_solde;
1814
				$tab_result[$i]['new_solde'] = $obj->new_solde;
1815
				$tab_result[$i]['fk_type'] = $obj->fk_type;
1816
1817
				$i++;
1818
			}
1819
			// Retourne 1 et ajoute le tableau à la variable
1820
			$this->logs = $tab_result;
1821
			return 1;
1822
		}
1823
		else
1824
		{
1825
			// Erreur SQL
1826
			$this->error="Error ".$this->db->lasterror();
1827
			return -1;
1828
		}
1829
	}
1830
1831
1832
	/**
1833
	 *  Return array with list of types
1834
	 *
1835
	 *  @param		int		$active		Status of type. -1 = Both
1836
	 *  @param		int		$affect		Filter on affect (a request will change sold or not). -1 = Both
1837
	 *  @return     array	    		Return array with list of types
1838
	 */
1839
	function getTypes($active=-1, $affect=-1)
1840
	{
1841
		global $mysoc;
1842
1843
		$sql = "SELECT rowid, code, label, affect, delay, newByMonth";
1844
		$sql.= " FROM " . MAIN_DB_PREFIX . "c_holiday_types";
1845
		$sql.= " WHERE (fk_country IS NULL OR fk_country = ".$mysoc->country_id.')';
1846
		if ($active >= 0) $sql.=" AND active = ".((int) $active);
1847
		if ($affect >= 0) $sql.=" AND affect = ".((int) $affect);
1848
1849
		$result = $this->db->query($sql);
1850
		if ($result)
1851
		{
1852
			$num = $this->db->num_rows($result);
1853
			if ($num)
1854
			{
1855
				while ($obj = $this->db->fetch_object($result))
1856
				{
1857
					$types[$obj->rowid] = array('rowid'=> $obj->rowid, 'code'=> $obj->code, 'label'=>$obj->label, 'affect'=>$obj->affect, 'delay'=>$obj->delay, 'newByMonth'=>$obj->newByMonth);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$types was never initialized. Although not strictly required by PHP, it is generally a good practice to add $types = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
1858
				}
1859
1860
				return $types;
0 ignored issues
show
Bug introduced by
The variable $types does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
1861
			}
1862
		}
1863
		else dol_print_error($this->db);
1864
1865
		return array();
1866
	}
1867
1868
1869
	/**
1870
	 *  Initialise an instance with random values.
1871
	 *  Used to build previews or test instances.
1872
	 *	id must be 0 if object instance is a specimen.
1873
	 *
1874
	 *  @return	void
1875
	 */
1876
	function initAsSpecimen()
1877
	{
1878
		global $user,$langs;
1879
1880
		// Initialise parameters
1881
		$this->id=0;
1882
		$this->specimen=1;
1883
1884
		$this->fk_user=1;
1885
		$this->description='SPECIMEN description';
1886
		$this->date_debut=dol_now();
0 ignored issues
show
Documentation Bug introduced by
The property $date_debut was declared of type string, but dol_now() is of type integer. Maybe add a type cast?

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

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

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
1887
		$this->date_fin=dol_now()+(24*3600);
0 ignored issues
show
Documentation Bug introduced by
The property $date_fin was declared of type string, but dol_now() + 24 * 3600 is of type integer. Maybe add a type cast?

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

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

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
1888
		$this->fk_validator=1;
1889
		$this->halfday=0;
0 ignored issues
show
Documentation Bug introduced by
The property $halfday was declared of type string, but 0 is of type integer. Maybe add a type cast?

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

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

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
1890
		$this->fk_type=1;
1891
	}
1892
}
1893