Passed
Branch develop (01f96b)
by
unknown
30:45
created

UserGroup::update()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

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