Completed
Push — master ( 9ee0eb...9d7b4a )
by Paul
04:30
created

absences_Agent::delete()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 22
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6
Metric Value
dl 0
loc 22
rs 9.2
ccs 0
cts 13
cp 0
cc 2
eloc 11
nc 2
nop 0
crap 6
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
require_once dirname(__FILE__).'/record.class.php';
26
require_once dirname(__FILE__).'/collection.class.php';
27
require_once dirname(__FILE__).'/vacincl.php';
28
29
/**
30
 * Agent, membre du personnel
31
 *
32
 * @property 	int 	$id_user
33
 * @property	int		$id_coll
34
 * @property	int		$id_sa
35
 * @property	int		$id_sa_cet
36
 * @property	int		$id_sa_recover
37
 * @property	string	$emails
38
 * @property    int     $id_organization
39
 */
40
class absences_Agent extends absences_Record
41
{
42
	/**
43
	 *
44
	 * @var int
45
	 */
46
	protected $id_user;
47
48
	/**
49
	 *
50
	 * @var absences_Organization
51
	 */
52
	protected $organization;
53
54
55
	/**
56
	 *
57
	 * @var absences_Collection
58
	 */
59
	protected $collection;
60
61
	/**
62
	 * Cache for user directory entry
63
	 * @var array
64
	 */
65
	private $direntry;
66
67
	/**
68
	 * Cache for user organization chart main entity
69
	 * @var array
70
	 */
71
	private $ocentity;
72
73
74
	/**
75
	 * Cache for approbation scheme
76
	 * @var array
77
	 */
78
	private $approbation;
79
80
	/**
81
	 *
82
	 * @var absences_AgentCet
83
	 */
84
	private $cet;
85
86
87
	/**
88
	 *
89
	 * @var absences_Agent
90
	 */
91
	private static $currentAgent;
92
93
94
	/**
95
	 *
96
	 * @var Array
97
	 */
98
	private $calendar_entities;
99
100
101
	/**
102
	 *
103
	 * @var Array
104
	 */
105
	private $managed_entities;
106
107
108
	/**
109
	 * Get the agent using the id_user
110
	 * @param	int	$id_user
111
	 * @return absences_Agent
112
	 */
113 13
	public static function getFromIdUser($id_user)
114
	{
115 13
		$agent = new absences_Agent;
116 13
		$agent->id_user = (int) $id_user;
117
118 13
		return $agent;
119
	}
120
121
	/**
122
	 * Get the logged in agent
123
	 * @return absences_Agent
124
	 */
125
	public static function getCurrentUser()
126
	{
127
		if (!isset(self::$currentAgent))
128
		{
129
			$id_user = bab_getUserId();
130
			if (0 === $id_user)
131
			{
132
				throw new Exception('The user is not logged in');
133
			}
134
135
			self::$currentAgent = self::getFromIdUser($id_user);
136
		}
137
138
		return self::$currentAgent;
139
	}
140
141
142
143
	/**
144
	 * Get Agent using the ID in "personnel" table
145
	 * @return absences_Agent
146
	 */
147
	public static function getFromIdPersonnel($id)
148
	{
149
		$agent = new absences_Agent;
150
		$agent->id = (int) $id;
151
152
		return $agent;
153
	}
154
155
	/**
156
	 * @return int
157
	 */
158 16
	public function getIdUser()
159
	{
160 16
		if (isset($this->id_user))
161 16
		{
162 13
			return $this->id_user;
163
		}
164
165 4
		$row = $this->getRow();
166 4
		return (int) $row['id_user'];
167
	}
168
169
170
	/**
171
	 * Regime
172
	 * @param	absences_Collection	$collection
173
	 */
174
	public function setCollection(absences_Collection $collection)
175
	{
176
		$this->collection = $collection;
177
		return $this;
178
	}
179
180
	/**
181
	 * Regime
182
	 * @return absences_Collection
183
	 */
184 View Code Duplication
	public function getCollection()
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...
185
	{
186
187
		if (!isset($this->collection))
188
		{
189
			$row = $this->getRow();
190
			$this->collection = absences_Collection::getById($row['id_coll']);
191
		}
192
193
		return $this->collection;
194
	}
195
196
197
198
199
200
201
	/**
202
	 * Organisme
203
	 * @param	absences_Organization	$organization
204
	 */
205
	public function setOrganization(absences_Organization $organization)
206
	{
207
	    $this->organization = $organization;
208
	    return $this;
209
	}
210
211
	/**
212
	 * Organisme
213
	 * @return absences_Organization
214
	 */
215
	public function getOrganization()
216
	{
217
218
	    if (!isset($this->organization))
219
	    {
220
	        require_once dirname(__FILE__).'/organization.class.php';
221
	        $row = $this->getRow();
222
	        if($row['id_organization'] == 0){
223
	        	return null;
224
	        }
225
	        $this->organization = absences_Organization::getById($row['id_organization']);
226
	    }
227
228
	    if (null == $this->organization->getRow())
229
	    {
230
	    	return null;
231
	    }
232
233
	    return $this->organization;
234
	}
235
236
237
238
239
240
	/**
241
	 * @return string
242
	 */
243 8
	public function getName()
244
	{
245 8
		return bab_getUserName($this->getIdUser());
246
	}
247
248
249
250
	/**
251
	 * Table row as an array
252
	 * @return array
253
	 */
254 4
	public function getRow()
255
	{
256 4
		if (null === $this->row)
257 4
		{
258
			global $babDB;
259
260
			$query = 'SELECT * FROM absences_personnel WHERE ';
261
			if (isset($this->id))
262
			{
263
				$query .= 'id='.$babDB->quote($this->id);
264
			}
265
266
			if (isset($this->id_user))
267
			{
268
				$query .= 'id_user='.$babDB->quote($this->id_user);
269
			}
270
271
			$res = $babDB->db_query($query);
272
			$row = $babDB->db_fetch_assoc($res);
273
274
			if (!$row)
275
			{
276
				throw new Exception('This agent does not exists id='.$this->id.' id_user='.$this->id_user);
277
			}
278
279
			$this->setRow($row);
280
281
			return $this->row;
282
		}
283
284 4
		return $this->row;
285
	}
286
287
288
	/**
289
	 * Test if agent exists in personnel members
290
	 * @return bool
291
	 */
292
	public function exists()
293
	{
294
		try {
295
			$row = $this->getRow();
296
		} catch(Exception $e)
297
		{
298
			return false;
299
		}
300
301
		return (false !== $row);
302
	}
303
304
305
306
	/**
307
	 * All agent requests sorted by creation date
308
	 *
309
	 * @return absences_RequestIterator
310
	 */
311
	public function getRequestIterator()
312
	{
313
		require_once dirname(__FILE__).'/request.class.php';
314
		$I = new absences_RequestIterator(array($this->getIdUser()));
315
316
		return $I;
317
	}
318
319
320
321
	/**
322
 	 * iterateur des droits d'un agent, vue utilisateur au moment de la demande
323
 	 * droit ouverts, ordonnes alphabetiquement
324
	 *
325
	 * @return absences_AgentRightUserIterator
326
	 */
327
	public function getAgentRightUserIterator()
328
	{
329
		require_once dirname(__FILE__).'/agent_right.class.php';
330
		$I = new absences_AgentRightUserIterator;
331
		$I->setAgent($this);
332
333
		return $I;
334
	}
335
336
337
338
	/**
339
	 * iterateur des droits d'un agent, vue gestionnaire
340
 	 * tout les droits associes a l'agent, ordonnes par annees, puis alphabetiquement
341
	 *
342
	 * @return absences_AgentRightManagerIterator
343
	 */
344
	public function getAgentRightManagerIterator()
345
	{
346
		require_once dirname(__FILE__).'/agent_right.class.php';
347
		$I = new absences_AgentRightManagerIterator;
348
		$I->setAgent($this);
349
350
		return $I;
351
	}
352
353
354
355
356
357
	/**
358
	 * Add a vacation right to the agent
359
	 * return true if inserted or if already exists
360
	 *
361
	 * @param	absences_Right	$right
362
	 * @return bool
363
	 */
364
	public function addRight(absences_Right $right)
365
	{
366
		global $babDB;
367
		$babDB->db_queryWem('INSERT INTO absences_users_rights (id_user, id_right) 
368
				VALUES ('.$babDB->quote($this->getIdUser()).', '.$babDB->quote($right->id).')');
369
370
		$this->addMovement(sprintf(absences_translate('The right %s has been assigned to the user %s'), $right->description, $this->getName()));
371
372
		return true;
373
	}
374
375
376
	/**
377
	 * Add fixed entry if the right is FIXED
378
	 *
379
	 * @throws absences_EntryException
380
	 *
381
	 * @param	absences_Right	$right
382
	 * @param 	bool			$notify
383
	 *
384
	 * @return bool
385
	 */
386
	public function addFixedEntry(absences_Right $right, $notify = true)
387
	{
388
		if( absences_Right::FIXED !== $right->getKind() ) {
389
		    return false;
390
		}
391
392
393
		if (absences_addFixedVacation($this->getIdUser(), $right))
394
		{
395
			if ($notify)
396
			{
397
				absences_notifyOnVacationChange(array($this->getIdUser()), $right->quantity, $right->date_begin_fixed, $right->date_end_fixed,  ABSENCES_FIX_ADD);
0 ignored issues
show
Documentation introduced by
array($this->getIdUser()) is of type array<integer,integer,{"0":"integer"}>, 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...
398
			}
399
400
			return true;
401
		}
402
403
		return false;
404
	}
405
406
407
	/**
408
	 * Add fixed entry if the right is FIXED
409
	 *
410
	 * @throws absences_EntryException
411
	 *
412
	 * @param	absences_Right	$right
413
	 * @param 	bool			$notify
414
	 *
415
	 * @return bool
416
	 */
417
	public function addFixedEntryIfNotExists(absences_Right $right, $notify = true)
418
	{
419
	    if( absences_Right::FIXED !== $right->getKind()) {
420
	        return false;
421
	    }
422
423
	    if (absences_isFixedCreated($this->getIdUser(), $right->id)) {
424
	        return false;
425
	    }
426
427
	    return $this->addFixedEntry($right, $notify);
428
	}
429
430
431
432
	/**
433
	 * Remove vacation right from agent
434
	 * Ne pas autoriser si le regime de l'agent est liee au droit
435
	 * return true if link removed or does not exists, return false if remove failed (ex because of collection assignement)
436
	 *
437
	 * @param	absences_Right	$right
438
	 * @return bool
439
	 */
440
	public function removeRight(absences_Right $right)
441
	{
442
443
		$collection = $this->getCollection();
444
		if ($collection->isLinkedToRight($right))
445
		{
446
			// empecher la suppression du lien agent-droit tant que le regime force le lien
447
			return false;
448
		}
449
450
		require_once dirname(__FILE__).'/agent_right.class.php';
451
452
		$agentRight = new absences_AgentRight();
453
		$agentRight->setAgent($this);
454
		$agentRight->setRight($right);
455
456
		if (!$agentRight->getRow())
457
		{
458
			// le lien n'existe pas
459
			return false;
460
		}
461
462
463
		$agentRight->delete();
464
465
		$this->addMovement(sprintf(absences_translate('The right %s has been unassigned from the user %s'), $right->description, $this->getName()));
466
467
		return true;
468
	}
469
470
	/**
471
	 * remove fixed entry if the right is FIXED
472
	 * @param	absences_Right	$right
473
	 * @param 	bool			$notify
474
	 * @return absences_Agent
475
	 */
476
	public function removeFixedEntry(absences_Right $right, $notify = true)
477
	{
478
		if( absences_Right::FIXED === $right->getKind() )
479
		{
480
			global $babDB;
481
482
483
			$res = $babDB->db_query("
484
			    SELECT
485
			         vet.*,
486
			         veet.quantity
487
488
			    from absences_entries_elem veet
489
			         left join absences_entries vet on veet.id_entry=vet.id
490
			    where
491
			         veet.id_right=".$babDB->quote($right->id)."
492
			         and vet.id_user=".$babDB->quote($this->getIdUser())
493
			);
494
495
			while ($arr = $babDB->db_fetch_assoc($res)) {
496
497
			    if (absences_removeFixedVacation( $arr['id'])) {
498
			        if ($notify) {
499
			            absences_notifyOnVacationChange(array($arr['id_user']), $arr['quantity'], $arr['date_begin'], $arr['date_end'], ABSENCES_FIX_DELETE);
0 ignored issues
show
Documentation introduced by
array($arr['id_user']) 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...
500
			        }
501
			    }
502
			}
503
504
		}
505
506
		return $this;
507
	}
508
509
510
511
	/**
512
	 * Test if right is linked to collection
513
	 * @param absences_Right $right
514
	 * @return boolean
515
	 */
516 View Code Duplication
	public function isLinkedToRight(absences_Right $right)
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...
517
	{
518
		require_once dirname(__FILE__).'/agent_right.class.php';
519
520
		$link = new absences_AgentRight;
521
		$link->setAgent($this);
522
		$link->setRight($right);
523
		$row = $link->getRow();
524
525
		if ($row)
0 ignored issues
show
Bug Best Practice introduced by
The expression $row of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
526
		{
527
			return true;
528
		}
529
		return false;
530
	}
531
532
533
	/**
534
	 * Get organizational chart main entity or null
535
	 * @return array
536
	 */
537
	public function getMainEntity()
538
	{
539
		if (!isset($this->ocentity))
540
		{
541
			$id_oc = absences_getVacationOption('id_chart');
542
543
			require_once $GLOBALS['babInstallPath'].'utilit/ocapi.php';
544
			$this->ocentity = bab_OCGetUserMainEntity($this->getIdUser(), $id_oc);
0 ignored issues
show
Documentation Bug introduced by
It seems like bab_OCGetUserMainEntity(...s->getIdUser(), $id_oc) can be null. However, the property $ocentity is declared as array. Maybe change the type of the property to array|null or add a type check?

Our type inference engine has found an assignment of a scalar value (like a string, an integer or null) to a property which is an array.

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

To type hint that a parameter can be either an array or null, you can set a type hint of array and a default value of null. The PHP interpreter will then accept both an array or null for that parameter.

function aContainsB(array $needle = null, array  $haystack) {
    if (!$needle) {
        return false;
    }

    return array_intersect($haystack, $needle) == $haystack;
}

The function can be called with either null or an array for the parameter $needle but will only accept an array as $haystack.

Loading history...
545
		}
546
547
		return $this->ocentity;
548
	}
549
550
	/**
551
	 * Get approbation scheme informations
552
	 * @return array
553
	 */
554
	public function getApprobation()
555
	{
556
		if (empty($this->id_sa))
557
		{
558
			return null;
559
		}
560
561
		if (null === $this->approbation)
562
		{
563
			require_once $GLOBALS['babInstallPath'].'utilit/wfincl.php';
564
			$this->approbation = bab_WFGetApprobationInfos($this->id_sa);
0 ignored issues
show
Documentation Bug introduced by
It seems like bab_WFGetApprobationInfos($this->id_sa) can be null. However, the property $approbation is declared as array. Maybe change the type of the property to array|null or add a type check?

Our type inference engine has found an assignment of a scalar value (like a string, an integer or null) to a property which is an array.

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

To type hint that a parameter can be either an array or null, you can set a type hint of array and a default value of null. The PHP interpreter will then accept both an array or null for that parameter.

function aContainsB(array $needle = null, array  $haystack) {
    if (!$needle) {
        return false;
    }

    return array_intersect($haystack, $needle) == $haystack;
}

The function can be called with either null or an array for the parameter $needle but will only accept an array as $haystack.

Loading history...
565
		}
566
567
		return $this->approbation;
568
	}
569
570
571
	/**
572
	 * Get superior if the agent is in organizational chart
573
	 * @return array
574
	 */
575
	public function getSuperior()
576
	{
577
	    require_once $GLOBALS['babInstallPath'].'utilit/afincl.php';
578
	    
579
	    $id_oc = absences_getVacationOption('id_chart');
580
	    
581
	    $superior = bab_getSupervisor((int) $this->id_user, $id_oc, 0);
582
	    
583
	    if (!isset($superior['name']) || 0 === count($superior['name'])) {
584
	        return null;
585
	    }
586
	    
587
	    return $superior;
588
	}
589
590
591
592
	/**
593
	 * Get directory entry
594
	 * @return array
595
	 */
596 1
	public function getDirEntry()
597
	{
598 1
		if (!isset($this->direntry))
599 1
		{
600 1
			$this->direntry = bab_admGetDirEntry($this->getIdUser(), BAB_DIR_ENTRY_ID_USER);
601 1
		}
602
603 1
		return $this->direntry;
604
	}
605
606
607
	/**
608
	 * Date contenue dans la fiche d'annuaire
609
	 * formats autorises :
610
	 * 		DD/MM/YYYY
611
	 * 		DD/MM/YY
612
	 * 		D/M/YYYY
613
	 * 		DD-MM-YYYY
614
	 * 		DD-MM-YY
615
	 * 		D-M-YYYY
616
	 *
617
	 * @param string $fieldname
618
	 *
619
	 * @return string		ISO date
620
	 */
621
	public function getDirEntryDate($fieldname)
622
	{
623
		$direntry = $this->getDirEntry();
624
		if (!isset($direntry[$fieldname]))
625
		{
626
			return null;
627
		}
628
629
		$value = $direntry[$fieldname]['value'];
630
631
		if ('' === $value)
632
		{
633
			return null;
634
		}
635
636
		if (!preg_match('#([0-9]{1,2})(?:/|-)([0-9]{1,2})(?:/|-)([0-9]{2,4})#', $value, $m))
637
		{
638
			return null;
639
		}
640
641
		return sprintf('%04d-%02d-%02d', (int) $m[3], (int) $m[2], (int) $m[1]);
642
	}
643
644
645
646
	/**
647
	 * @return bab_dirEntryPhoto
648
	 */
649
	private function getDirEntryPhoto()
650
	{
651
		$entry = $this->getDirEntry();
652
		if (isset($entry['jpegphoto']['photo']))
653
		{
654
			return $entry['jpegphoto']['photo'];
655
		}
656
657
		return null;
658
	}
659
660
	/**
661
	 * Get icon url only if thumbnailer is present (16x16)
662
	 * @return string
663
	 */
664
	public function getIcon()
665
	{
666
		$T = bab_functionality::get('Thumbnailer');
667
668
		if ($T && $photo = $this->getDirEntryPhoto())
669
		{
670
			$photo->setThumbSize(16, 16);
671
			return $photo->getUrl();
672
		}
673
674
		return null;
675
	}
676
677
	/**
678
	 * Get a small photo to display in agent page or requests page (64x64)
679
	 * if the thumbnailer is not present photo is not resized
680
	 * @return string
681
	 */
682
	public function getPhoto()
683
	{
684
		if ($photo = $this->getDirEntryPhoto())
685
		{
686
			$photo->setThumbSize(64, 64);
687
			return $photo->getUrl();
688
		}
689
690
		return null;
691
	}
692
693
694
695
	/**
696
	 * @return bool
697
	 */
698 2
	public function isInPersonnel()
699
	{
700 2
		global $babDB;
701
702
		try {
703
704 2
			$id_user = $this->getIdUser();
705
706 2
		} catch(Exception $e) {
707
			bab_debug($e->getMessage());
708
			return false;
709
		}
710
711 2
		$res = $babDB->db_query("select id from absences_personnel where id_user='".$babDB->db_escape_string($id_user)."'");
712 2
		if( $res && $babDB->db_num_rows($res) > 0)
713 2
		{
714 1
			return true;
715
		}
716
717 1
		return false;
718
	}
719
720
	/**
721
	 * Test if the user have access to at least one vacation right
722
	 * si les droits accessibles ont un solde a 0, la fonction renvoi true malgre tout, seul le nombre de droit accessible est teste
723
	 * (certains droits peuvent accepter les soldes negatifs)
724
	 * @return bool
725
	 */
726
	public function haveRights()
727
	{
728
		$I = $this->getAgentRightUserIterator();
729
730
		return ($I->count() > 0);
731
	}
732
733
734
735
	/**
736
	 * @return bool
737
	 */
738
	public function isManager()
739
	{
740
		return bab_isAccessValid('absences_managers_groups', 1, $this->getIdUser());
741
742
	}
743
744
	/**
745
	 * Test si l'agent est un approbateur
746
	 * @param	int	$id_user	test si l'agent est l'approbateur d'un demandeur en particulier
747
	 * @return bool
748
	 */
749
	public function isApprover($id_user = null)
750
	{
751
		global $babDB;
752
753
		$arrchi = bab_getWaitingIdSAInstance($this->getIdUser());
754
		$query = "SELECT idfai from ".ABSENCES_ENTRIES_TBL."  where status='' AND idfai IN(".$babDB->quote($arrchi).")";
755
		if (isset($id_user))
756
		{
757
			$query .= " AND id_user=".$babDB->quote($id_user);
758
		}
759
760
		$res = $babDB->db_query($query);
761
		if( $res && $babDB->db_num_rows($res) > 0)
762
		{
763
			return true;
764
		}
765
766
		return false;
767
	}
768
769
770
771
772
	/**
773
	 * Liste des entites gerees par la gestion deleguee
774
	 * @return array
775
	 */
776
	public function getManagedEntities()
777
	{
778
		if (!isset($this->managed_entities))
779
		{
780
			$id_oc = absences_getVacationOption('id_chart');
781
782
			require_once $GLOBALS['babInstallPath'].'utilit/ocapi.php';
783
784
			$userentities = bab_OCGetUserEntities($this->getIdUser(), $id_oc);
785
			absences_addCoManagerEntities($userentities, $this->getIdUser());
786
787
			$this->managed_entities = array();
788
789
			foreach ($userentities['superior'] as $entity)
790
			{
791
				$this->managed_entities[] = $entity;
792
				$children = bab_OCGetChildsEntities($entity['id'], $id_oc);
793
				$this->managed_entities = array_merge($this->managed_entities, $children);
794
			}
795
796
		}
797
		return $this->managed_entities;
798
	}
799
800
	/**
801
	 * Access a la gestion delegee
802
	 * @return bool
803
	 */
804
	public function isEntityManager()
805
	{
806
		$arr = $this->getManagedEntities();
807
808
		return (count($arr) > 0);
809
	}
810
811
812
	/**
813
	 * Gestionnaire delegue de l'entite
814
	 * @param int $id_entity
815
	 * @return bool
816
	 */
817
	public function isEntityManagerOf($id_entity)
818
	{
819
		$managed_entities = $this->getManagedEntities();
820
821
		foreach($managed_entities as $entity)
822
		{
823
			if ($id_entity == $entity['id'])
824
			{
825
				return true;
826
			}
827
		}
828
829
		return false;
830
	}
831
832
833
834
	/**
835
	 * Tester si l'agent est le supperieur d'un autre agent
836
	 * @param absences_Agent $agent
837
	 * @return bool
838
	 */
839
	public function isSuperiorOf(absences_Agent $agent)
840
	{
841
	    if ($agent->getIdUser() === $this->getIdUser())
842
	    {
843
	        return false;
844
	    }
845
846
		$user_entities_id = $agent->getMemberEntityIds();
847
		$managed_entities = $this->getManagedEntities();
848
849
		foreach($managed_entities as $entity)
850
		{
851
			if (isset($user_entities_id[$entity['id']]))
852
			{
853
				return true;
854
			}
855
		}
856
		return false;
857
	}
858
859
860
861
862
	/**
863
	 * Liste des entites autorises pour les visualisation de planning
864
	 * @return array
865
	 */
866
	public function getCalendarEntities()
867
	{
868
		if (!isset($this->calendar_entities))
869
		{
870
			global $babDB;
871
872
			$id_oc = absences_getVacationOption('id_chart');
873
874
			$this->calendar_entities = array();
875
			$res = $babDB->db_query("SELECT id_entity FROM absences_planning WHERE id_user=".$babDB->quote($this->getIdUser()));
876
			while ($arr = $babDB->db_fetch_assoc($res)) {
877
				$this->calendar_entities[$arr['id_entity']] = $arr['id_entity'];
878
				$tmp = bab_OCGetChildsEntities($arr['id_entity'], $id_oc);
879
880
				foreach($tmp as $entity) {
881
					$this->calendar_entities[$entity['id']] = $entity['id'];
882
				}
883
			}
884
		}
885
886
		return $this->calendar_entities;
887
	}
888
889
	/**
890
	 * Tester si l'agent a les droits pour voir le planning d'un autre agent
891
	 * @param absences_Agent $agent
892
	 * @return bool
893
	 */
894
	public function canViewCalendarOf(absences_Agent $agent)
895
	{
896
	    if ($this->isManager())
897
	    {
898
	        return true;
899
	    }
900
	    
901
	    if ($this->isSuperiorOf($agent))
902
	    {
903
	        return true;
904
	    }
905
	    
906
	    if ($this->isApprover($agent->getIdUser()))
907
	    {
908
	        return true;
909
	    }
910
	    
911
	    if (!$agent->isInPersonnel())
912
		{
913
			return false;
914
		}
915
916
		if ($this->getIdUser() === $agent->getIdUser())
917
		{
918
			return true;
919
		}
920
		
921
		if ($this->isSharedCalendarEntity($agent))
922
		{
923
			return true;
924
		}
925
926
		if ($this->isInSameEntityPlanning($agent))
927
		{
928
			return true;
929
		}
930
931
		return false;
932
	}
933
934
935
936
937
	/**
938
	 * listes des entities de l'agent
939
	 * @return array
940
	 */
941
	public function getMemberEntities()
942
	{
943
		$id_oc = absences_getVacationOption('id_chart');
944
		$arr = bab_OCGetUserEntities($this->getIdUser(), $id_oc);
945
		return array_merge($arr['superior'], $arr['temporary'], $arr['members']);
946
	}
947
948
	/**
949
	 * Liste des ID des entites de l'agent
950
	 * @return array
951
	 */
952
	public function getMemberEntityIds()
953
	{
954
		$user_entities_id = array();
955
		foreach($this->getMemberEntities() as $entity)
956
		{
957
			$user_entities_id[$entity['id']] = $entity['id'];
958
		}
959
960
		return $user_entities_id;
961
	}
962
963
964
	/**
965
	 * Tester si l'agent a acces au planning de l'agent passe en parametre en passant par le partage de planning des entites
966
	 * @param	absences_Agent $agent
967
	 * @return bool
968
	 */
969
	public function isSharedCalendarEntity(absences_Agent $agent)
970
	{
971
		$calendar_entities = $this->getCalendarEntities(); // entites agendas autorises en partage
972
		$user_entities = $agent->getMemberEntities(); // entites de l'utilisteur que l'on cherche a visualiser
973
974
		foreach($user_entities as $entity) {
975
976
			$id_entity = (int) $entity['id'];
977
978
			if (array_key_exists($id_entity, $calendar_entities)) {
979
				return true;
980
			}
981
		}
982
983
		return false;
984
	}
985
986
987
988
	/**
989
	 * Tester si l'agent passe en parametre est dans le  meme planning de service et que la visualisation du planning de service est activee
990
	 * @param absences_Agent $agent
991
	 * @return bool
992
	 */
993
	public function isInSameEntityPlanning(absences_Agent $agent)
994
	{
995
		if (0 === (int) absences_getVacationOption('entity_planning'))
996
		{
997
			return false;
998
		}
999
1000
1001
		if ($this->getIdUser() === $agent->getIdUser())
1002
		{
1003
			return true;
1004
		}
1005
1006
		$myEntity = $this->getMainEntity();
1007
		$agentEntity = $agent->getMainEntity();
1008
1009
		if ($myEntity['id'] === $agentEntity['id'])
1010
		{
1011
			return true;
1012
		}
1013
1014
		return false;
1015
	}
1016
	
1017
	
1018
	public function canViewCustomPlanning($id_planning)
1019
	{
1020
	    return bab_isAccessValid('absences_custom_planning_groups', $id_planning,  $this->getIdUser());
1021
	}
1022
1023
1024
	/**
1025
	 * Tester si l'agent peut voir le planning d'une autre entite
1026
	 *
1027
	 * @return bool
1028
	 */
1029
	public function canViewEntityPlanning($id_entity = null)
1030
	{
1031
	    if ($this->isManager()) {
1032
	        return true;
1033
	    }
1034
	    
1035
	    
1036
		// cas possible avec le partage de planning
1037
1038
		$calendars = $this->getCalendarEntities();
1039
1040
		if (isset($calendars[$id_entity]))
1041
		{
1042
			return true;
1043
		}
1044
1045
		// si supperieur de l'entite
1046
1047
		if ($this->isEntityManagerOf($id_entity))
1048
		{
1049
			return true;
1050
		}
1051
1052
		// si planning du service
1053
1054
		$myEntity = $this->getMainEntity();
1055
		if ((int) $id_entity === (int) $myEntity['id'] && 1 === (int) absences_getVacationOption('entity_planning')) {
1056
		    return true;
1057
		}
1058
1059
1060
		return false;
1061
	}
1062
1063
	/**
1064
	 * Tester si l'agent peut voir le planning de son entite principale
1065
	 */
1066
	public function canViewMainEntityPlanning()
1067
	{
1068
		$myEntity = $this->getMainEntity();
1069
1070
		return $this->canViewEntityPlanning($myEntity['id']);
1071
	}
1072
1073
1074
1075
	/**
1076
	 * Declaration de jours travailles donnant droit a recuperation
1077
	 * @return bool
1078
	 */
1079
	public function canCreateWorkperiodRecoverRequest()
1080
	{
1081
		$workperiod = (bool) absences_getVacationOption('workperiod_recover_request');
1082
1083
		if (!$workperiod)
1084
		{
1085
			return false;
1086
		}
1087
1088
		if (!$this->isInPersonnel())
1089
		{
1090
			return false;
1091
		}
1092
1093
		return true;
1094
	}
1095
1096
1097
	/**
1098
	 * @return absences_AgentCet
1099
	 */
1100
	public function Cet()
1101
	{
1102
		if (!isset($this->cet))
1103
		{
1104
			require_once dirname(__FILE__).'/agent_cet.class.php';
1105
			$this->cet = new absences_AgentCet($this);
1106
1107
		}
1108
1109
		return $this->cet;
1110
	}
1111
1112
1113
	/**
1114
	 * Approbation sheme ID
1115
	 * @return int
1116
	 */
1117
	public function getApprobationId()
1118
	{
1119
		return (int) $this->id_sa;
1120
	}
1121
1122
1123
	/**
1124
	 * Approbation sheme ID from recover request
1125
	 * @return int
1126
	 */
1127
	public function getRecoverApprobationId()
1128
	{
1129
		$id_sa_recover = (int) $this->id_sa_recover;
1130
		if (0 === $id_sa_recover)
1131
		{
1132
			return $this->getApprobationId();
1133
		}
1134
1135
		return $id_sa_recover;
1136
	}
1137
1138
1139
	/**
1140
	 * Approbation sheme ID from cet request
1141
	 * @return int
1142
	 */
1143
	public function getCetApprobationId()
1144
	{
1145
		$id_sa_cet = (int) $this->id_sa_cet;
1146
		if (0 === $id_sa_cet)
1147
		{
1148
			return $this->getApprobationId();
1149
		}
1150
1151
		return $id_sa_cet;
1152
	}
1153
1154
1155
	/**
1156
	 * Create reports for expired rights of agent
1157
	 *
1158
	 */
1159
	public function createReports()
1160
	{
1161
		$res = $this->getAgentRightManagerIterator();
1162
1163
		foreach($res as $agentRight)
1164
		{
1165
			/*@var $agentRight absences_AgentRight */
1166
1167
			$agentRight->createReport();
1168
		}
1169
1170
	}
1171
	
1172
	
1173
1174
	private function getRecoveryRgroup($quantity_unit)
1175
	{
1176
	    global $babDB;
1177
	
1178
	    $res = $babDB->db_query("SELECT id FROM absences_rgroup WHERE recover='1' AND quantity_unit=".$babDB->quote($quantity_unit));
1179
	
1180
	    if ($babDB->db_num_rows($res) == 0)
1181
	    {
1182
	        return 0;
1183
	    }
1184
	
1185
	    $row = $babDB->db_fetch_assoc($res);
1186
	
1187
	    return $row['id'];
1188
	}
1189
	
1190
	
1191
	
1192
	/**
1193
	 * Create a recovery right for the agent
1194
	 * and return the id_right
1195
	 * 
1196
	 * @param string $begin            ISO date YYYY-MM-DD
1197
	 * @param string $end              ISO date YYYY-MM-DD
1198
	 * @parap string $description
1199
	 * @param float $quantity
1200
	 * @param string $quantity_unit D|H
1201
	 * 
1202
	 * @return int
1203
	 */
1204
	public function createRecoveryRight($begin, $end, $description, $quantity, $quantity_unit)
1205
	{
1206
        require_once dirname(__FILE__).'/right.class.php';
1207
        global $babDB;
1208
1209
1210
	    $babDB->db_query('INSERT INTO absences_rights
1211
				(
1212
					kind,
1213
					description,
1214
	                createdOn,
1215
					date_entry,
1216
					date_begin,
1217
					date_end,
1218
					cbalance,
1219
					id_type,
1220
					id_rgroup,
1221
					quantity,
1222
					quantity_unit,
1223
					use_in_cet,
1224
					no_distribution
1225
				)
1226
	    
1227
			VALUES (
1228
					'.$babDB->quote(absences_Right::RECOVERY).',
1229
					'.$babDB->quote($description).',
1230
	                CURDATE(),
1231
					CURDATE(),
1232
					'.$babDB->quote($begin).',
1233
					'.$babDB->quote($end).',
1234
					'.$babDB->quote('N').',
1235
					'.$babDB->quote(absences_getRecoveryType()).',
1236
					'.$babDB->quote($this->getRecoveryRgroup($quantity_unit)).',
1237
					'.$babDB->quote($quantity).',
1238
					'.$babDB->quote($quantity_unit).',
1239
					'.$babDB->quote(0).',
1240
					'.$babDB->quote(1).'
1241
				)');
1242
	    
1243
	    $id_right = $babDB->db_insert_id();
1244
	    
1245
	    
1246
	    $babDB->db_query('INSERT INTO absences_rights_rules
1247
				(
1248
					id_right
1249
				)
1250
			VALUES
1251
				(
1252
					'.$babDB->quote($id_right).'
1253
				)
1254
	    
1255
		');
1256
	    
1257
	    
1258
	    $babDB->db_query('INSERT INTO absences_rights_inperiod
1259
				(
1260
					id_right,
1261
					period_start,
1262
					period_end,
1263
					right_inperiod
1264
				)
1265
			VALUES
1266
				(
1267
					'.$babDB->quote($id_right).',
1268
					'.$babDB->quote($begin).',
1269
					'.$babDB->quote($end).',
1270
					'.$babDB->quote(1).'
1271
				)
1272
		');
1273
	    
1274
	    
1275
	    $babDB->db_query('INSERT INTO absences_users_rights
1276
			(
1277
				id_right,
1278
				id_user
1279
			)
1280
			VALUES
1281
			(
1282
				'.$babDB->quote($id_right).',
1283
				'.$babDB->quote($this->getIdUser()).'
1284
			)
1285
		');
1286
	    
1287
	    return $id_right;
1288
	}
1289
1290
1291
1292
	/**
1293
	 * Movements related to the agent
1294
	 * @return absences_MovementIterator
1295
	 */
1296
	public function getMovementIterator()
1297
	{
1298
		require_once dirname(__FILE__).'/movement.class.php';
1299
1300
		$I = new absences_MovementIterator();
1301
		$I->setAgent($this);
1302
1303
		return $I;
1304
	}
1305
1306
1307
	/**
1308
	 *
1309
	 * @param string $message	Generated message
1310
	 * @param string $comment	Author comment
1311
	 */
1312
	public function addMovement($message, $comment = '')
1313
	{
1314
		require_once dirname(__FILE__).'/movement.class.php';
1315
1316
		$movement = new absences_Movement();
1317
		$movement->message = $message;
1318
		$movement->comment = $comment;
1319
		$movement->setAgent($this);
1320
		$movement->save();
1321
	}
1322
1323
1324
	public function delete()
1325
	{
1326
		global $babDB;
1327
1328
		$id_user = $this->getIdUser();
1329
		absences_clearUserCalendar($id_user);
1330
1331
		$I = $this->getRequestIterator();
1332
		foreach($I as $request)
1333
		{
1334
			$request->delete();
1335
		}
1336
1337
		$babDB->db_query("delete from ".ABSENCES_USERS_RIGHTS_TBL." where id_user='".$babDB->db_escape_string($id_user)."'");
1338
		$babDB->db_query("delete from ".ABSENCES_PERSONNEL_TBL." where id_user='".$babDB->db_escape_string($id_user)."'");
1339
1340
		$babDB->db_query("delete from absences_comanager where id_user='".$babDB->db_escape_string($id_user)."'");
1341
		$babDB->db_query("delete from absences_planning where id_user='".$babDB->db_escape_string($id_user)."'");
1342
1343
1344
1345
	}
1346
1347
1348
1349
	public function setEmails($emails)
1350
	{
1351
		global $babDB;
1352
		$id_user = $this->getIdUser();
1353
1354
		$babDB->db_query('UPDATE absences_personnel SET emails='.$babDB->quote($emails).' WHERE id_user='.$babDB->quote($id_user));
1355
	}
1356
1357
	/**
1358
	 * @return array
1359
	 */
1360
	public function getEmails()
1361
	{
1362
		return preg_split('/\s*,\s*/', $this->emails);
1363
	}
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
	/**
1378
	 * Set organization of agent from the "organizationname" field of the directory entry
1379
	 * if possible or return false if the organization does not exists
1380
	 *
1381
	 * @return bool
1382
	 */
1383
	public function setOrganizationFromDirEntry()
1384
	{
1385
	    global $babDB;
1386
	    $entry = $this->getDirEntry();
1387
	    
1388
	    if (!isset($entry)||false === $entry||0 === count($entry)) {
1389
	        throw new Exception(absences_translate('Directory entry not found'));
1390
	    }
1391
	    
1392
	    if (empty($entry['organisationname'])||empty($entry['organisationname']['value'])) {
1393
	        throw new Exception(absences_translate('Organization name not found in directory entry, the organization associated  to the absence personnel member was not updated, nonetheless, the directory entry was sucessfully saved'));
1394
	    }
1395
	    
1396
	    $organization = absences_Organization::getByName($entry['organisationname']['value']);
1397
1398
	    if (!isset($organization)) {
1399
	        throw new Exception(
1400
	            sprintf(
1401
	                absences_translate('Organization not found in absences for "%s"'), 
1402
	                $entry['organisationname']['value']
1403
		        )
1404
		    );
1405
	    }
1406
1407
	    $this->setOrganization($organization);
1408
1409
	    $babDB->db_query('UPDATE absences_personnel SET
1410
					id_organization='.$babDB->quote($organization->id).'
1411
				WHERE
1412
					id_user='.$babDB->quote($this->getIdUser()));
1413
1414
	    return true;
1415
	}
1416
}
1417
1418
1419
1420
1421
1422
1423
1424
1425
class absences_AgentIterator extends absences_Iterator
1426
{
1427
    /**
1428
     * @var absences_Collection
1429
     */
1430
	protected $collection;
1431
1432
	/**
1433
	 * @var absences_Right
1434
	 */
1435
	protected $right;
1436
1437
	/**
1438
	 * @var absences_Organization
1439
	 */
1440
	protected $organization;
1441
1442
	/**
1443
	 * @var array
1444
	 */
1445
	public $exclude_users;
1446
1447
	/**
1448
	 * Create an agent iterator with agent associated to a vacation right
1449
	 * @param absences_Right $right
1450
	 */
1451
	public function setRight(absences_Right $right)
1452
	{
1453
		$this->right = $right;
1454
	}
1455
1456
	/**
1457
	 * Create an agent iterator with agents associated to a collection
1458
	 * @param absences_Collection $collection
1459
	 */
1460
	public function setCollection(absences_Collection $collection)
1461
	{
1462
		$this->collection = $collection;
1463
	}
1464
1465
	/**
1466
	 * Create the agent iterator with agents associated to an organization
1467
	 * @param absences_Organization $organization
1468
	 */
1469
	public function setOrganization(absences_Organization $organization)
1470
	{
1471
	    $this->organization = $organization;
1472
	}
1473
1474
1475
	public function getObject($data)
1476
	{
1477
		$agent = new absences_Agent;
1478
		$agent->setRow($data);
1479
1480
1481
		if (isset($this->collection))
1482
		{
1483
			$agent->setCollection($this->collection);
1484
		}
1485
1486
		if (isset($this->organization))
1487
		{
1488
		    $agent->setOrganization($this->organization);
1489
		}
1490
1491
		return $agent;
1492
	}
1493
1494
	public function executeQuery()
1495
	{
1496
		if(is_null($this->_oResult))
1497
		{
1498
			global $babDB;
1499
1500
			$query = '
1501
				SELECT
1502
					a.*
1503
				FROM
1504
					absences_personnel a
1505
			';
1506
1507
			$where = array();
1508
1509 View Code Duplication
			if (isset($this->organization)) {
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...
1510
			    $where[] = 'a.id_organization='.$babDB->quote($this->organization->id).'';
1511
			}
1512
1513 View Code Duplication
			if (isset($this->collection)) {
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...
1514
				$where[] = 'a.id_coll='.$babDB->quote($this->collection->id).'';
1515
			}
1516
1517
			if (isset($this->right)) {
1518
				$query .= ', absences_users_rights ur';
1519
				$where[] = 'ur.id_user=a.id_user';
1520
				$where[] = 'ur.id_right='.$babDB->quote($this->right->id);
1521
			}
1522
1523
			if (isset($this->exclude_users)) {
1524
			    $where[] = 'a.id_user NOT IN('.$babDB->quote($this->exclude_users).')';
1525
			}
1526
1527
			if ($where) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $where of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1528
			     $query.= ' WHERE '.implode(' AND ', $where);
1529
			}
1530
1531
			$this->setMySqlResult($this->getDataBaseAdapter()->db_query($query));
1532
		}
1533
	}
1534
1535
}