Passed
Branch develop (a7390e)
by
unknown
25:38
created

UserGroup::_load_ldap_dn()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 6
c 0
b 0
f 0
nc 8
nop 2
dl 0
loc 9
rs 10
1
<?php
2
/* Copyright (c) 2005       Rodolphe Quiedeville <[email protected]>
3
 * Copyright (c) 2005-2018	Laurent Destailleur	 <[email protected]>
4
 * Copyright (c) 2005-2018	Regis Houssin		 <[email protected]>
5
 * Copyright (C) 2012		Florian Henry		 <[email protected]>
6
 * Copyright (C) 2014		Juanjo Menent		 <[email protected]>
7
 * Copyright (C) 2014		Alexis Algoud		 <[email protected]>
8
 * Copyright (C) 2018       Nicolas ZABOURI		 <[email protected]>
9
 *
10
 * This program is free software; you can redistribute it and/or modify
11
 * it under the terms of the GNU General Public License as published by
12
 * the Free Software Foundation; either version 3 of the License, or
13
 * (at your option) any later version.
14
 *
15
 * This program is distributed in the hope that it will be useful,
16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
 * GNU General Public License for more details.
19
 *
20
 * You should have received a copy of the GNU General Public License
21
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
22
 */
23
24
/**
25
 *	 \file       htdocs/user/class/usergroup.class.php
26
 *	 \brief      File of class to manage user groups
27
 */
28
29
require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
30
if (! empty($conf->ldap->enabled)) require_once DOL_DOCUMENT_ROOT."/core/class/ldap.class.php";
31
32
33
/**
34
 *	Class to manage user groups
35
 */
36
class UserGroup extends CommonObject
37
{
38
	/**
39
	 * @var string ID to identify managed object
40
	 */
41
	public $element='usergroup';
42
43
	/**
44
	 * @var string Name of table without prefix where object is stored
45
	 */
46
	public $table_element='usergroup';
47
48
	/**
49
	 * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
50
	 * @var int
51
	 */
52
	public $ismultientitymanaged = 1;
53
54
    public $picto='group';
55
56
	/**
57
	 * @var int Entity of group
58
	 */
59
	public $entity;
60
61
	/**
62
	 * @var string
63
	 * @deprecated
64
	 * @see $name
65
	 */
66
	public $nom;
67
68
	/**
69
	 * @var string name
70
	 */
71
	public $name;			// Name of group
72
73
	public $globalgroup;	// Global group
74
75
	/**
76
     * Date creation record (datec)
77
     *
78
     * @var integer
79
     */
80
    public $datec;
81
82
	/**
83
     * Date modification record (tms)
84
     *
85
     * @var integer
86
     */
87
    public $datem;
88
89
	public $note;			// Description
90
91
	public $members=array();	// Array of users
92
93
	public $nb_rights;					// Number of rights granted to the user
94
95
	private $_tab_loaded=array();		// Array of cache of already loaded permissions
96
97
	public $oldcopy;		// To contains a clone of this when we need to save old properties of object
98
99
100
	/**
101
     *    Constructor de la classe
102
     *
103
     *    @param   DoliDb  $db     Database handler
104
     */
105
    public function __construct($db)
106
    {
107
        $this->db = $db;
108
        $this->nb_rights = 0;
109
    }
110
111
112
	/**
113
	 *  Charge un objet group avec toutes ses caracteristiques (except ->members array)
114
	 *
115
	 *	@param      int		$id				Id of group to load
116
	 *	@param      string	$groupname		Name of group to load
117
	 *  @param		boolean	$load_members	Load all members of the group
118
	 *	@return		int						<0 if KO, >0 if OK
119
	 */
120
	public function fetch($id = '', $groupname = '', $load_members = true)
121
	{
122
		global $conf;
123
124
		$sql = "SELECT g.rowid, g.entity, g.nom as name, g.note, g.datec, g.tms as datem";
125
		$sql.= " FROM ".MAIN_DB_PREFIX."usergroup as g";
126
		if ($groupname)
127
		{
128
			$sql.= " WHERE g.nom = '".$this->db->escape($groupname)."'";
129
		}
130
		else
131
		{
132
			$sql.= " WHERE g.rowid = ".$id;
133
		}
134
135
		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
136
		$result = $this->db->query($sql);
137
		if ($result)
138
		{
139
			if ($this->db->num_rows($result))
140
			{
141
				$obj = $this->db->fetch_object($result);
142
143
				$this->id = $obj->rowid;
144
				$this->ref = $obj->rowid;
145
				$this->entity = $obj->entity;
146
				$this->name = $obj->name;
147
				$this->nom = $obj->name; // Deprecated
148
				$this->note = $obj->note;
149
				$this->datec = $obj->datec;
150
				$this->datem = $obj->datem;
151
152
				if($load_members)
153
					$this->members=$this->listUsersForGroup();
154
155
156
				// Retreive all extrafield
157
				// fetch optionals attributes and labels
158
				$this->fetch_optionals();
159
160
161
				// Sav current LDAP Current DN
162
				//$this->ldap_dn = $this->_load_ldap_dn($this->_load_ldap_info(),0);
163
			}
164
			$this->db->free($result);
165
			return 1;
166
		}
167
		else
168
		{
169
			$this->error=$this->db->lasterror();
170
			return -1;
171
		}
172
	}
173
174
175
	/**
176
	 *  Return array of groups objects for a particular user
177
	 *
178
	 *  @param		int		$userid 		User id to search
179
	 *  @param		boolean	$load_members	Load all members of the group
180
	 *  @return		array     				Array of groups objects
181
	 */
182
	public function listGroupsForUser($userid, $load_members = true)
183
	{
184
		global $conf, $user;
185
186
		$ret=array();
187
188
		$sql = "SELECT g.rowid, ug.entity as usergroup_entity";
189
		$sql.= " FROM ".MAIN_DB_PREFIX."usergroup as g,";
190
		$sql.= " ".MAIN_DB_PREFIX."usergroup_user as ug";
191
		$sql.= " WHERE ug.fk_usergroup = g.rowid";
192
		$sql.= " AND ug.fk_user = ".$userid;
193
		if(! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
194
		{
195
			$sql.= " AND g.entity IS NOT NULL";
196
		}
197
		else
198
		{
199
			$sql.= " AND g.entity IN (0,".$conf->entity.")";
200
		}
201
		$sql.= " ORDER BY g.nom";
202
203
		dol_syslog(get_class($this)."::listGroupsForUser", LOG_DEBUG);
204
		$result = $this->db->query($sql);
205
		if ($result)
206
		{
207
			while ($obj = $this->db->fetch_object($result))
208
			{
209
				if (! array_key_exists($obj->rowid, $ret))
210
				{
211
					$newgroup=new UserGroup($this->db);
212
					$newgroup->fetch($obj->rowid, '', $load_members);
213
					$ret[$obj->rowid]=$newgroup;
214
				}
215
216
				$ret[$obj->rowid]->usergroup_entity[]=$obj->usergroup_entity;
217
			}
218
219
			$this->db->free($result);
220
221
			return $ret;
222
		}
223
		else
224
		{
225
			$this->error=$this->db->lasterror();
226
			return -1;
227
		}
228
	}
229
230
	/**
231
	 * 	Return array of User objects for group this->id (or all if this->id not defined)
232
	 *
233
	 * 	@param	string	$excludefilter		Filter to exclude
234
	 *  @param	int		$mode				0=Return array of user instance, 1=Return array of users id only
235
	 * 	@return	mixed						Array of users or -1 on error
236
	 */
237
	public function listUsersForGroup($excludefilter = '', $mode = 0)
238
	{
239
		global $conf, $user;
240
241
		$ret=array();
242
243
		$sql = "SELECT u.rowid";
244
		if (! empty($this->id)) $sql.= ", ug.entity as usergroup_entity";
245
		$sql.= " FROM ".MAIN_DB_PREFIX."user as u";
246
		if (! empty($this->id)) $sql.= ", ".MAIN_DB_PREFIX."usergroup_user as ug";
247
		$sql.= " WHERE 1 = 1";
248
		if (! empty($this->id)) $sql.= " AND ug.fk_user = u.rowid";
249
		if (! empty($this->id)) $sql.= " AND ug.fk_usergroup = ".$this->id;
250
		if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
251
		{
252
			$sql.= " AND u.entity IS NOT NULL";
253
		}
254
		else
255
		{
256
			$sql.= " AND u.entity IN (0,".$conf->entity.")";
257
		}
258
		if (! empty($excludefilter)) $sql.=' AND ('.$excludefilter.')';
259
260
		dol_syslog(get_class($this)."::listUsersForGroup", LOG_DEBUG);
261
		$resql = $this->db->query($sql);
262
		if ($resql)
263
		{
264
			while ($obj = $this->db->fetch_object($resql))
265
			{
266
				if (! array_key_exists($obj->rowid, $ret))
267
				{
268
					if ($mode != 1)
269
					{
270
						$newuser=new User($this->db);
271
						$newuser->fetch($obj->rowid);
272
						$ret[$obj->rowid]=$newuser;
273
					}
274
					else $ret[$obj->rowid]=$obj->rowid;
275
				}
276
				if ($mode != 1 && ! empty($obj->usergroup_entity))
277
				{
278
					$ret[$obj->rowid]->usergroup_entity[]=$obj->usergroup_entity;
279
				}
280
			}
281
282
			$this->db->free($resql);
283
284
			return $ret;
285
		}
286
		else
287
		{
288
			$this->error=$this->db->lasterror();
289
			return -1;
290
		}
291
	}
292
293
	/**
294
	 *    Add a permission to a group
295
	 *
296
	 *    @param	int		$rid		id du droit a ajouter
297
	 *    @param	string	$allmodule	Ajouter tous les droits du module allmodule
298
	 *    @param	string	$allperms	Ajouter tous les droits du module allmodule, perms allperms
299
	 *    @param	int		$entity		Entity to use
300
	 *    @return	int					> 0 if OK, < 0 if KO
301
	 */
302
	public function addrights($rid, $allmodule = '', $allperms = '', $entity = 0)
303
	{
304
		global $conf, $user, $langs;
305
306
		$entity = (! empty($entity)?$entity:$conf->entity);
307
308
		dol_syslog(get_class($this)."::addrights $rid, $allmodule, $allperms, $entity");
309
		$error=0;
310
		$whereforadd='';
311
312
		$this->db->begin();
313
314
		if (! empty($rid))
315
		{
316
			// Si on a demande ajout d'un droit en particulier, on recupere
317
			// les caracteristiques (module, perms et subperms) de ce droit.
318
			$sql = "SELECT module, perms, subperms";
319
			$sql.= " FROM ".MAIN_DB_PREFIX."rights_def";
320
			$sql.= " WHERE id = '".$this->db->escape($rid)."'";
321
			$sql.= " AND entity = ".$entity;
322
323
			$result=$this->db->query($sql);
324
			if ($result) {
325
				$obj = $this->db->fetch_object($result);
326
				$module=$obj->module;
327
				$perms=$obj->perms;
328
				$subperms=$obj->subperms;
329
			}
330
			else {
331
				$error++;
332
				dol_print_error($this->db);
333
			}
334
335
			// Where pour la liste des droits a ajouter
336
			$whereforadd="id=".$this->db->escape($rid);
337
			// Ajout des droits induits
338
			if ($subperms)   $whereforadd.=" OR (module='$module' AND perms='$perms' AND (subperms='lire' OR subperms='read'))";
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $perms does not seem to be defined for all execution paths leading up to this point.
Loading history...
Comprehensibility Best Practice introduced by
The variable $module does not seem to be defined for all execution paths leading up to this point.
Loading history...
Comprehensibility Best Practice introduced by
The variable $subperms does not seem to be defined for all execution paths leading up to this point.
Loading history...
339
			elseif ($perms) $whereforadd.=" OR (module='$module' AND (perms='lire' OR perms='read') AND subperms IS NULL)";
340
341
			// Pour compatibilite, si lowid = 0, on est en mode ajout de tout
342
			// TODO A virer quand sera gere par l'appelant
343
			//if (substr($rid,-1,1) == 0) $whereforadd="module='$module'";
344
		}
345
		else {
346
			// Where pour la liste des droits a ajouter
347
			if (! empty($allmodule))
348
			{
349
				if ($allmodule == 'allmodules')
350
				{
351
					$whereforadd='allmodules';
352
				}
353
				else
354
				{
355
					$whereforadd="module='".$this->db->escape($allmodule)."'";
356
					if (! empty($allperms))  $whereforadd.=" AND perms='".$this->db->escape($allperms)."'";
357
				}
358
			}
359
		}
360
361
		// Ajout des droits de la liste whereforadd
362
		if (! empty($whereforadd))
363
		{
364
			//print "$module-$perms-$subperms";
365
			$sql = "SELECT id";
366
			$sql.= " FROM ".MAIN_DB_PREFIX."rights_def";
367
			$sql.= " WHERE entity = ".$entity;
368
			if (! empty($whereforadd) && $whereforadd != 'allmodules') {
369
				$sql.= " AND ".$whereforadd;
370
			}
371
372
			$result=$this->db->query($sql);
373
			if ($result)
374
			{
375
				$num = $this->db->num_rows($result);
376
				$i = 0;
377
				while ($i < $num)
378
				{
379
					$obj = $this->db->fetch_object($result);
380
					$nid = $obj->id;
381
382
					$sql = "DELETE FROM ".MAIN_DB_PREFIX."usergroup_rights WHERE fk_usergroup = $this->id AND fk_id=".$nid." AND entity = ".$entity;
383
					if (! $this->db->query($sql)) $error++;
384
					$sql = "INSERT INTO ".MAIN_DB_PREFIX."usergroup_rights (entity, fk_usergroup, fk_id) VALUES (".$entity.", ".$this->id.", ".$nid.")";
385
					if (! $this->db->query($sql)) $error++;
386
387
					$i++;
388
				}
389
			}
390
			else
391
			{
392
				$error++;
393
				dol_print_error($this->db);
394
			}
395
396
			if (! $error)
397
			{
398
				$langs->load("other");
399
				$this->context = array('audit'=>$langs->trans("PermissionsAdd").($rid?' (id='.$rid.')':''));
400
401
			    // Call trigger
402
			    $result=$this->call_trigger('GROUP_MODIFY', $user);
403
			    if ($result < 0) { $error++; }
404
			    // End call triggers
405
			}
406
		}
407
408
		if ($error) {
409
			$this->db->rollback();
410
			return -$error;
411
		}
412
		else {
413
			$this->db->commit();
414
			return 1;
415
		}
416
	}
417
418
419
	/**
420
	 *    Remove a permission from group
421
	 *
422
	 *    @param	int		$rid		id du droit a retirer
423
	 *    @param	string	$allmodule	Retirer tous les droits du module allmodule
424
	 *    @param	string	$allperms	Retirer tous les droits du module allmodule, perms allperms
425
	 *    @param	int		$entity		Entity to use
426
	 *    @return	int					> 0 if OK, < 0 if OK
427
	 */
428
	public function delrights($rid, $allmodule = '', $allperms = '', $entity = 0)
429
	{
430
		global $conf, $user, $langs;
431
432
		$error=0;
433
		$wherefordel='';
434
435
		$entity = (! empty($entity)?$entity:$conf->entity);
436
437
		$this->db->begin();
438
439
		if (! empty($rid))
440
		{
441
			// Si on a demande supression d'un droit en particulier, on recupere
442
			// les caracteristiques module, perms et subperms de ce droit.
443
			$sql = "SELECT module, perms, subperms";
444
			$sql.= " FROM ".MAIN_DB_PREFIX."rights_def";
445
			$sql.= " WHERE id = '".$this->db->escape($rid)."'";
446
			$sql.= " AND entity = ".$entity;
447
448
			$result=$this->db->query($sql);
449
			if ($result) {
450
				$obj = $this->db->fetch_object($result);
451
				$module=$obj->module;
452
				$perms=$obj->perms;
453
				$subperms=$obj->subperms;
454
			}
455
			else {
456
				$error++;
457
				dol_print_error($this->db);
458
			}
459
460
			// Where pour la liste des droits a supprimer
461
			$wherefordel="id=".$this->db->escape($rid);
462
			// Suppression des droits induits
463
			if ($subperms=='lire' || $subperms=='read') $wherefordel.=" OR (module='$module' AND perms='$perms' AND subperms IS NOT NULL)";
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $subperms does not seem to be defined for all execution paths leading up to this point.
Loading history...
Comprehensibility Best Practice introduced by
The variable $perms does not seem to be defined for all execution paths leading up to this point.
Loading history...
Comprehensibility Best Practice introduced by
The variable $module does not seem to be defined for all execution paths leading up to this point.
Loading history...
464
			if ($perms=='lire' || $perms=='read')    $wherefordel.=" OR (module='$module')";
465
466
			// Pour compatibilite, si lowid = 0, on est en mode suppression de tout
467
			// TODO A virer quand sera gere par l'appelant
468
			//if (substr($rid,-1,1) == 0) $wherefordel="module='$module'";
469
		} else {
470
			// Where pour la liste des droits a supprimer
471
			if (! empty($allmodule))
472
			{
473
				if ($allmodule == 'allmodules')
474
				{
475
					$wherefordel='allmodules';
476
				}
477
				else
478
				{
479
					$wherefordel="module='".$this->db->escape($allmodule)."'";
480
					if (! empty($allperms))  $whereforadd.=" AND perms='".$this->db->escape($allperms)."'";
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $whereforadd does not exist. Did you maybe mean $wherefordel?
Loading history...
481
				}
482
			}
483
		}
484
485
		// Suppression des droits de la liste wherefordel
486
		if (! empty($wherefordel))
487
		{
488
			//print "$module-$perms-$subperms";
489
			$sql = "SELECT id";
490
			$sql.= " FROM ".MAIN_DB_PREFIX."rights_def";
491
			$sql.= " WHERE entity = ".$entity;
492
			if (! empty($wherefordel) && $wherefordel != 'allmodules') {
493
				$sql.= " AND ".$wherefordel;
494
			}
495
496
			$result=$this->db->query($sql);
497
			if ($result)
498
			{
499
				$num = $this->db->num_rows($result);
500
				$i = 0;
501
				while ($i < $num)
502
				{
503
					$obj = $this->db->fetch_object($result);
504
					$nid = $obj->id;
505
506
					$sql = "DELETE FROM ".MAIN_DB_PREFIX."usergroup_rights";
507
					$sql.= " WHERE fk_usergroup = $this->id AND fk_id=".$nid;
508
					$sql.= " AND entity = ".$entity;
509
					if (! $this->db->query($sql)) $error++;
510
511
					$i++;
512
				}
513
			}
514
			else
515
			{
516
				$error++;
517
				dol_print_error($this->db);
518
			}
519
520
			if (! $error)
521
			{
522
				$langs->load("other");
523
				$this->context = array('audit'=>$langs->trans("PermissionsDelete").($rid?' (id='.$rid.')':''));
524
525
			    // Call trigger
526
			    $result=$this->call_trigger('GROUP_MODIFY', $user);
527
			    if ($result < 0) { $error++; }
528
			    // End call triggers
529
			}
530
		}
531
532
		if ($error) {
533
			$this->db->rollback();
534
			return -$error;
535
		}
536
		else {
537
			$this->db->commit();
538
			return 1;
539
		}
540
	}
541
542
543
	/**
544
	 *  Charge dans l'objet group, la liste des permissions auquels le groupe a droit
545
	 *
546
	 *  @param      string	$moduletag	 	Name of module we want permissions ('' means all)
547
	 *	@return     int						<0 if KO, >0 if OK
548
	 */
549
	public function getrights($moduletag = '')
550
	{
551
		global $conf;
552
553
		if ($moduletag && isset($this->_tab_loaded[$moduletag]) && $this->_tab_loaded[$moduletag])
554
		{
555
			// Rights for this module are already loaded, so we leave
556
			return;
557
		}
558
559
		if (! empty($this->all_permissions_are_loaded))
560
		{
561
			// We already loaded all rights for this group, so we leave
562
			return;
563
		}
564
565
		/*
566
		 * Recuperation des droits
567
		 */
568
		$sql = "SELECT r.module, r.perms, r.subperms ";
569
		$sql.= " FROM ".MAIN_DB_PREFIX."usergroup_rights as u, ".MAIN_DB_PREFIX."rights_def as r";
570
		$sql.= " WHERE r.id = u.fk_id";
571
		$sql.= " AND r.entity = ".$conf->entity;
572
		$sql.= " AND u.entity = ".$conf->entity;
573
		$sql.= " AND u.fk_usergroup = ".$this->id;
574
		$sql.= " AND r.perms IS NOT NULL";
575
		if ($moduletag) $sql.= " AND r.module = '".$this->db->escape($moduletag)."'";
576
577
		dol_syslog(get_class($this).'::getrights', LOG_DEBUG);
578
		$resql=$this->db->query($sql);
579
		if ($resql)
580
		{
581
			$num = $this->db->num_rows($resql);
582
			$i = 0;
583
			while ($i < $num)
584
			{
585
				$obj = $this->db->fetch_object($resql);
586
587
				$module=$obj->module;
588
				$perms=$obj->perms;
589
				$subperms=$obj->subperms;
590
591
				if ($perms)
592
				{
593
					if (! isset($this->rights)) $this->rights = new stdClass(); // For avoid error
594
					if (! isset($this->rights->$module) || ! is_object($this->rights->$module)) $this->rights->$module = new stdClass();
595
					if ($subperms)
596
					{
597
						if (! isset($this->rights->$module->$perms) || ! is_object($this->rights->$module->$perms)) $this->rights->$module->$perms = new stdClass();
598
						if(empty($this->rights->$module->$perms->$subperms)) $this->nb_rights++;
599
						$this->rights->$module->$perms->$subperms = 1;
600
					}
601
					else
602
					{
603
						if(empty($this->rights->$module->$perms)) $this->nb_rights++;
604
						$this->rights->$module->$perms = 1;
605
					}
606
				}
607
608
				$i++;
609
			}
610
			$this->db->free($resql);
611
		}
612
613
		if ($moduletag == '')
614
		{
615
			// Si module etait non defini, alors on a tout charge, on peut donc considerer
616
			// que les droits sont en cache (car tous charges) pour cet instance de group
617
			$this->all_permissions_are_loaded=1;
618
		}
619
		else
620
		{
621
			// If module defined, we flag it as loaded into cache
622
		    $this->_tab_loaded[$moduletag]=1;
623
		}
624
625
        return 1;
626
	}
627
628
	/**
629
	 *	Delete a group
630
	 *
631
	 *	@param	User	$user		User that delete
632
	 *	@return     				<0 if KO, > 0 if OK
0 ignored issues
show
Documentation Bug introduced by
The doc comment <0 at position 0 could not be parsed: Unknown type name '<' at position 0 in <0.
Loading history...
633
	 */
634
	public function delete(User $user)
635
	{
636
		global $conf,$langs;
637
638
		$error=0;
639
640
		$this->db->begin();
641
642
		$sql = "DELETE FROM ".MAIN_DB_PREFIX."usergroup_rights";
643
		$sql .= " WHERE fk_usergroup = ".$this->id;
644
		$this->db->query($sql);
645
646
		$sql = "DELETE FROM ".MAIN_DB_PREFIX."usergroup_user";
647
		$sql .= " WHERE fk_usergroup = ".$this->id;
648
		$this->db->query($sql);
649
650
        // Remove extrafields
651
        if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
652
        {
653
            $result=$this->deleteExtraFields();
654
            if ($result < 0)
655
            {
656
                $error++;
657
                dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
658
            }
659
        }
660
661
		$sql = "DELETE FROM ".MAIN_DB_PREFIX."usergroup";
662
		$sql .= " WHERE rowid = ".$this->id;
663
		$result=$this->db->query($sql);
664
		if ($result)
665
		{
666
            // Call trigger
667
            $result=$this->call_trigger('GROUP_DELETE', $user);
668
            if ($result < 0) { $error++; $this->db->rollback(); return -1; }
669
            // End call triggers
670
671
			$this->db->commit();
672
			return 1;
673
		}
674
		else
675
		{
676
			$this->db->rollback();
677
			dol_print_error($this->db);
678
			return -1;
679
		}
680
	}
681
682
	/**
683
	 *	Create group into database
684
	 *
685
	 *	@param		int		$notrigger	0=triggers enabled, 1=triggers disabled
686
	 *	@return     int					<0 if KO, >=0 if OK
687
	 */
688
	public function create($notrigger = 0)
689
	{
690
		global $user, $conf, $langs, $hookmanager;
691
692
		$error=0;
693
		$now=dol_now();
694
695
		if (! isset($this->entity)) $this->entity=$conf->entity;	// If not defined, we use default value
696
697
		$entity=$this->entity;
698
		if (! empty($conf->multicompany->enabled) && $conf->entity == 1) $entity=$this->entity;
699
700
		$this->db->begin();
701
702
		$sql = "INSERT INTO ".MAIN_DB_PREFIX."usergroup (";
703
		$sql.= "datec";
704
		$sql.= ", nom";
705
		$sql.= ", entity";
706
		$sql.= ") VALUES (";
707
		$sql.= "'".$this->db->idate($now)."'";
708
		$sql.= ",'".$this->db->escape($this->nom)."'";
709
		$sql.= ",".$this->db->escape($entity);
710
		$sql.= ")";
711
712
		dol_syslog(get_class($this)."::create", LOG_DEBUG);
713
		$result=$this->db->query($sql);
714
		if ($result)
715
		{
716
			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."usergroup");
717
718
			if ($this->update(1) < 0) return -2;
719
720
			$action='create';
721
722
			// Actions on extra fields (by external module or standard code)
723
			if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
724
			{
725
				$result=$this->insertExtraFields();
726
				if ($result < 0)
727
				{
728
					$error++;
729
				}
730
			}
731
732
			if (! $error && ! $notrigger)
733
			{
734
                // Call trigger
735
                $result=$this->call_trigger('GROUP_CREATE', $user);
736
                if ($result < 0) { $error++; $this->db->rollback(); return -1; }
737
                // End call triggers
738
			}
739
740
			if ($error > 0) { $error++; $this->db->rollback(); return -1; }
741
			else $this->db->commit();
742
743
			return $this->id;
744
		}
745
		else
746
		{
747
		    $this->db->rollback();
748
			$this->error=$this->db->lasterror();
749
			return -1;
750
		}
751
	}
752
753
	/**
754
	 *		Update group into database
755
	 *
756
	 *      @param      int		$notrigger	    0=triggers enabled, 1=triggers disabled
757
	 *    	@return     int						<0 if KO, >=0 if OK
758
	 */
759
	public function update($notrigger = 0)
760
	{
761
		global $user, $conf, $langs, $hookmanager;
762
763
		$error=0;
764
765
		$entity=$conf->entity;
766
		if(! empty($conf->multicompany->enabled) && $conf->entity == 1)
767
		{
768
			$entity=$this->entity;
769
		}
770
771
		$this->db->begin();
772
773
		$sql = "UPDATE ".MAIN_DB_PREFIX."usergroup SET ";
774
		$sql.= " nom = '" . $this->db->escape($this->name) . "'";
775
		$sql.= ", entity = " . $this->db->escape($entity);
776
		$sql.= ", note = '" . $this->db->escape($this->note) . "'";
777
		$sql.= " WHERE rowid = " . $this->id;
778
779
		dol_syslog(get_class($this)."::update", LOG_DEBUG);
780
		$resql = $this->db->query($sql);
781
		if ($resql)
782
		{
783
			$action='update';
784
785
			// Actions on extra fields (by external module or standard code)
786
			if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
787
			{
788
				$result=$this->insertExtraFields();
789
				if ($result < 0)
790
				{
791
					$error++;
792
				}
793
			}
794
795
			if (! $error && ! $notrigger)
796
			{
797
                // Call trigger
798
                $result=$this->call_trigger('GROUP_MODIFY', $user);
799
                if ($result < 0) { $error++; }
800
                // End call triggers
801
			}
802
803
			if (! $error)
804
			{
805
			    $this->db->commit();
806
			    return 1;
807
			}
808
			else
809
			{
810
			    $this->db->rollback();
811
			    return -$error;
812
			}
813
		}
814
		else
815
		{
816
		    $this->db->rollback();
817
			dol_print_error($this->db);
818
			return -1;
819
		}
820
	}
821
822
823
	/**
824
	 *  Return label of status of user (active, inactive)
825
	 *
826
	 *  @param	int		$mode          0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
827
	 *  @return	string 			       Label of status
828
	 */
829
	public function getLibStatut($mode = 0)
830
	{
831
	    return $this->LibStatut(0, $mode);
832
	}
833
834
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
835
	/**
836
	 *  Renvoi le libelle d'un statut donne
837
	 *
838
	 *  @param	int		$statut        	Id statut
839
	 *  @param  int		$mode          	0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
840
	 *  @return string 			       	Label of status
841
	 */
842
	public function LibStatut($statut, $mode = 0)
843
	{
844
        // phpcs:enable
845
	    global $langs;
846
	    $langs->load('users');
847
	    return '';
848
	}
849
850
	/**
851
	 *  Return a link to the user card (with optionaly the picto)
852
	 *  Use this->id,this->lastname, this->firstname
853
	 *
854
	 *  @param  int		$withpicto					Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto, -1=Include photo into link, -2=Only picto photo, -3=Only photo very small)
855
	 *	@param  string	$option						On what the link point to ('nolink', )
856
	 *  @param	integer	$notooltip					1=Disable tooltip on picto and name
857
	 *  @param  string  $morecss            		Add more css on link
858
	 *  @param  int     $save_lastsearch_value    	-1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
859
	 *	@return	string								String with URL
860
	 */
861
	public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
862
	{
863
		global $langs, $conf, $db, $hookmanager;
864
		global $dolibarr_main_authentication, $dolibarr_main_demo;
865
		global $menumanager;
866
867
		if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpicto) $withpicto=0;
868
869
		$result=''; $label='';
870
871
		$label.= '<div class="centpercent">';
872
		$label.= '<u>' . $langs->trans("Group") . '</u><br>';
873
		$label.= '<b>' . $langs->trans('Name') . ':</b> ' . $this->name;
874
		$label.= '<br><b>' . $langs->trans("Description").':</b> '.$this->note;
875
		$label.='</div>';
876
877
		$url = DOL_URL_ROOT.'/user/group/card.php?id='.$this->id;
878
879
		if ($option != 'nolink')
880
		{
881
			// Add param to save lastsearch_values or not
882
			$add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
883
			if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
884
			if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1';
885
		}
886
887
		$linkclose="";
888
		if (empty($notooltip))
889
		{
890
			if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
891
			{
892
				$langs->load("users");
893
				$label=$langs->trans("ShowGroup");
894
				$linkclose.=' alt="'.dol_escape_htmltag($label, 1, 1).'"';
895
			}
896
			$linkclose.= ' title="'.dol_escape_htmltag($label, 1, 1).'"';
897
			$linkclose.= ' class="classfortooltip'.($morecss?' '.$morecss:'').'"';
898
899
			/*
900
			 $hookmanager->initHooks(array('groupdao'));
901
			 $parameters=array('id'=>$this->id);
902
			 $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
903
			 if ($reshook > 0) $linkclose = $hookmanager->resPrint;
904
			 */
905
		}
906
907
		$linkstart = '<a href="'.$url.'"';
908
		$linkstart.=$linkclose.'>';
909
		$linkend='</a>';
910
911
		$result = $linkstart;
912
		if ($withpicto) $result.=img_object(($notooltip?'':$label), ($this->picto?$this->picto:'generic'), ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip?0:1);
913
		if ($withpicto != 2) $result.= $this->name;
914
		$result .= $linkend;
915
916
		global $action;
917
		$hookmanager->initHooks(array('groupdao'));
918
		$parameters=array('id'=>$this->id, 'getnomurl'=>$result);
919
		$reshook=$hookmanager->executeHooks('getNomUrl', $parameters, $this, $action);    // Note that $action and $object may have been modified by some hooks
920
		if ($reshook > 0) $result = $hookmanager->resPrint;
921
		else $result .= $hookmanager->resPrint;
922
923
		return $result;
924
	}
925
926
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
927
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
928
	/**
929
	 *	Retourne chaine DN complete dans l'annuaire LDAP pour l'objet
930
	 *
931
	 *	@param		array	$info		Info array loaded by _load_ldap_info
932
	 *	@param		int		$mode		0=Return full DN (uid=qqq,ou=xxx,dc=aaa,dc=bbb)
933
	 *									1=Return DN without key inside (ou=xxx,dc=aaa,dc=bbb)
934
	 *									2=Return key only (uid=qqq)
935
	 *	@return		string				DN
936
	 */
937
    public function _load_ldap_dn($info, $mode = 0)
938
	{
939
        // phpcs:enable
940
		global $conf;
941
		$dn='';
942
		if ($mode==0) $dn=$conf->global->LDAP_KEY_GROUPS."=".$info[$conf->global->LDAP_KEY_GROUPS].",".$conf->global->LDAP_GROUP_DN;
943
		if ($mode==1) $dn=$conf->global->LDAP_GROUP_DN;
944
		if ($mode==2) $dn=$conf->global->LDAP_KEY_GROUPS."=".$info[$conf->global->LDAP_KEY_GROUPS];
945
		return $dn;
946
	}
947
948
949
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
950
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
951
	/**
952
	 *	Initialize the info array (array of LDAP values) that will be used to call LDAP functions
953
	 *
954
	 *	@return		array		Tableau info des attributs
955
	 */
956
    public function _load_ldap_info()
957
	{
958
        // phpcs:enable
959
		global $conf;
960
961
		$info=array();
962
963
		// Object classes
964
		$info["objectclass"]=explode(',', $conf->global->LDAP_GROUP_OBJECT_CLASS);
965
966
		// Champs
967
		if ($this->name && ! empty($conf->global->LDAP_GROUP_FIELD_FULLNAME)) $info[$conf->global->LDAP_GROUP_FIELD_FULLNAME] = $this->name;
968
		//if ($this->name && ! empty($conf->global->LDAP_GROUP_FIELD_NAME)) $info[$conf->global->LDAP_GROUP_FIELD_NAME] = $this->name;
969
		if ($this->note && ! empty($conf->global->LDAP_GROUP_FIELD_DESCRIPTION)) $info[$conf->global->LDAP_GROUP_FIELD_DESCRIPTION] = dol_string_nohtmltag($this->note, 2);
970
		if (! empty($conf->global->LDAP_GROUP_FIELD_GROUPMEMBERS))
971
		{
972
			$valueofldapfield=array();
973
			foreach($this->members as $key=>$val)    // This is array of users for group into dolibarr database.
974
			{
975
				$muser=new User($this->db);
976
				$muser->fetch($val->id);
977
				$info2 = $muser->_load_ldap_info();
978
				$valueofldapfield[] = $muser->_load_ldap_dn($info2);
979
			}
980
			$info[$conf->global->LDAP_GROUP_FIELD_GROUPMEMBERS] = (!empty($valueofldapfield)?$valueofldapfield:'');
981
		}
982
		return $info;
983
	}
984
985
986
	/**
987
     *  Initialise an instance with random values.
988
     *  Used to build previews or test instances.
989
     *	id must be 0 if object instance is a specimen.
990
     *
991
     *  @return	void
992
     */
993
    public function initAsSpecimen()
994
	{
995
		global $conf, $user, $langs;
996
997
		// Initialise parametres
998
		$this->id=0;
999
		$this->ref = 'SPECIMEN';
1000
		$this->specimen=1;
1001
1002
		$this->name='DOLIBARR GROUP SPECIMEN';
1003
		$this->note='This is a note';
1004
		$this->datec=time();
1005
		$this->datem=time();
1006
1007
        // Members of this group is just me
1008
        $this->members=array(
1009
            $user->id => $user
1010
        );
1011
    }
1012
1013
	/**
1014
	 *  Create a document onto disk according to template module.
1015
	 *
1016
	 * 	@param	    string		$modele			Force model to use ('' to not force)
1017
	 * 	@param		Translate	$outputlangs	Object langs to use for output
1018
	 *  @param      int			$hidedetails    Hide details of lines
1019
	 *  @param      int			$hidedesc       Hide description
1020
	 *  @param      int			$hideref        Hide ref
1021
     *  @param      null|array  $moreparams     Array to provide more information
1022
	 * 	@return     int         				0 if KO, 1 if OK
1023
	 */
1024
	public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
1025
	{
1026
		global $conf,$user,$langs;
1027
1028
		$langs->load("user");
1029
1030
		// Positionne le modele sur le nom du modele a utiliser
1031
		if (! dol_strlen($modele))
1032
		{
1033
			if (! empty($conf->global->USERGROUP_ADDON_PDF))
1034
			{
1035
				$modele = $conf->global->USERGROUP_ADDON_PDF;
1036
			}
1037
			else
1038
			{
1039
				$modele = 'grass';
1040
			}
1041
		}
1042
1043
		$modelpath = "core/modules/usergroup/doc/";
1044
1045
		return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
1046
	}
1047
}
1048