usergroup.class.php 32 KB

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