Passed
Push — master ( fa5a21...043752 )
by Alxarafe
27:01
created

dolibarr/htdocs/user/class/usergroup.class.php (1 issue)

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