Completed
Push — master ( 6fc3a1...47798a )
by Paul
03:19
created

absences_RightAct::goToNoBeneficiaries()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 7

Duplication

Lines 9
Ratio 100 %
Metric Value
dl 9
loc 9
rs 9.6666
cc 1
eloc 7
nc 1
nop 1
1
<?php
2
/************************************************************************
3
 * OVIDENTIA http://www.ovidentia.org                                   *
4
 ************************************************************************
5
 * Copyright (c) 2003 by CANTICO ( http://www.cantico.fr )              *
6
 *                                                                      *
7
 * This file is part of Ovidentia.                                      *
8
 *                                                                      *
9
 * Ovidentia is free software; you can redistribute it and/or modify    *
10
 * it under the terms of the GNU General Public License as published by *
11
 * the Free Software Foundation; either version 2, or (at your option)  *
12
 * any later version.													*
13
 *																		*
14
 * This program is distributed in the hope that it will be useful, but  *
15
 * WITHOUT ANY WARRANTY; without even the implied warranty of			*
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.					*
17
 * See the  GNU General Public License for more details.				*
18
 *																		*
19
 * You should have received a copy of the GNU General Public License	*
20
 * along with this program; if not, write to the Free Software			*
21
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,*
22
 * USA.																	*
23
************************************************************************/
24
25
26
require_once dirname(__FILE__).'/right.class.php';
27
require_once dirname(__FILE__).'/type.class.php';
28
require_once dirname(__FILE__).'/movement.class.php';
29
30
31
class absences_RightAct
32
{
33
	private static $post;
34
35
	
36
	
37
	/**
38
	 * Get date from field name
39
	 * @param string $name
40
	 * @return string
41
	 */
42
	private static function getDateValue($name)
43
	{
44
		if (!isset(self::$post[$name]))
45
		{
46
			return '0000-00-00';
47
		}
48
	
49
		$W = bab_Widgets();
50
		$date = $W->DatePicker()->getISODate(self::$post[$name]);
51
	
52
		if (false === $date)
53
		{
54
			return '0000-00-00';
55
		}
56
	
57
		return $date;
58
	}
59
	
60
	
61
	/**
62
	 *
63
	 * @param string $datename		name of datepicker
64
	 * @param string $timename		Name of select contains times values
65
	 * @return string
66
	 */
67
	private static function getDateTimeValue($datename, $timename)
68
	{
69
		if (!isset(self::$post[$datename]))
70
		{
71
			return '0000-00-00 00:00:00';
72
		}
73
	
74
		$W = bab_Widgets();
75
		$date = $W->DatePicker()->getISODate(self::$post[$datename]);
76
	
77
		if (false === $date || '0000-00-00' === $date)
78
		{
79
			return '0000-00-00 00:00:00';
80
		}
81
	
82
		$time = '00:00:00';
83
	
84
		if (isset(self::$post[$timename]))
85
		{
86
			if (8 !== mb_strlen(self::$post[$timename]))
87
			{
88
				return '0000-00-00 00:00:00';
89
			}
90
	
91
			$time = self::$post[$timename];
92
		}
93
	
94
		return $date.' '.$time;
95
	}
96
	
97
	
98
	/**
99
	 * 
100
	 * @param string $begin		Field name
101
	 * @param string $end		Field name
102
	 * @param string $title		title for error message
103
	 * 
104
	 * @return boolean
105
	 */
106
	private static function checkPeriod($begin, $end, $title)
107
	{
108
		global $babBody;
109
		
110
		$date_begin = self::getDateValue($begin);
111
		$date_end = self::getDateValue($end);
112
		
113 View Code Duplication
		if ('0000-00-00' === $date_begin)
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
114
		{
115
			$babBody->addError(sprintf(absences_translate("Invalid start date for the %s"), mb_strtolower($title)));
116
			return false;
117
		}
118
		
119 View Code Duplication
		if ('0000-00-00' === $date_end)
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
120
		{
121
			$babBody->addError(sprintf(absences_translate("Invalid end date for the %s"), mb_strtolower($title)));
122
			return false;
123
		}
124
		
125
		if($date_begin > $date_end )
126
		{
127
			$babBody->addError(sprintf(absences_translate("Begin date must be less than end date in %s"), $title));
128
			return false;
129
		}
130
		
131
		return true;
132
	}
133
	
134
	/**
135
	 * Validate optional period
136
	 * 
137
 	 * @param string $begin		Field name
138
	 * @param string $end		Field name
139
	 * @param string $title		title for error message
140
	 * 
141
	 * @return boolean
142
	 */
143
	private static function checkOptionalPeriod($begin, $end, $title)
144
	{
145
		if ('' === self::$post[$begin] && '' === self::$post[$end])
146
		{
147
			// period not set
148
			return true;
149
		}
150
		
151
		return self::checkPeriod($begin, $end, $title);
152
	}
153
	
154
	
155
	
156
	/**
157
	 * Test posted values before saving
158
	 * @return bool
159
	 */
160
	protected static function checkPost()
161
	{
162
		global $babBody, $babDB;
163
		
164
		
165
		if( empty(self::$post['description']))
166
		{
167
			$babBody->msgerror = absences_translate("You must specify a vacation description");
168
			return false;
169
		}
170
		
171
		$query = "SELECT id FROM absences_rights WHERE description LIKE '".$babDB->db_escape_like(self::$post['description'])."'";
172
		if (!empty(self::$post['id']))
173
		{
174
			$query .= ' AND id<>'.$babDB->quote(self::$post['id']);
175
		}
176
		
177
		$res = $babDB->db_query($query);
178
		if (0 !== $babDB->db_num_rows($res))
179
		{
180
			$babBody->addError(absences_translate("A vacation right with the same name already exists"));
181
			return false;
182
		}
183
		
184
		
185
		if(empty(self::$post['id']))
186
		{
187 View Code Duplication
			if (absences_Right::REPORT === (int) self::$post['kind'])
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
188
			{
189
				$babBody->addError(absences_translate("A report right cannot be created by a manager, they are created automaticaly after expiration of a right"));
190
				return false;
191
			}
192
			
193 View Code Duplication
			if (absences_Right::RECOVERY === (int) self::$post['kind'])
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
194
			{
195
				$babBody->addError(absences_translate("A recovery right cannot be created by a manager, they are created after approval of a workingday entitling recovery"));
196
				return false;
197
			}
198
		}
199
		
200
		
201
		if ((empty(self::$post['date_begin']) || empty(self::$post['date_end'])) && !empty(self::$post['quantity_alert_days']))
202
		{
203
			$babBody->addError(absences_translate("The configuration of an alert depending on the consumed number of days require a valid theoretical period"));
204
			return false;
205
		}
206
		
207
		
208
		if( absences_Right::CET !== (int) self::$post['kind'])
209
		{
210
			// tests de la quantite
211
			
212 View Code Duplication
			if( !is_numeric(self::$post['quantity']))
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
213
			{
214
				$babBody->addError(absences_translate("You must specify a correct quantity"));
215
				return false;
216
			}
217
			
218 View Code Duplication
			if( 0 > (int) self::$post['quantity'])
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
219
			{
220
				$babBody->addError(absences_translate("You must specify a correct quantity"));
221
				return false;
222
			}
223
		}
224
		
225
		if (0 !== (int) self::$post['id_rgroup'])
226
		{
227
			$res = $babDB->db_query("SELECT quantity_unit FROM absences_rgroup WHERE id=".$babDB->quote(self::$post['id_rgroup']));
228
			$rgroup = $babDB->db_fetch_assoc($res);
229
230
			if (!$rgroup || ($rgroup['quantity_unit'] != self::$post['quantity_unit']))
231
			{
232
				$babBody->msgerror = absences_translate("The right quantity unit and the right group quantity unit must be the same");
233
				return false;
234
			}
235
			
236
		}
237
		
238
		if (absences_Right::REGULAR === (int) self::$post['kind'] || absences_Right::INCREMENT === (int) self::$post['kind'])
239
		{
240
			$type = new absences_Type(self::$post['id_type']);
241
			if (!isset($type->cbalance) || ($type->cbalance == 'N' && self::$post['cbalance'] != 'N'))
242
			{
243
				$babBody->msgerror = absences_translate("Negative balance are not allowed with this vacation type");
244
				return false;
245
			}
246
		}
247
		
248
		
249
		if (!self::checkOptionalPeriod('date_begin', 'date_end', absences_translate('theoretical period')))
250
		{
251
			return false;
252
		}
253
		
254
		if (!self::checkOptionalPeriod('date_begin_valid', 'date_end_valid', absences_translate('validity period')))
255
		{
256
			return false;
257
		}
258
		
259
		if (!self::checkOptionalPeriod('trigger_p1_begin', 'trigger_p1_end', absences_translate('first test period')))
260
		{
261
			return false;
262
		}
263
		
264
		if (!self::checkOptionalPeriod('trigger_p2_begin', 'trigger_p2_end', absences_translate('second test period')))
265
		{
266
			return false;
267
		}
268
		
269
		
270
		
271
		
272
		
273
		if(absences_Right::FIXED === (int) self::$post['kind'])
274
		{
275
			// mandatory if fixed vacation
276
			
277
			$date_begin_fixed = self::getDateTimeValue('datebeginfx', 'hourbeginfx');
278
			$date_end_fixed = self::getDateTimeValue('dateendfx', 'hourendfx');
279
			
280
			if ('0000-00-00 00:00:00' === $date_begin_fixed)
281
			{
282
				$babBody->msgerror = absences_translate("Invalid start date for the fixed vacation period");
283
				return false;
284
			}
285
			
286
			if ('0000-00-00 00:00:00' === $date_end_fixed)
287
			{
288
				$babBody->msgerror = absences_translate("Invalid end date for the fixed vacation period");
289
				return false;
290
			}
291
			
292
			if($date_begin_fixed >= $date_end_fixed )
293
			{
294
				$babBody->msgerror = absences_translate("Begin date must be less than end date");
295
				return false;
296
			}
297
			
298
		}
299
		
300
		
301
		return true;
302
	}
303
	
304
	
305
	/**
306
	 * Si le droit est fixe+modifie ou si le droit deviens fixe
307
	 * @param absences_Right $right
308
	 * @return boolean
309
	 */
310
	protected function isFixedModified(absences_Right $right = null)
311
	{
312
		if (absences_Right::FIXED !== (int) self::$post['kind'] || null === $right)
313
		{
314
			return false;
315
		}
316
		
317
		if (absences_Right::FIXED !== $right->getKind())
318
		{
319
			return true;
320
		}
321
		
322
		
323
		if($right->date_begin_fixed != self::getDateTimeValue('datebeginfx', 'hourbeginfx')
324
				|| $right->date_end_fixed != self::getDateTimeValue('dateendfx', 'hourendfx'))
325
		{
326
			return true;
327
		}
328
		
329
		return false;
330
	}
331
	
332
	
333
	
334
	/**
335
	 * Update rights beneficiaries
336
	 * @param absences_Right 		$right
337
	 * @param Widget_ProgressBar 	$progress
338
	 * @param array					$checked_collections
339
	 */
340
	public static function updateCollectionsBeneficiaries(absences_Right $right, Widget_ProgressBar $progress, Array $checked_collections)
341
	{
342
		$already_exists = array();
343
		$I = $right->getCollectionIterator();
344
		
345
		$total = $I->count() + count($checked_collections);
346
		$pos = 1;
347
		$progress->updateProgress(0);
348
		
349
		foreach($I as $collection)
350
		{
351
			/*@var $collection absences_Collection */
352
		    
353
		    
354
			if (!in_array($collection->id, $checked_collections))
355
			{
356
				
357
				try
358
				{
359
					$collection->removeRight($right);
360
					$collection->unlinkAgentsFromRight($right);
361
				} catch (absences_EntryException $e) {
362
					$agent = $e->entry->getAgent();
363
					echo bab_toHtml(sprintf(absences_translate('Failed to update the period for %s, %s (%s)'), 
364
							$agent->getName(), 
365
							$e->getMessage(),
366
							absences_DateTimePeriod($e->entry->date_begin, $e->entry->date_end))
367
					, BAB_HTML_ALL);
368
				}
369
			} else {
370
			    
371
			    
372
				$already_exists[$collection->id] = true;
373
				
374
				// la collection etait deja cochee, il faut creer les demandes pour les agents qui n'en ont pas
375
				$collection->updateAgents($right, $progress);
376
			}
377
			
378
			$p = ($pos * 100) / $total;
379
			$progress->updateProgress($p);
380
			$pos++;
381
		}
382
		
383
		
384
		
385
		
386
		foreach($checked_collections as $id_collection)
387
		{
388
			$p = ($pos * 100) / $total;
389
			$progress->updateProgress($p);
390
			$pos++;
391
			
392
			
393
			if (isset($already_exists[$id_collection]))
394
			{
395
				continue;
396
			}
397
		
398
			$collection = absences_Collection::getById($id_collection);
399
			$collection->addRight($right);
400
			
401
			try {
402
			    $collection->linkAgentsToRight($right, $progress);
403
			}  catch (Exception $e) {
404
			    // ex: l'url vers caldav est vide mais on utilise caldav
405
			    // exception remontee par LibCaldav
406
			    echo bab_toHtml($e->getMessage(), BAB_HTML_ALL);
407
			}
408
		}
409
		
410
		
411
		$progress->updateProgress(100, absences_translate('Finished'));
412
	}
413
414
	
415
	/**
416
	 * Update fixed vacation periods on an existing right
417
	 * 
418
	 */
419
	public static function updateFixed(absences_Right $right, Widget_ProgressBar $progress)
420
	{
421
		global $babDB;
422
		
423
		
424
		$rightusers = array();
425
		foreach($right->getAgentIterator() as $agent)
426
		{
427
			$rightusers[$agent->id_user] = $agent;
428
		}
429
430
		$entriesusers = array();
431
		$res = $babDB->db_query("select 
432
			vet.*, 
433
			veet.id elem,
434
			veet.quantity 
435
				
436
				from absences_entries_elem veet 
437
					left join absences_entries vet on veet.id_entry=vet.id 
438
			where 
439
				veet.id_right=".$babDB->quote($right->id)." 
440
		");
441
		
442
		$remove_total = $babDB->db_num_rows($res);
443
		
444
		if ($remove_total > 0)
445
		{
446
			// dans ce cas on effectue une premiere progression de la gauge pour le nettoyage
447
			$pos = 0;
448
			while( $arr = $babDB->db_fetch_array($res))
449
			{
450
				if (!isset($arr['id']))
451
				{
452
					throw new Exception('missing entry for elem id='.$arr['elem']);
453
				}
454
				
455
				
456
				$entriesusers[$arr['id_user']] = $arr['id'];
457
				if( !isset($rightusers[$arr['id_user']]) )
458
				{
459
					$progress->updateProgress(100*$pos/$remove_total, sprintf(absences_translate('Remove vacation for user %s'), bab_getUserName($arr['id_user'])));
460
					absences_removeFixedVacation($arr['id']);
461
					$arrnotif = array($arr['id_user']);
462
					// remove vacation and notify
463
					absences_notifyOnVacationChange($arrnotif, $arr['quantity'], $arr['date_begin'], $arr['date_end'], ABSENCES_FIX_DELETE);
0 ignored issues
show
Documentation introduced by
$arrnotif is of type array<integer,?,{"0":"?"}>, but the function expects a integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
464
				}
465
				
466
				$pos++;
467
			}
468
		}
469
	
470
		// reset gauge
471
		$progress->updateProgress(0, absences_translate('Add and update vacations'));
472
		$update_total = count($rightusers);
473
		$pos = 0;
474
		
475
		$uupd = array();
476
		$uadd = array();
477
		foreach($rightusers as $ukey => $agent )
478
		{
479
480
			
481
			if( isset($entriesusers[$ukey]))
482
			{
483
				// update
484
				$progress->updateProgress(90*$pos/$update_total, sprintf(absences_translate('Update vacation for user %s'), $agent->getName()));
485
				try 
486
				{
487
					absences_updateFixedVacation($ukey, $right);
488
					$uupd[] = $ukey;
489
				} catch(absences_EntryException $e)
490
				{
491
					echo bab_toHtml(sprintf(absences_translate('Failed to update the period for %s, %s'), $agent->getName(), $e->getMessage()), BAB_HTML_ALL);
492
				}
493
				
494
				
495
			}
496
			else
497
			{
498
				// add
499
				$progress->updateProgress(90*$pos/$update_total, sprintf(absences_translate('Add new vacation for user %s'), bab_getUserName($ukey)));
500
				try {
501
					absences_addFixedVacation($ukey, $right);
502
					$uadd[] = $ukey;
503
				} catch(absences_EntryException $e)
504
				{
505
					echo bab_toHtml(sprintf(absences_translate('Failed to add the period for %s, %s'), $agent->getName(), $e->getMessage()), BAB_HTML_ALL);
506
				}
507
			}
508
			
509
			$pos++;
510
		}
511
	
512 View Code Duplication
		if( count($uupd)> 0 )
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
513
		{
514
			$progress->updateProgress(92, absences_translate('Notify users about the modified vacation'));
515
			absences_notifyOnVacationChange($uupd, $right->quantity, $right->date_begin_fixed,  $right->date_end_fixed, ABSENCES_FIX_UPDATE);
0 ignored issues
show
Documentation introduced by
$uupd is of type array, but the function expects a integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
516
		}
517
		
518 View Code Duplication
		if( count($uadd)> 0 )
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
519
		{
520
			$progress->updateProgress(97, absences_translate('Notify users about the new vacation'));
521
			absences_notifyOnVacationChange($uadd, $right->quantity, $right->date_begin_fixed,  $right->date_end_fixed,  ABSENCES_FIX_ADD);
0 ignored issues
show
Documentation introduced by
$uadd is of type array, but the function expects a integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
522
		}
523
		
524
		$progress->updateProgress(100, absences_translate('Finished'));
525
	}
526
	
527
528
529
	/**
530
	 * Save posted values
531
	 * @return boolean
532
	 */
533
	public static function save()
534
	{
535
		global $babBody, $babDB;
536
	
537
	
538
		self::$post = $_POST['right'];
539
	
540
		
541
		if (!self::checkPost())
542
		{
543
			return false;
544
		}
545
		
546
		
547
		if (absences_Right::CET === ((int) self::$post['kind']) || absences_Right::FIXED === ((int) self::$post['kind']))
548
		{
549
			$use_in_cet = 0;
550
			$cet_quantity = 0.0;
551
		} else {
552
			$use_in_cet = self::$post['use_in_cet'];
553
			$cet_quantity = str_replace(',', '.', self::$post['cet_quantity']);
554
		}
555
		
556
		
557
		
558
		
559
		if (isset(self::$post['report']) && self::$post['report'])
560
		{
561
			$id_report_type = self::$post['id_report_type'];
562
			$date_end_report = self::getDateValue('date_end_report');
563
			$description_report = self::$post['description_report'];
564
		} else {
565
			$id_report_type = 0;
566
			$date_end_report = '0000-00-00';
567
			$description_report = '';
568
		}
569
		
570
		
571
	
572
		if (!empty(self::$post['id']))
573
		{
574
				
575
			$right = new absences_Right(self::$post['id']);
576
			
577
			if (!$right->getRow())
578
			{
579
				// on ne doit pas passer ici, normallement
580
				$babBody->addError(absences_translate("This right does not exists"));
581
				return false;
582
			}
583
	
584 View Code Duplication
			if($right->date_begin_fixed != '0000-00-00 00:00:00' && absences_Right::FIXED !== (int) self::$post['kind'])
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
585
				{
586
				$babBody->addError(absences_translate("A fixed vacation right cannot be changed to another right because vacation entries can be associated with it, please delete the right to remove all vacation entries created by this right"));
587
				return false;
588
			}
589
	
590
			
591
			$fixedModified = self::isFixedModified($right);
592
593
594
			$babDB->db_query("
595
	
596
				UPDATE ".ABSENCES_RIGHTS_TBL."
597
				SET 
598
					kind				=".$babDB->quote(self::$post['kind']).",
599
					description			=".$babDB->quote(self::$post['description']).",
600
					id_creditor			=".$babDB->quote($GLOBALS['BAB_SESS_USERID']).",
601
					id_type				=".$babDB->quote(self::$post['id_type']).",
602
					quantity			=".$babDB->quote(self::$post['quantity']).",
603
					quantity_unit		=".$babDB->quote(self::$post['quantity_unit']).",
604
					date_entry			=curdate(),
605
					date_begin			=".$babDB->quote(self::getDateValue('date_begin')).",
606
					date_end			=".$babDB->quote(self::getDateValue('date_end')).",
607
					active				=".$babDB->quote(self::$post['active']).",
608
					cbalance			=".$babDB->quote(self::$post['cbalance']).",
609
					date_begin_valid	=".$babDB->quote(self::getDateValue('date_begin_valid')).",
610
					date_end_valid		=".$babDB->quote(self::getDateValue('date_end_valid')).",
611
					date_begin_fixed	=".$babDB->quote(self::getDateTimeValue('datebeginfx', 'hourbeginfx')).",
612
					date_end_fixed		=".$babDB->quote(self::getDateTimeValue('dateendfx', 'hourendfx')).",
613
					no_distribution		=".$babDB->quote(self::$post['no_distribution']).",
614
					use_in_cet			=".$babDB->quote($use_in_cet).",
615
					cet_quantity		=".$babDB->quote($cet_quantity).",
616
					id_rgroup			=".$babDB->quote(self::$post['id_rgroup']).",
617
					earlier				=".$babDB->quote(self::$post['earlier']).",
618
				 	earlier_begin_valid =".$babDB->quote(self::$post['earlier_begin_valid']).",
619
				 	earlier_end_valid	=".$babDB->quote(self::$post['earlier_end_valid']).",
620
					later				=".$babDB->quote(self::$post['later']).",
621
					later_begin_valid	=".$babDB->quote(self::$post['later_begin_valid']).",
622
					later_end_valid		=".$babDB->quote(self::$post['later_end_valid']).",
623
					delay_before		=".$babDB->quote(self::$post['delay_before']).",
624
					id_report_type		=".$babDB->quote($id_report_type).", 
625
					date_end_report		=".$babDB->quote($date_end_report).", 
626
					description_report	=".$babDB->quote($description_report).", 
627
					quantity_alert_days	=".$babDB->quote(self::$post['quantity_alert_days']).", 
628
					quantity_alert_types =".$babDB->quote(isset(self::$post['quantity_alert_types']) ? implode(',',self::$post['quantity_alert_types']) : '').", 
629
					quantity_alert_begin =".$babDB->quote(self::getDateValue('quantity_alert_begin')).", 
630
					quantity_alert_end	=".$babDB->quote(self::getDateValue('quantity_alert_end')).", 
631
					quantity_inc_month	=".$babDB->quote(str_replace(',', '.', self::$post['quantity_inc_month'])).",
632
					quantity_inc_max	=".$babDB->quote(str_replace(',', '.', self::$post['quantity_inc_max'])).",
633
					
634
					dynconf_types 		=".$babDB->quote(isset(self::$post['dynconf_types']) ? implode(',',self::$post['dynconf_types']) : '').", 
635
					dynconf_begin 		=".$babDB->quote(self::getDateValue('dynconf_begin')).", 
636
					dynconf_end			=".$babDB->quote(self::getDateValue('dynconf_end')).", 
637
					
638
					require_approval	=".$babDB->quote(self::$post['require_approval'])."  
639
				WHERE 
640
					id=".$babDB->quote(self::$post['id'])."
641
	
642
				");
643
	
644
			$id = self::$post['id'];
645
			
646
			$right->addMovement(sprintf(absences_translate('Vacation right updated : %s'), self::$post['description']));
647
			 
648
			// si la quantite du droit a ete changee, enregistrer un mouvement pour tout les utilisateurs concernes
649
			if (!absences_cq($right->quantity, self::$post['quantity']) || $right->quantity_unit !== self::$post['quantity_unit'])
650
			{
651
				foreach($right->getAgentRightIterator() as $agentRight)
652
				{
653
					/*@var $agentRight absences_AgentRight */
654
					if ($agentRight->quantity == '')
655
					{
656
						$agentRight->addMovement(sprintf(absences_translate('The quantity on right %s has been modified from %s to %s for the user %s'), 
657
								self::$post['description'], 
658
								absences_quantity($right->quantity, $right->quantity_unit),
659
								absences_quantity(self::$post['quantity'], self::$post['quantity_unit']),
660
								$agentRight->getAgent()->getName()
661
						));
662
					}
663
				}
664
			}
665
		}
666
		else
667
		{
668
	
669
			require_once $GLOBALS['babInstallPath'].'utilit/uuid.php';
670
			
671
			$fixedModified = self::isFixedModified(null);
672
			
673
			if (!isset(self::$post['active'])) {
674
				self::$post['active'] = 'N';
675
			}
676
	
677
	
678
			$babDB->db_query("
679
	
680
				INSERT into ".ABSENCES_RIGHTS_TBL."
681
					(
682
					kind,
683
					description,
684
					id_creditor,
685
					id_type,
686
					quantity,
687
					quantity_unit,
688
			        createdOn,
689
					date_entry,
690
					date_begin,
691
					date_end,
692
					active,
693
					cbalance,
694
					date_begin_valid,
695
					date_end_valid,
696
					date_begin_fixed,
697
					date_end_fixed,
698
					no_distribution,
699
					use_in_cet,
700
					cet_quantity,
701
					id_rgroup,
702
					
703
					earlier,
704
				 	earlier_begin_valid,
705
				 	earlier_end_valid,
706
					later,
707
					later_begin_valid,
708
					later_end_valid,
709
					delay_before,
710
					
711
					id_report_type,
712
					date_end_report,
713
					description_report,
714
					quantity_alert_days,
715
					quantity_alert_types,
716
					quantity_alert_begin,
717
					quantity_alert_end,
718
					quantity_inc_month,
719
					quantity_inc_max,
720
					
721
					dynconf_types, 
722
					dynconf_begin,
723
					dynconf_end,
724
					
725
					require_approval,
726
					uuid
727
					)
728
				VALUES 
729
					(
730
					".$babDB->quote(self::$post['kind']).",
731
					".$babDB->quote(self::$post['description']).",
732
					".$babDB->quote($GLOBALS['BAB_SESS_USERID']).",
733
					".$babDB->quote(self::$post['id_type']).",
734
					".$babDB->quote(self::$post['quantity']).",
735
					".$babDB->quote(self::$post['quantity_unit']).",
736
			        curdate(),
737
					curdate(),
738
					".$babDB->quote(self::getDateValue('date_begin')).",
739
					".$babDB->quote(self::getDateValue('date_end')).",
740
					".$babDB->quote(self::$post['active']).",
741
					".$babDB->quote(self::$post['cbalance']).",
742
					".$babDB->quote(self::getDateValue('date_begin_valid')).",
743
					".$babDB->quote(self::getDateValue('date_end_valid')).",
744
					".$babDB->quote(self::getDateTimeValue('datebeginfx', 'hourbeginfx')).",
745
					".$babDB->quote(self::getDateTimeValue('dateendfx', 'hourendfx')).",
746
					".$babDB->quote(self::$post['no_distribution']).",
747
					".$babDB->quote($use_in_cet).",
748
					".$babDB->quote($cet_quantity).",
749
					".$babDB->quote(self::$post['id_rgroup']).",
750
					
751
					".$babDB->quote(self::$post['earlier']).",
752
					".$babDB->quote(self::$post['earlier_begin_valid']).",
753
					".$babDB->quote(self::$post['earlier_end_valid']).",
754
					".$babDB->quote(self::$post['later']).",
755
					".$babDB->quote(self::$post['later_begin_valid']).",
756
					".$babDB->quote(self::$post['later_end_valid']).",
757
					".$babDB->quote(self::$post['delay_before']).",
758
					
759
					".$babDB->quote($id_report_type).",
760
					".$babDB->quote($date_end_report).",
761
					".$babDB->quote($description_report).",
762
					".$babDB->quote(self::$post['quantity_alert_days']).",
763
					".$babDB->quote(isset(self::$post['quantity_alert_types']) ? implode(',',self::$post['quantity_alert_types']) : '').",
764
					".$babDB->quote(self::getDateValue('quantity_alert_begin')).",
765
					".$babDB->quote(self::getDateValue('quantity_alert_end')).",
766
					".$babDB->quote(str_replace(',', '.', self::$post['quantity_inc_month'])).",
767
					".$babDB->quote(str_replace(',', '.', self::$post['quantity_inc_max'])).",
768
					
769
					".$babDB->quote(isset(self::$post['dynconf_types']) ? implode(',',self::$post['dynconf_types']) : '').", 
770
					".$babDB->quote(self::getDateValue('dynconf_begin')).", 
771
					".$babDB->quote(self::getDateValue('dynconf_end')).", 
772
					
773
					".$babDB->quote(self::$post['require_approval']).",
774
					".$babDB->quote(bab_uuid())."
775
					)
776
				");
777
	
778
			$id = $babDB->db_insert_id();
779
			
780
			
781
			$movement = new absences_Movement;
782
			$movement->id_right = $id;
783
			$movement->message = sprintf(absences_translate('Vacation right created : %s'), self::$post['description']);
784
			$movement->save();
785
		}
786
			
787
		self::saveRules($id);
788
		self::saveCet($id);
789
		self::applyDynamicRights($id);
790
		
791
792
		// si aucun beneficiaire, proposer d'en ajouter
793
		$res = $babDB->db_query('SELECT id FROM absences_users_rights WHERE id_right='.$babDB->quote($id));
794
		if ($babDB->db_num_rows($res) === 0)
795
		{
796
			absences_RightAct::goToNoBeneficiaries($id);
797
		}
798
		
799
		
800
		// if fixed, update fixed requests
801
		if ($fixedModified)
802
		{
803
		    absences_RightAct::goToUpdateFixed($id);
804
		}
805
	
806
		
807
		// to list
808
		absences_RightAct::redirect();
809
	}
810
	
811
	
812
	
813
	/**
814
	 * Apply dynamic rights for current beneficiaries
815
	 * @param int $id
816
	 */
817
	protected static function applyDynamicRights($id)
818
	{
819
		$right = new absences_Right($id);
820
		$res = $right->getAgentRightIterator();
821
		
822
		foreach($res as $agentRight)
823
		{
824
			$agentRight->applyDynamicRight();
825
		}
826
	}
827
	
828
	
829
	
830
	protected static function saveCet($id)
831
	{
832
		global $babDB;
833
834
		if (absences_Right::CET !== (int) self::$post['kind'])
835
		{
836
			// save
837
			$babDB->db_query("DELETE FROM absences_rights_cet WHERE id_right=".$babDB->quote($id));
838
			
839
			
840
		} else {
841
			
842
			$per_year = str_replace(',', '.', self::$post['per_year']);
843
			// $per_cet = str_replace(',', '.', self::$post['per_cet']);
844
			$per_cet = 0.0;
845
			$ceiling = str_replace(',', '.', self::$post['ceiling']);
846
			
847
			switch((int) self::$post['min_use_opt'])
848
			{
849
				case 0:
850
					$min_use = 0.0;
851
					break;
852
				case -1:
853
					$min_use = -1.0;
854
					break;
855
				case 1:
856
					$min_use = str_replace(',', '.', self::$post['min_use']);
857
					break;
858
			}
859
			
860
			
861
			
862
			$res = $babDB->db_query("SELECT id FROM absences_rights_cet WHERE id_right=".$babDB->quote($id));
863
			if ($babDB->db_num_rows($res) > 0)
864
			{
865
				list($id_cet) = $babDB->db_fetch_array($res);
866
				$babDB->db_query("
867
					UPDATE absences_rights_cet 
868
					SET
869
						saving_begin	=".$babDB->quote(self::getDateValue('saving_begin')).",
870
						saving_end		=".$babDB->quote(self::getDateValue('saving_end')).",
871
						per_year		=".$babDB->quote($per_year).",
872
						per_cet			=".$babDB->quote($per_cet).",
873
						ceiling			=".$babDB->quote($ceiling).",
874
						min_use			=".$babDB->quote($min_use)."
0 ignored issues
show
Bug introduced by
The variable $min_use 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...
875
						
876
					WHERE
877
						id=".$babDB->quote($id_cet)."
878
				");
879
			}
880
			else
881
			{
882
				$babDB->db_query("
883
					INSERT INTO absences_rights_cet 
884
					(
885
						id_right,
886
						saving_begin,
887
						saving_end,
888
						per_year,
889
						per_cet,
890
						ceiling,
891
						min_use
892
					)
893
					VALUES 
894
					(
895
						".$babDB->quote($id).",
896
						".$babDB->quote(self::getDateValue('saving_begin')).",
897
						".$babDB->quote(self::getDateValue('saving_end')).",
898
						".$babDB->quote($per_year).",
899
						".$babDB->quote($per_cet).",
900
						".$babDB->quote($ceiling).",
901
						".$babDB->quote($min_use)."
902
					)
903
				");
904
			}
905
		}
906
	}
907
	
908
	
909
	
910
	/**
911
	 * Save rules associated to right
912
	 * @param	int		$id			
913
	 */
914
	protected static function saveRules($id)
915
	{
916
		global $babDB;
917
		require_once $GLOBALS['babInstallPath'].'utilit/uuid.php';
918
		
919
		if (absences_Right::FIXED === (int) self::$post['kind'])
920
		{
921
			$babDB->db_query("DELETE FROM ".ABSENCES_RIGHTS_RULES_TBL." WHERE id_right=".$babDB->quote($id));
922
			$babDB->db_query("DELETE FROM ".ABSENCES_RIGHTS_INPERIOD_TBL." WHERE id_right=".$babDB->quote($id));
923
		}
924
		else // rules
925
		{
926
			$validoverlap = isset(self::$post['validoverlap']) ? self::$post['validoverlap'] : 0;
927
			$trigger_type = isset(self::$post['trigger_type']) ? self::$post['trigger_type'] : 0;
928
			$trigger_overlap = isset(self::$post['trigger_overlap']) ? self::$post['trigger_overlap'] : 0;
929
		
930
		
931
			$res = $babDB->db_query("SELECT id FROM ".ABSENCES_RIGHTS_RULES_TBL." WHERE id_right=".$babDB->quote($id));
932
			if ($babDB->db_num_rows($res) > 0)
933
			{
934
				list($id_rule) = $babDB->db_fetch_array($res);
935
				$babDB->db_query("
936
						UPDATE ".ABSENCES_RIGHTS_RULES_TBL."
937
						SET
938
							validoverlap		=".$babDB->quote($validoverlap).",
939
							trigger_nbdays_min	=".$babDB->quote((int) self::$post['trigger_nbdays_min']).",
940
							trigger_nbdays_max	=".$babDB->quote((int) self::$post['trigger_nbdays_max']).",
941
							trigger_type		=".$babDB->quote($trigger_type).",
942
							trigger_p1_begin	=".$babDB->quote(self::getDateValue('trigger_p1_begin')).",
943
							trigger_p1_end		=".$babDB->quote(self::getDateValue('trigger_p1_end')).",
944
							trigger_p2_begin	=".$babDB->quote(self::getDateValue('trigger_p2_begin')).",
945
							trigger_p2_end		=".$babDB->quote(self::getDateValue('trigger_p2_end')).",
946
							trigger_overlap		=".$babDB->quote($trigger_overlap)."
947
						WHERE
948
							id=".$babDB->quote($id_rule)."
949
					");
950
			}
951
			else
952
			{
953
				$babDB->db_query("
954
						INSERT INTO ".ABSENCES_RIGHTS_RULES_TBL."
955
						(
956
							id_right,
957
							validoverlap,
958
							trigger_nbdays_min,
959
							trigger_nbdays_max,
960
							trigger_type,
961
							trigger_p1_begin,
962
							trigger_p1_end,
963
							trigger_p2_begin,
964
							trigger_p2_end,
965
							trigger_overlap
966
						)
967
						VALUES
968
						(
969
							".$babDB->quote($id).",
970
							".$babDB->quote($validoverlap).",
971
							".$babDB->quote((int) self::$post['trigger_nbdays_min']).",
972
							".$babDB->quote((int) self::$post['trigger_nbdays_max']).",
973
							".$babDB->quote($trigger_type).",
974
							".$babDB->quote(self::getDateValue('trigger_p1_begin')).",
975
							".$babDB->quote(self::getDateValue('trigger_p1_end')).",
976
							".$babDB->quote(self::getDateValue('trigger_p2_begin')).",
977
							".$babDB->quote(self::getDateValue('trigger_p2_end')).",
978
							".$babDB->quote($trigger_overlap)."
979
				)
980
						");
981
			}
982
		
983
		
984
			$babDB->db_query('DELETE FROM '.ABSENCES_RIGHTS_INPERIOD_TBL.' WHERE id_right='.$babDB->quote($id));
985
		
986
		
987
			$W = bab_Widgets();
988
			$datePicker = $W->DatePicker();
989
			
990
			foreach(self::$post['inperiod'] as $arr) {
991
				
992
				
993
				$period_start = $datePicker->getISODate($arr['period_start']);
994
				$period_end = $datePicker->getISODate($arr['period_end']);
995
		
996
				if($period_start && $period_end && '0000-00-00' !== $period_start && '0000-00-00' !== $period_end)
997
				{
998
					$babDB->db_query('
999
						INSERT INTO '.ABSENCES_RIGHTS_INPERIOD_TBL.'
1000
						(
1001
							id_right,
1002
							period_start,
1003
							period_end,
1004
							right_inperiod,
1005
							uuid
1006
						)
1007
						VALUES
1008
						(
1009
							'.$babDB->quote($id).',
1010
							'.$babDB->quote($period_start).',
1011
							'.$babDB->quote($period_end).',
1012
							'.$babDB->quote($arr['right_inperiod']).',
1013
							'.$babDB->quote(bab_uuid()).'
1014
						)
1015
					');
1016
				}
1017
			}
1018
			
1019
			
1020
			$babDB->db_query('DELETE FROM absences_dynamic_configuration WHERE id_right='.$babDB->quote($id));
1021
			
1022
			foreach(self::$post['dynconf'] as $arr) {
1023
			
1024
			
1025
				$test_quantity = (float) str_replace(',', '.', $arr['test_quantity']);
1026
				$quantity = (float) str_replace(',', '.', $arr['quantity']);
1027
				
1028
				if ('-' === $arr['sign'])
1029
				{
1030
					$quantity *= -1;
1031
				}
1032
			
1033
				if(0 !== (int) round(100 * $test_quantity) && 0 !== (int) round(100 * $quantity))
1034
				{
1035
					$babDB->db_query('
1036
						INSERT INTO absences_dynamic_configuration 
1037
						(
1038
							id_right,
1039
							test_quantity,
1040
							quantity
1041
						)
1042
						VALUES
1043
						(
1044
							'.$babDB->quote($id).',
1045
							'.$babDB->quote($test_quantity).',
1046
							'.$babDB->quote($quantity).'
1047
						)
1048
					');
1049
				}
1050
			}
1051
		
1052
		}
1053
	}
1054
	
1055
	
1056 View Code Duplication
	public static function goToNoBeneficiaries($id)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1057
	{
1058
		require_once $GLOBALS['babInstallPath'].'utilit/urlincl.php';
1059
		$url = bab_url::get_request('tg');
1060
		$url->idx = 'nobenef';
1061
		$url->idvr = $id;
1062
		$url->location();
1063
		return true;
1064
	}
1065
	
1066
	
1067 View Code Duplication
	public static function goToUpdateFixed($id)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1068
	{
1069
		require_once $GLOBALS['babInstallPath'].'utilit/urlincl.php';
1070
		$url = bab_url::get_request('tg');
1071
		$url->idx = 'fixedud';
1072
		$url->idvr = $id;
1073
		$url->location();
1074
		return true;
1075
	}
1076
	
1077
	
1078 View Code Duplication
	public static function redirect()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1079
	{
1080
		require_once $GLOBALS['babInstallPath'].'utilit/urlincl.php';
1081
		$url = bab_url::get_request('tg');
1082
		$url->idx = 'lrig';
1083
		$url->location();
1084
		return true;
1085
	}
1086
	
1087
}	
1088