absences_Agent::isSharedCalendarEntity()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
eloc 8
c 0
b 0
f 0
nc 3
nop 1
dl 0
loc 16
rs 9.4285
ccs 0
cts 9
cp 0
crap 12
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
	    try {
229
	        $this->organization->getRow();
230
	    } catch (Exception $e) {
231
	        return null;
232
	    }
233
	    
234
	    return $this->organization;
235
	}
236
237
238
239
240
241
	/**
242
	 * @return string
243
	 */
244 8
	public function getName()
245
	{
246 8
		return bab_getUserName($this->getIdUser());
247
	}
248
249
250
251
	/**
252
	 * Table row as an array
253
	 * @return array
254
	 */
255 4
	public function getRow()
256
	{
257 4
		if (null === $this->row)
258 4
		{
259
			global $babDB;
260
261
			$query = 'SELECT * FROM absences_personnel WHERE ';
262
			if (isset($this->id))
263
			{
264
				$query .= 'id='.$babDB->quote($this->id);
265
			}
266
267
			if (isset($this->id_user))
268
			{
269
				$query .= 'id_user='.$babDB->quote($this->id_user);
270
			}
271
272
			$res = $babDB->db_query($query);
273
			$row = $babDB->db_fetch_assoc($res);
274
275
			if (!$row)
276
			{
277
				throw new Exception('This agent does not exists id='.$this->id.' id_user='.$this->id_user);
278
			}
279
280
			$this->setRow($row);
281
282
			return $this->row;
283
		}
284
285 4
		return $this->row;
286
	}
287
288
289
	/**
290
	 * Test if agent exists in personnel members
291
	 * @return bool
292
	 */
293
	public function exists()
294
	{
295
		try {
296
			$row = $this->getRow();
297
		} catch(Exception $e)
298
		{
299
			return false;
300
		}
301
302
		return (false !== $row);
303
	}
304
305
306
307
	/**
308
	 * All agent requests sorted by creation date
309
	 *
310
	 * @return absences_RequestIterator
311
	 */
312
	public function getRequestIterator()
313
	{
314
		require_once dirname(__FILE__).'/request.class.php';
315
		$I = new absences_RequestIterator(array($this->getIdUser()));
316
317
		return $I;
318
	}
319
320
321
322
	/**
323
 	 * iterateur des droits d'un agent, vue utilisateur au moment de la demande
324
 	 * droit ouverts, ordonnes alphabetiquement
325
	 *
326
	 * @return absences_AgentRightUserIterator
327
	 */
328
	public function getAgentRightUserIterator()
329
	{
330
		require_once dirname(__FILE__).'/agent_right.class.php';
331
		$I = new absences_AgentRightUserIterator;
332
		$I->setAgent($this);
333
334
		return $I;
335
	}
336
337
338
339
	/**
340
	 * iterateur des droits d'un agent, vue gestionnaire
341
 	 * tout les droits associes a l'agent, ordonnes par annees, puis alphabetiquement
342
	 *
343
	 * @return absences_AgentRightManagerIterator
344
	 */
345
	public function getAgentRightManagerIterator()
346
	{
347
		require_once dirname(__FILE__).'/agent_right.class.php';
348
		$I = new absences_AgentRightManagerIterator;
349
		$I->setAgent($this);
350
351
		return $I;
352
	}
353
354
355
356
357
358
	/**
359
	 * Add a vacation right to the agent
360
	 * return true if inserted or if already exists
361
	 *
362
	 * @param	absences_Right	$right
363
	 * @return bool
364
	 */
365
	public function addRight(absences_Right $right)
366
	{
367
		global $babDB;
368
		$babDB->db_queryWem('INSERT INTO absences_users_rights (id_user, id_right) 
369
				VALUES ('.$babDB->quote($this->getIdUser()).', '.$babDB->quote($right->id).')');
370
371
		$this->addMovement(sprintf(absences_translate('The right %s has been assigned to the user %s'), $right->description, $this->getName()));
372
373
		return true;
374
	}
375
376
377
	/**
378
	 * Add fixed entry if the right is FIXED
379
	 *
380
	 * @throws absences_EntryException
381
	 *
382
	 * @param	absences_Right	$right
383
	 * @param 	bool			$notify
384
	 *
385
	 * @return bool
386
	 */
387
	public function addFixedEntry(absences_Right $right, $notify = true)
388
	{
389
		if( absences_Right::FIXED !== $right->getKind() ) {
390
		    return false;
391
		}
392
393
394
		if (absences_addFixedVacation($this->getIdUser(), $right))
395
		{
396
			if ($notify)
397
			{
398
				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...
399
			}
400
401
			return true;
402
		}
403
404
		return false;
405
	}
406
407
408
	/**
409
	 * Add fixed entry if the right is FIXED
410
	 *
411
	 * @throws absences_EntryException
412
	 *
413
	 * @param	absences_Right	$right
414
	 * @param 	bool			$notify
415
	 *
416
	 * @return bool
417
	 */
418
	public function addFixedEntryIfNotExists(absences_Right $right, $notify = true)
419
	{
420
	    if( absences_Right::FIXED !== $right->getKind()) {
421
	        return false;
422
	    }
423
424
	    if (absences_isFixedCreated($this->getIdUser(), $right->id)) {
425
	        return false;
426
	    }
427
428
	    return $this->addFixedEntry($right, $notify);
429
	}
430
431
432
433
	/**
434
	 * Remove vacation right from agent
435
	 * Ne pas autoriser si le regime de l'agent est liee au droit
436
	 * return true if link removed or does not exists, return false if remove failed (ex because of collection assignement)
437
	 *
438
	 * @param	absences_Right	$right
439
	 * @return bool
440
	 */
441
	public function removeRight(absences_Right $right)
442
	{
443
444
		$collection = $this->getCollection();
445
		if ($collection->isLinkedToRight($right))
446
		{
447
			// empecher la suppression du lien agent-droit tant que le regime force le lien
448
			return false;
449
		}
450
451
		require_once dirname(__FILE__).'/agent_right.class.php';
452
453
		$agentRight = new absences_AgentRight();
454
		$agentRight->setAgent($this);
455
		$agentRight->setRight($right);
456
457
		if (!$agentRight->getRow())
458
		{
459
			// le lien n'existe pas
460
			return false;
461
		}
462
463
464
		$agentRight->delete();
465
466
		$this->addMovement(sprintf(absences_translate('The right %s has been unassigned from the user %s'), $right->description, $this->getName()));
467
468
		return true;
469
	}
470
471
	/**
472
	 * remove fixed entry if the right is FIXED
473
	 * @param	absences_Right	$right
474
	 * @param 	bool			$notify
475
	 * @return absences_Agent
476
	 */
477
	public function removeFixedEntry(absences_Right $right, $notify = true)
478
	{
479
		if( absences_Right::FIXED === $right->getKind() )
480
		{
481
			global $babDB;
482
483
484
			$res = $babDB->db_query("
485
			    SELECT
486
			         vet.*,
487
			         veet.quantity
488
489
			    from absences_entries_elem veet
490
			         left join absences_entries vet on veet.id_entry=vet.id
491
			    where
492
			         veet.id_right=".$babDB->quote($right->id)."
493
			         and vet.id_user=".$babDB->quote($this->getIdUser())
494
			);
495
496
			while ($arr = $babDB->db_fetch_assoc($res)) {
497
498
			    if (absences_removeFixedVacation( $arr['id'])) {
499
			        if ($notify) {
500
			            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...
501
			        }
502
			    }
503
			}
504
505
		}
506
507
		return $this;
508
	}
509
510
511
512
	/**
513
	 * Test if right is linked to collection
514
	 * @param absences_Right $right
515
	 * @return boolean
516
	 */
517 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...
518
	{
519
		require_once dirname(__FILE__).'/agent_right.class.php';
520
521
		$link = new absences_AgentRight;
522
		$link->setAgent($this);
523
		$link->setRight($right);
524
		$row = $link->getRow();
525
526
		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...
527
		{
528
			return true;
529
		}
530
		return false;
531
	}
532
533
534
	/**
535
	 * Get organizational chart main entity or null
536
	 * @return array
537
	 */
538
	public function getMainEntity()
539
	{
540
		if (!isset($this->ocentity))
541
		{
542
			$id_oc = absences_getVacationOption('id_chart');
543
544
			require_once $GLOBALS['babInstallPath'].'utilit/ocapi.php';
545
			$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...
546
		}
547
548
		return $this->ocentity;
549
	}
550
551
	/**
552
	 * Get approbation scheme informations
553
	 * @return array
554
	 */
555
	public function getApprobation()
556
	{
557
		if (empty($this->id_sa))
558
		{
559
			return null;
560
		}
561
562
		if (null === $this->approbation)
563
		{
564
			require_once $GLOBALS['babInstallPath'].'utilit/wfincl.php';
565
			$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...
566
		}
567
568
		return $this->approbation;
569
	}
570
571
572
	/**
573
	 * Get superior if the agent is in organizational chart
574
	 * @return array
575
	 */
576
	public function getSuperior()
577
	{
578
	    require_once $GLOBALS['babInstallPath'].'utilit/afincl.php';
579
	    
580
	    $id_oc = absences_getVacationOption('id_chart');
581
	    
582
	    $superior = bab_getSupervisor((int) $this->id_user, $id_oc, 0);
583
	    
584
	    if (!isset($superior['name']) || 0 === count($superior['name'])) {
585
	        return null;
586
	    }
587
	    
588
	    return $superior;
589
	}
590
591
592
593
	/**
594
	 * Get directory entry
595
	 * @return array
596
	 */
597 1
	public function getDirEntry()
598
	{
599 1
		if (!isset($this->direntry))
600 1
		{
601 1
			$this->direntry = bab_admGetDirEntry($this->getIdUser(), BAB_DIR_ENTRY_ID_USER);
602 1
		}
603
604 1
		return $this->direntry;
605
	}
606
607
608
	/**
609
	 * Date contenue dans la fiche d'annuaire
610
	 * formats autorises :
611
	 * 		DD/MM/YYYY
612
	 * 		DD/MM/YY
613
	 * 		D/M/YYYY
614
	 * 		DD-MM-YYYY
615
	 * 		DD-MM-YY
616
	 * 		D-M-YYYY
617
	 *
618
	 * @param string $fieldname
619
	 *
620
	 * @return string		ISO date
621
	 */
622
	public function getDirEntryDate($fieldname)
623
	{
624
		$direntry = $this->getDirEntry();
625
		if (!isset($direntry[$fieldname]))
626
		{
627
			return null;
628
		}
629
630
		$value = $direntry[$fieldname]['value'];
631
632
		if ('' === $value)
633
		{
634
			return null;
635
		}
636
637
		if (!preg_match('#([0-9]{1,2})(?:/|-)([0-9]{1,2})(?:/|-)([0-9]{2,4})#', $value, $m))
638
		{
639
			return null;
640
		}
641
642
		return sprintf('%04d-%02d-%02d', (int) $m[3], (int) $m[2], (int) $m[1]);
643
	}
644
645
646
647
	/**
648
	 * @return bab_dirEntryPhoto
649
	 */
650
	private function getDirEntryPhoto()
651
	{
652
		$entry = $this->getDirEntry();
653
		if (isset($entry['jpegphoto']['photo']))
654
		{
655
			return $entry['jpegphoto']['photo'];
656
		}
657
658
		return null;
659
	}
660
661
	/**
662
	 * Get icon url only if thumbnailer is present (16x16)
663
	 * @return string
664
	 */
665
	public function getIcon()
666
	{
667
		$T = bab_functionality::get('Thumbnailer');
668
669
		if ($T && $photo = $this->getDirEntryPhoto())
670
		{
671
			$photo->setThumbSize(16, 16);
672
			return $photo->getUrl();
673
		}
674
675
		return null;
676
	}
677
678
	/**
679
	 * Get a small photo to display in agent page or requests page (64x64)
680
	 * if the thumbnailer is not present photo is not resized
681
	 * @return string
682
	 */
683
	public function getPhoto()
684
	{
685
		if ($photo = $this->getDirEntryPhoto())
686
		{
687
			$photo->setThumbSize(64, 64);
688
			return $photo->getUrl();
689
		}
690
691
		return null;
692
	}
693
694
695
696
	/**
697
	 * @return bool
698
	 */
699 2
	public function isInPersonnel()
700
	{
701 2
		global $babDB;
702
703
		try {
704
705 2
			$id_user = $this->getIdUser();
706
707 2
		} catch(Exception $e) {
708
			bab_debug($e->getMessage());
709
			return false;
710
		}
711
712 2
		$res = $babDB->db_query("select id from absences_personnel where id_user='".$babDB->db_escape_string($id_user)."'");
713 2
		if( $res && $babDB->db_num_rows($res) > 0)
714 2
		{
715 1
			return true;
716
		}
717
718 1
		return false;
719
	}
720
721
	/**
722
	 * Test if the user have access to at least one vacation right
723
	 * si les droits accessibles ont un solde a 0, la fonction renvoi true malgre tout, seul le nombre de droit accessible est teste
724
	 * (certains droits peuvent accepter les soldes negatifs)
725
	 * @return bool
726
	 */
727
	public function haveRights()
728
	{
729
		$I = $this->getAgentRightUserIterator();
730
731
		return ($I->count() > 0);
732
	}
733
734
735
736
	/**
737
	 * @return bool
738
	 */
739
	public function isManager()
740
	{
741
		return bab_isAccessValid('absences_managers_groups', 1, $this->getIdUser());
742
743
	}
744
745
	/**
746
	 * Test si l'agent est un approbateur
747
	 * @param	int	$id_user	test si l'agent est l'approbateur d'un demandeur en particulier
748
	 * @return bool
749
	 */
750
	public function isApprover($id_user = null)
751
	{
752
		global $babDB;
753
754
		$arrchi = bab_getWaitingIdSAInstance($this->getIdUser());
755
		$query = "SELECT idfai from ".ABSENCES_ENTRIES_TBL."  where status='' AND idfai IN(".$babDB->quote($arrchi).")";
756
		if (isset($id_user))
757
		{
758
			$query .= " AND id_user=".$babDB->quote($id_user);
759
		}
760
761
		$res = $babDB->db_query($query);
762
		if( $res && $babDB->db_num_rows($res) > 0)
763
		{
764
			return true;
765
		}
766
767
		return false;
768
	}
769
770
771
772
773
	/**
774
	 * Liste des entites gerees par la gestion deleguee
775
	 * @return array
776
	 */
777
	public function getManagedEntities()
778
	{
779
		if (!isset($this->managed_entities))
780
		{
781
			$id_oc = absences_getVacationOption('id_chart');
782
783
			require_once $GLOBALS['babInstallPath'].'utilit/ocapi.php';
784
785
			$userentities = bab_OCGetUserEntities($this->getIdUser(), $id_oc);
786
			absences_addCoManagerEntities($userentities, $this->getIdUser());
787
788
			$this->managed_entities = array();
789
790
			foreach ($userentities['superior'] as $entity)
791
			{
792
				$this->managed_entities[] = $entity;
793
				$children = bab_OCGetChildsEntities($entity['id'], $id_oc);
794
				$this->managed_entities = array_merge($this->managed_entities, $children);
795
			}
796
797
		}
798
		return $this->managed_entities;
799
	}
800
801
	/**
802
	 * Access a la gestion delegee
803
	 * @return bool
804
	 */
805
	public function isEntityManager()
806
	{
807
		$arr = $this->getManagedEntities();
808
809
		return (count($arr) > 0);
810
	}
811
812
813
	/**
814
	 * Gestionnaire delegue de l'entite
815
	 * @param int $id_entity
816
	 * @return bool
817
	 */
818
	public function isEntityManagerOf($id_entity)
819
	{
820
		$managed_entities = $this->getManagedEntities();
821
822
		foreach($managed_entities as $entity)
823
		{
824
			if ($id_entity == $entity['id'])
825
			{
826
				return true;
827
			}
828
		}
829
830
		return false;
831
	}
832
833
834
835
	/**
836
	 * Tester si l'agent est le supperieur d'un autre agent
837
	 * @param absences_Agent $agent
838
	 * @return bool
839
	 */
840
	public function isSuperiorOf(absences_Agent $agent)
841
	{
842
	    if ($agent->getIdUser() === $this->getIdUser())
843
	    {
844
	        return false;
845
	    }
846
847
		$user_entities_id = $agent->getMemberEntityIds();
848
		$managed_entities = $this->getManagedEntities();
849
850
		foreach($managed_entities as $entity)
851
		{
852
			if (isset($user_entities_id[$entity['id']]))
853
			{
854
				return true;
855
			}
856
		}
857
		return false;
858
	}
859
860
861
862
863
	/**
864
	 * Liste des entites autorises pour les visualisation de planning
865
	 * @return array
866
	 */
867
	public function getCalendarEntities()
868
	{
869
		if (!isset($this->calendar_entities))
870
		{
871
			global $babDB;
872
873
			$id_oc = absences_getVacationOption('id_chart');
874
875
			$this->calendar_entities = array();
876
			$res = $babDB->db_query("SELECT id_entity FROM absences_planning WHERE id_user=".$babDB->quote($this->getIdUser()));
877
			while ($arr = $babDB->db_fetch_assoc($res)) {
878
				$this->calendar_entities[$arr['id_entity']] = $arr['id_entity'];
879
				$tmp = bab_OCGetChildsEntities($arr['id_entity'], $id_oc);
880
881
				foreach($tmp as $entity) {
882
					$this->calendar_entities[$entity['id']] = $entity['id'];
883
				}
884
			}
885
		}
886
887
		return $this->calendar_entities;
888
	}
889
890
	/**
891
	 * Tester si l'agent a les droits pour voir le planning d'un autre agent
892
	 * @param absences_Agent $agent
893
	 * @return bool
894
	 */
895
	public function canViewCalendarOf(absences_Agent $agent)
896
	{
897
	    if ($this->isManager())
898
	    {
899
	        return true;
900
	    }
901
	    
902
	    if ($this->isSuperiorOf($agent))
903
	    {
904
	        return true;
905
	    }
906
	    
907
	    if ($this->isApprover($agent->getIdUser()))
908
	    {
909
	        return true;
910
	    }
911
	    
912
	    if (!$agent->isInPersonnel())
913
		{
914
			return false;
915
		}
916
917
		if ($this->getIdUser() === $agent->getIdUser())
918
		{
919
			return true;
920
		}
921
		
922
		if ($this->isSharedCalendarEntity($agent))
923
		{
924
			return true;
925
		}
926
927
		if ($this->isInSameEntityPlanning($agent))
928
		{
929
			return true;
930
		}
931
932
		return false;
933
	}
934
935
936
937
938
	/**
939
	 * listes des entities de l'agent
940
	 * @return array
941
	 */
942
	public function getMemberEntities()
943
	{
944
		$id_oc = absences_getVacationOption('id_chart');
945
		$arr = bab_OCGetUserEntities($this->getIdUser(), $id_oc);
946
		return array_merge($arr['superior'], $arr['temporary'], $arr['members']);
947
	}
948
949
	/**
950
	 * Liste des ID des entites de l'agent
951
	 * @return array
952
	 */
953
	public function getMemberEntityIds()
954
	{
955
		$user_entities_id = array();
956
		foreach($this->getMemberEntities() as $entity)
957
		{
958
			$user_entities_id[$entity['id']] = $entity['id'];
959
		}
960
961
		return $user_entities_id;
962
	}
963
964
965
	/**
966
	 * Tester si l'agent a acces au planning de l'agent passe en parametre en passant par le partage de planning des entites
967
	 * @param	absences_Agent $agent
968
	 * @return bool
969
	 */
970
	public function isSharedCalendarEntity(absences_Agent $agent)
971
	{
972
		$calendar_entities = $this->getCalendarEntities(); // entites agendas autorises en partage
973
		$user_entities = $agent->getMemberEntities(); // entites de l'utilisteur que l'on cherche a visualiser
974
975
		foreach($user_entities as $entity) {
976
977
			$id_entity = (int) $entity['id'];
978
979
			if (array_key_exists($id_entity, $calendar_entities)) {
980
				return true;
981
			}
982
		}
983
984
		return false;
985
	}
986
987
988
989
	/**
990
	 * Tester si l'agent passe en parametre est dans le  meme planning de service et que la visualisation du planning de service est activee
991
	 * @param absences_Agent $agent
992
	 * @return bool
993
	 */
994
	public function isInSameEntityPlanning(absences_Agent $agent)
995
	{
996
		if (0 === (int) absences_getVacationOption('entity_planning'))
997
		{
998
			return false;
999
		}
1000
1001
1002
		if ($this->getIdUser() === $agent->getIdUser())
1003
		{
1004
			return true;
1005
		}
1006
1007
		$myEntity = $this->getMainEntity();
1008
		$agentEntity = $agent->getMainEntity();
1009
1010
		if ($myEntity['id'] === $agentEntity['id'])
1011
		{
1012
			return true;
1013
		}
1014
1015
		return false;
1016
	}
1017
	
1018
	
1019
	public function canViewCustomPlanning($id_planning)
1020
	{
1021
	    return bab_isAccessValid('absences_custom_planning_groups', $id_planning,  $this->getIdUser());
1022
	}
1023
1024
1025
	/**
1026
	 * Tester si l'agent peut voir le planning d'une autre entite
1027
	 *
1028
	 * @return bool
1029
	 */
1030
	public function canViewEntityPlanning($id_entity = null)
1031
	{
1032
	    if ($this->isManager()) {
1033
	        return true;
1034
	    }
1035
	    
1036
	    
1037
		// cas possible avec le partage de planning
1038
1039
		$calendars = $this->getCalendarEntities();
1040
1041
		if (isset($calendars[$id_entity]))
1042
		{
1043
			return true;
1044
		}
1045
1046
		// si supperieur de l'entite
1047
1048
		if ($this->isEntityManagerOf($id_entity))
1049
		{
1050
			return true;
1051
		}
1052
1053
		// si planning du service
1054
1055
		$myEntity = $this->getMainEntity();
1056
		if ((int) $id_entity === (int) $myEntity['id'] && 1 === (int) absences_getVacationOption('entity_planning')) {
1057
		    return true;
1058
		}
1059
1060
1061
		return false;
1062
	}
1063
1064
	/**
1065
	 * Tester si l'agent peut voir le planning de son entite principale
1066
	 */
1067
	public function canViewMainEntityPlanning()
1068
	{
1069
		$myEntity = $this->getMainEntity();
1070
1071
		return $this->canViewEntityPlanning($myEntity['id']);
1072
	}
1073
1074
1075
1076
	/**
1077
	 * Declaration de jours travailles donnant droit a recuperation
1078
	 * @return bool
1079
	 */
1080
	public function canCreateWorkperiodRecoverRequest()
1081
	{
1082
		$workperiod = (bool) absences_getVacationOption('workperiod_recover_request');
1083
1084
		if (!$workperiod)
1085
		{
1086
			return false;
1087
		}
1088
1089
		if (!$this->isInPersonnel())
1090
		{
1091
			return false;
1092
		}
1093
1094
		return true;
1095
	}
1096
1097
1098
	/**
1099
	 * @return absences_AgentCet
1100
	 */
1101
	public function Cet()
1102
	{
1103
		if (!isset($this->cet))
1104
		{
1105
			require_once dirname(__FILE__).'/agent_cet.class.php';
1106
			$this->cet = new absences_AgentCet($this);
1107
1108
		}
1109
1110
		return $this->cet;
1111
	}
1112
1113
1114
	/**
1115
	 * Approbation sheme ID
1116
	 * @return int
1117
	 */
1118
	public function getApprobationId()
1119
	{
1120
		return (int) $this->id_sa;
1121
	}
1122
1123
1124
	/**
1125
	 * Approbation sheme ID from recover request
1126
	 * @return int
1127
	 */
1128
	public function getRecoverApprobationId()
1129
	{
1130
		$id_sa_recover = (int) $this->id_sa_recover;
1131
		if (0 === $id_sa_recover)
1132
		{
1133
			return $this->getApprobationId();
1134
		}
1135
1136
		return $id_sa_recover;
1137
	}
1138
1139
1140
	/**
1141
	 * Approbation sheme ID from cet request
1142
	 * @return int
1143
	 */
1144
	public function getCetApprobationId()
1145
	{
1146
		$id_sa_cet = (int) $this->id_sa_cet;
1147
		if (0 === $id_sa_cet)
1148
		{
1149
			return $this->getApprobationId();
1150
		}
1151
1152
		return $id_sa_cet;
1153
	}
1154
1155
1156
	/**
1157
	 * Create reports for expired rights of agent
1158
	 *
1159
	 */
1160
	public function createReports()
1161
	{
1162
		$res = $this->getAgentRightManagerIterator();
1163
1164
		foreach($res as $agentRight)
1165
		{
1166
			/*@var $agentRight absences_AgentRight */
1167
1168
			$agentRight->createReport();
1169
		}
1170
1171
	}
1172
	
1173
	
1174
1175
	private function getRecoveryRgroup($quantity_unit)
1176
	{
1177
	    global $babDB;
1178
	
1179
	    $res = $babDB->db_query("SELECT id FROM absences_rgroup WHERE recover='1' AND quantity_unit=".$babDB->quote($quantity_unit));
1180
	
1181
	    if ($babDB->db_num_rows($res) == 0)
1182
	    {
1183
	        return 0;
1184
	    }
1185
	
1186
	    $row = $babDB->db_fetch_assoc($res);
1187
	
1188
	    return $row['id'];
1189
	}
1190
	
1191
	
1192
	
1193
	/**
1194
	 * Create a recovery right for the agent
1195
	 * and return the id_right
1196
	 * 
1197
	 * @param string $begin            ISO date YYYY-MM-DD
1198
	 * @param string $end              ISO date YYYY-MM-DD
1199
	 * @parap string $description
1200
	 * @param float $quantity
1201
	 * @param string $quantity_unit D|H
1202
	 * 
1203
	 * @return int
1204
	 */
1205
	public function createRecoveryRight($begin, $end, $description, $quantity, $quantity_unit)
1206
	{
1207
        require_once dirname(__FILE__).'/right.class.php';
1208
        global $babDB;
1209
1210
1211
	    $babDB->db_query('INSERT INTO absences_rights
1212
				(
1213
					kind,
1214
					description,
1215
	                createdOn,
1216
					date_entry,
1217
					date_begin,
1218
					date_end,
1219
					cbalance,
1220
					id_type,
1221
					id_rgroup,
1222
					quantity,
1223
					quantity_unit,
1224
					use_in_cet,
1225
					no_distribution,
1226
        	        date_begin_valid,
1227
        	        date_end_valid,
1228
	                hide_empty
1229
				)
1230
	    
1231
			VALUES (
1232
					'.$babDB->quote(absences_Right::RECOVERY).',
1233
					'.$babDB->quote($description).',
1234
	                CURDATE(),
1235
					CURDATE(),
1236
					'.$babDB->quote($begin).',
1237
					'.$babDB->quote($end).',
1238
					'.$babDB->quote('N').',
1239
					'.$babDB->quote(absences_getRecoveryType()).',
1240
					'.$babDB->quote($this->getRecoveryRgroup($quantity_unit)).',
1241
					'.$babDB->quote($quantity).',
1242
					'.$babDB->quote($quantity_unit).',
1243
					'.$babDB->quote(0).',
1244
					'.$babDB->quote(1).',
1245
					'.$babDB->quote($begin).',
1246
					'.$babDB->quote($end).',
1247
	                '.$babDB->quote(1).'
1248
				)');
1249
	    
1250
	    $id_right = $babDB->db_insert_id();
1251
	    
1252
	    
1253
	    $babDB->db_query('INSERT INTO absences_rights_rules
1254
				(
1255
					id_right
1256
				)
1257
			VALUES
1258
				(
1259
					'.$babDB->quote($id_right).'
1260
				)
1261
	    
1262
		');
1263
	    
1264
	    
1265
	    $babDB->db_query('INSERT INTO absences_rights_inperiod
1266
				(
1267
					id_right,
1268
					period_start,
1269
					period_end,
1270
					right_inperiod
1271
				)
1272
			VALUES
1273
				(
1274
					'.$babDB->quote($id_right).',
1275
					'.$babDB->quote($begin).',
1276
					'.$babDB->quote($end).',
1277
					'.$babDB->quote(1).'
1278
				)
1279
		');
1280
	    
1281
	    
1282
	    $babDB->db_query('INSERT INTO absences_users_rights
1283
			(
1284
				id_right,
1285
				id_user
1286
			)
1287
			VALUES
1288
			(
1289
				'.$babDB->quote($id_right).',
1290
				'.$babDB->quote($this->getIdUser()).'
1291
			)
1292
		');
1293
	    
1294
	    return $id_right;
1295
	}
1296
1297
1298
1299
	/**
1300
	 * Movements related to the agent
1301
	 * @return absences_MovementIterator
1302
	 */
1303
	public function getMovementIterator()
1304
	{
1305
		require_once dirname(__FILE__).'/movement.class.php';
1306
1307
		$I = new absences_MovementIterator();
1308
		$I->setAgent($this);
1309
1310
		return $I;
1311
	}
1312
1313
1314
	/**
1315
	 *
1316
	 * @param string $message	Generated message
1317
	 * @param string $comment	Author comment
1318
	 */
1319
	public function addMovement($message, $comment = '')
1320
	{
1321
		require_once dirname(__FILE__).'/movement.class.php';
1322
1323
		$movement = new absences_Movement();
1324
		$movement->message = $message;
1325
		$movement->comment = $comment;
1326
		$movement->setAgent($this);
1327
		$movement->save();
1328
	}
1329
1330
1331
	public function delete()
1332
	{
1333
		global $babDB;
1334
1335
		$id_user = $this->getIdUser();
1336
		absences_clearUserCalendar($id_user);
1337
1338
		$I = $this->getRequestIterator();
1339
		foreach($I as $request)
1340
		{
1341
			$request->delete();
1342
		}
1343
1344
		$babDB->db_query("delete from ".ABSENCES_USERS_RIGHTS_TBL." where id_user='".$babDB->db_escape_string($id_user)."'");
1345
		$babDB->db_query("delete from ".ABSENCES_PERSONNEL_TBL." where id_user='".$babDB->db_escape_string($id_user)."'");
1346
1347
		$babDB->db_query("delete from absences_comanager where id_user='".$babDB->db_escape_string($id_user)."'");
1348
		$babDB->db_query("delete from absences_planning where id_user='".$babDB->db_escape_string($id_user)."'");
1349
1350
1351
1352
	}
1353
1354
1355
1356
	public function setEmails($emails)
1357
	{
1358
		global $babDB;
1359
		$id_user = $this->getIdUser();
1360
1361
		$babDB->db_query('UPDATE absences_personnel SET emails='.$babDB->quote($emails).' WHERE id_user='.$babDB->quote($id_user));
1362
	}
1363
1364
	/**
1365
	 * @return array
1366
	 */
1367
	public function getEmails()
1368
	{
1369
		return preg_split('/\s*,\s*/', $this->emails);
1370
	}
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
	/**
1385
	 * Set organization of agent from the "organizationname" field of the directory entry
1386
	 * if possible or return false if the organization does not exists
1387
	 *
1388
	 * @return bool
1389
	 */
1390
	public function setOrganizationFromDirEntry()
1391
	{
1392
	    global $babDB;
1393
	    $entry = $this->getDirEntry();
1394
	    
1395
	    if (!isset($entry)||false === $entry||0 === count($entry)) {
1396
	        throw new Exception(absences_translate('Directory entry not found'));
1397
	    }
1398
	    
1399
	    if (empty($entry['organisationname']) || empty($entry['organisationname']['value'])) {
1400
	        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'));
1401
	    }
1402
	    
1403
	    $organization = absences_Organization::getByName($entry['organisationname']['value']);
1404
1405
	    if (!isset($organization)) {
1406
	        throw new Exception(
1407
	            sprintf(
1408
	                absences_translate('Organization not found in absences for "%s"'), 
1409
	                $entry['organisationname']['value']
1410
		        )
1411
		    );
1412
	    }
1413
1414
	    $this->setOrganization($organization);
1415
1416
	    $babDB->db_query('UPDATE absences_personnel SET
1417
					id_organization='.$babDB->quote($organization->id).'
1418
				WHERE
1419
					id_user='.$babDB->quote($this->getIdUser()));
1420
1421
	    return true;
1422
	}
1423
}
1424
1425
1426
1427
1428
1429
1430
1431
1432
class absences_AgentIterator extends absences_Iterator
1433
{
1434
    /**
1435
     * @var absences_Collection
1436
     */
1437
	protected $collection;
1438
1439
	/**
1440
	 * @var absences_Right
1441
	 */
1442
	protected $right;
1443
1444
	/**
1445
	 * @var absences_Organization
1446
	 */
1447
	protected $organization;
1448
1449
	/**
1450
	 * @var array
1451
	 */
1452
	public $exclude_users;
1453
1454
	/**
1455
	 * Create an agent iterator with agent associated to a vacation right
1456
	 * @param absences_Right $right
1457
	 */
1458
	public function setRight(absences_Right $right)
1459
	{
1460
		$this->right = $right;
1461
	}
1462
1463
	/**
1464
	 * Create an agent iterator with agents associated to a collection
1465
	 * @param absences_Collection $collection
1466
	 */
1467
	public function setCollection(absences_Collection $collection)
1468
	{
1469
		$this->collection = $collection;
1470
	}
1471
1472
	/**
1473
	 * Create the agent iterator with agents associated to an organization
1474
	 * @param absences_Organization $organization
1475
	 */
1476
	public function setOrganization(absences_Organization $organization)
1477
	{
1478
	    $this->organization = $organization;
1479
	}
1480
1481
1482
	public function getObject($data)
1483
	{
1484
		$agent = new absences_Agent;
1485
		$agent->setRow($data);
1486
1487
1488
		if (isset($this->collection))
1489
		{
1490
			$agent->setCollection($this->collection);
1491
		}
1492
1493
		if (isset($this->organization))
1494
		{
1495
		    $agent->setOrganization($this->organization);
1496
		}
1497
1498
		return $agent;
1499
	}
1500
1501
	public function executeQuery()
1502
	{
1503
		if(is_null($this->_oResult))
1504
		{
1505
			global $babDB;
1506
1507
			$query = '
1508
				SELECT
1509
					a.*
1510
				FROM
1511
					absences_personnel a
1512
			';
1513
1514
			$where = array();
1515
1516 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...
1517
			    $where[] = 'a.id_organization='.$babDB->quote($this->organization->id).'';
1518
			}
1519
1520 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...
1521
				$where[] = 'a.id_coll='.$babDB->quote($this->collection->id).'';
1522
			}
1523
1524
			if (isset($this->right)) {
1525
				$query .= ', absences_users_rights ur';
1526
				$where[] = 'ur.id_user=a.id_user';
1527
				$where[] = 'ur.id_right='.$babDB->quote($this->right->id);
1528
			}
1529
1530
			if (isset($this->exclude_users)) {
1531
			    $where[] = 'a.id_user NOT IN('.$babDB->quote($this->exclude_users).')';
1532
			}
1533
1534
			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...
1535
			     $query.= ' WHERE '.implode(' AND ', $where);
1536
			}
1537
1538
			$this->setMySqlResult($this->getDataBaseAdapter()->db_query($query));
1539
		}
1540
	}
1541
1542
}