FOSSology  3.2.0rc1
Open Source License Compliance by Open Source Software
UserDao.php
1 <?php
2 /***********************************************************
3  * Copyright (C) 2014-2017 Siemens AG
4  * Author: J. Najjar, S. Weber, A. Wührl
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * version 2 as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18  ***********************************************************/
19 
20 namespace Fossology\Lib\Dao;
21 
24 use Monolog\Logger;
26 
27 class UserDao
28 {
29  const USER = 0;
30  const ADMIN = 1;
31  const ADVISOR = 2;
32 
33  const SUPER_USER = 'fossy';
34 
35  /* @var DbManager */
36  private $dbManager;
37  /* @var Logger */
38  private $logger;
40  private $session;
41 
42  function __construct(DbManager $dbManager, Logger $logger)
43  {
44  $this->dbManager = $dbManager;
45  $this->logger = $logger;
46 
47  global $container;
48  $this->session = $container->get('session');
49  }
50 
54  public function getUserChoices($groupId=null)
55  {
56  if (empty($groupId)) {
57  $groupId = Auth::getGroupId();
58  }
59  $userChoices = array();
60  $statementN = __METHOD__;
61  $sql = "SELECT user_pk, user_name, user_desc FROM users LEFT JOIN group_user_member AS gum ON users.user_pk = gum.user_fk"
62  . " WHERE gum.group_fk = $1";
63  $this->dbManager->prepare($statementN, $sql);
64  $res = $this->dbManager->execute($statementN, array($groupId));
65  while ($rw = $this->dbManager->fetchArray($res)) {
66  $userChoices[$rw['user_pk']] = $rw['user_desc'] . ' (' . $rw['user_name'] . ')';
67  }
68  $this->dbManager->freeResult($res);
69  return $userChoices;
70  }
71 
77  function getAdminGroupMap($userId,$userLevel=0)
78  {
79  if ($userLevel == PLUGIN_DB_ADMIN) {
80  return $this->dbManager->createMap('groups', 'group_pk', 'group_name');
81  }
82  $sql = "SELECT group_pk, group_name FROM groups, group_user_member"
83  . " WHERE group_pk=group_fk AND user_fk=$1 AND group_perm=$2";
84  $param = array($userId,self::ADMIN);
85  $this->dbManager->prepare($stmt=__METHOD__, $sql);
86  $res = $this->dbManager->execute($stmt,$param);
87  $groupMap = array();
88  while ($row = $this->dbManager->fetchArray($res)) {
89  $groupMap[$row['group_pk']] = $row['group_name'];
90  }
91  $this->dbManager->freeResult($res);
92  return $groupMap;
93  }
94 
100  function getUserGroupMap($userId)
101  {
102  $sql = "SELECT group_pk, group_name FROM groups, group_user_member WHERE group_pk=group_fk AND user_fk=$1";
103  $this->dbManager->prepare($stmt=__METHOD__, $sql);
104  $res = $this->dbManager->execute($stmt,array($userId));
105  $groupMap = array();
106  while ($row = $this->dbManager->fetchArray($res)) {
107  $groupMap[$row['group_pk']] = $row['group_name'];
108  }
109  $this->dbManager->freeResult($res);
110  return $groupMap;
111  }
112 
118  function getDeletableAdminGroupMap($userId,$userLevel=0)
119  {
120  if ($userLevel == PLUGIN_DB_ADMIN) {
121  $sql = "SELECT group_pk, group_name FROM groups LEFT JOIN users ON group_name=user_name "
122  . "WHERE user_name IS NULL";
123  $param = array();
124  } else {
125  $sql = "SELECT group_pk, group_name FROM groups LEFT JOIN users ON group_name=user_name "
126  . " INNER JOIN group_user_member ON group_pk=group_user_member.group_fk AND user_fk=$1 AND group_perm=$2 "
127  . "WHERE user_name IS NULL";
128  $param = array($userId,1);
129  }
130  $this->dbManager->prepare($stmt=__METHOD__.".$userLevel", $sql);
131  $res = $this->dbManager->execute($stmt,$param);
132  $groupMap = array();
133  while ($row = $this->dbManager->fetchArray($res)) {
134  $groupMap[$row['group_pk']] = $row['group_name'];
135  }
136  $this->dbManager->freeResult($res);
137  return $groupMap;
138  }
139 
140 
147  function deleteGroup($groupId)
148  {
149  if (!$this->session->isStarted()) {
150  $this->session->setName('Login');
151  $this->session->start();
152  }
153  $groupArray = $this->dbManager->getSingleRow('SELECT group_pk, group_name FROM groups WHERE group_pk=$1',
154  array($groupId),__METHOD__.'.exists');
155  if ($groupArray===false) {
156  throw new \Exception( _("Group does not exist. Not deleted.") );
157  }
158  $groupConstraint = $this->dbManager->getSingleRow('SELECT count(*) cnt FROM users WHERE user_name=$1',
159  array($groupArray['group_name']),__METHOD__.'.contraint');
160  if ($groupConstraint['cnt']) {
161  throw new \Exception( _("Group must not be deleted due to name constraint.") );
162  }
163  if ($_SESSION[Auth::USER_LEVEL] != PLUGIN_DB_ADMIN) {
164  $userId = Auth::getUserId();
165  $adminLevel = $this->dbManager->getSingleRow("SELECT count(*) cnt FROM group_user_member WHERE group_fk=$1 and user_fk=$2 and group_perm=1",
166  array($groupId,$userId),__METHOD__.'.admin_lvl');
167  if ($adminLevel['cnt']< 1) {
168  $text = _("Permission Denied.");
169  throw new \Exception($text);
170  }
171  }
172 
173  $this->dbManager->begin();
174  $this->dbManager->getSingleRow("DELETE FROM perm_upload WHERE group_fk=$1",array($groupId),__METHOD__.'.perm_upload');
175  $this->dbManager->getSingleRow("DELETE FROM group_user_member WHERE group_fk=$1",array($groupId),__METHOD__.'.gum');
176  $this->dbManager->getSingleRow("UPDATE users SET new_upload_group_fk=NULL, new_upload_perm=NULL WHERE new_upload_group_fk=$1",
177  array($groupId),__METHOD__.'.upload_group');
178  $newGroupIdStmt = '(SELECT group_fk FROM group_user_member WHERE user_fk=user_pk LIMIT 1)';
179  $this->dbManager->getSingleRow("UPDATE users SET group_fk=$newGroupIdStmt WHERE group_fk=$1",
180  array($groupId),__METHOD__.'.active_group');
181  $this->dbManager->getSingleRow("DELETE FROM groups WHERE group_pk=$1",array($groupId),__METHOD__.'.delete');
182  $this->dbManager->commit();
183 
184  $newGroupId= $this->dbManager->getSingleRow("SELECT group_fk FROM users WHERE user_pk=$1",
185  array($this->session->get(AUTH::USER_ID)), __METHOD__.'.group_after_update');
186  $_SESSION[Auth::GROUP_ID] = $newGroupId['group_fk'];
187  $this->session->set(Auth::GROUP_ID, $newGroupId['group_fk']);
188 
189  return true;
190  }
191 
192  function updateUserTable()
193  {
194  $statementBasename = __FUNCTION__;
195  $this->dbManager->getSingleRow("UPDATE users SET user_seed = $1 WHERE user_seed IS NULL;",
196  array(rand()),
197  $statementBasename . '.randomizeEmptySeeds');
198 
199  /* No users with no seed and no perm -- make them read-only */
200  $this->dbManager->getSingleRow("UPDATE users SET user_perm = $1 WHERE user_perm IS NULL;",
201  array(PLUGIN_DB_READ),
202  $statementBasename . '.setDefaultPermission');
203  /* There must always be at least one default user. */
204  $defaultUser = $this->getUserByName('Default User');
205 
206  if (empty($defaultUser['user_name'])) {
207  $level = PLUGIN_DB_NONE;
208  $this->dbManager->getSingleRow("
209  INSERT INTO users (user_name,user_desc,user_seed,user_pass,user_perm,user_email,root_folder_fk)
210  VALUES ('Default User','Default User when nobody is logged in','Seed','Pass', $1,NULL,1);",
211  array($level), $statementBasename . '.createDefaultUser');
212  }
213  /* There must always be at least one user with user-admin access.
214  If he does not exist, make it SUPER_USER with the same password. */
215  $perm = PLUGIN_DB_ADMIN;
216  $row = $this->getUserByPermission($perm);
217  if (empty($row['user_name'])) {
218  /* No user with PLUGIN_DB_ADMIN access. */
219  $seed = rand() . rand();
220  $hash = sha1($seed . self::SUPER_USER);
221  $row0 = $this->getUserByName(self::SUPER_USER);
222 
223  if (empty($row0['user_name'])) {
224  $this->dbManager->getSingleRow("
225  INSERT INTO users (user_name, user_desc, user_seed, user_pass, user_perm, user_email, email_notify, root_folder_fk)
226  VALUES ($1,'Default Administrator',$2, $3, $4, $1,'y',1)",
227  array(self::SUPER_USER, $seed, $hash, $perm), $statementBasename . '.createDefaultAdmin');
228  } else {
229  $this->dbManager->getSingleRow("UPDATE users SET user_perm = $1, email_notify = 'y'," .
230  " user_email=$2 WHERE user_name =$2",
231  array($perm, self::SUPER_USER), $statementBasename . '.updateDefaultUserToDefaultAdmin');
232  }
233  $row = $this->getUserByPermission($perm);
234  }
235 
236  return empty($row['user_name']) ? 1 : 0;
237  }
238 
243  public function getUserByName($userName)
244  {
245  return $this->dbManager->getSingleRow("SELECT * FROM users WHERE user_name = $1", array($userName), __FUNCTION__);
246  }
247 
252  public function getUserByPk($userPk)
253  {
254  return $this->dbManager->getSingleRow("SELECT * FROM users WHERE user_pk = $1", array($userPk), __FUNCTION__);
255  }
256 
261  public function getGroupIdByName($groupName)
262  {
263  $row = $this->dbManager->getSingleRow("SELECT * FROM groups WHERE group_name = $1", array($groupName), __FUNCTION__);
264  return $row['group_pk'];
265  }
266 
271  private function getUserByPermission($permission)
272  {
273  return $this->dbManager->getSingleRow("SELECT * FROM users WHERE user_perm = $1", array($permission), __FUNCTION__);
274  }
275 
280  public function setDefaultGroupMembership($userId, $groupId)
281  {
282  $this->dbManager->getSingleRow("UPDATE users SET group_fk=$2 WHERE user_pk=$1",
283  array($userId, $groupId), __FUNCTION__);
284  }
285 
286  public function getUserAndDefaultGroupByUserName($userName)
287  {
288  $userRow = $this->dbManager->getSingleRow(
289  "SELECT users.*,group_name FROM users LEFT JOIN groups ON group_fk=group_pk WHERE user_name=$1",
290  array($userName), __FUNCTION__);
291  if (empty($userRow)) {
292  throw new \Exception('invalid user name');
293  }
294  if ($userRow['group_fk']) {
295  return $userRow;
296  }
297  $groupRow = $this->fixDefaultGroup($userRow['user_pk'],$userName);
298  $this->setDefaultGroupMembership($userRow['user_pk'], $groupRow['group_fk']);
299  $userRow['group_fk'] = $groupRow['group_fk'];
300  $userRow['group_name'] = $groupRow['group_name'];
301  return $userRow;
302  }
303 
309  private function fixDefaultGroup($userId, $groupName)
310  {
311  $groupRow = $this->dbManager->getSingleRow(
312  "SELECT group_fk,group_name FROM group_user_member LEFT JOIN groups ON group_fk=group_pk WHERE user_fk=$1",
313  array($userId), __FUNCTION__.".getGroup");
314  if ($groupRow) {
315  return $groupRow;
316  }
317 
318  $groupId = $this->getGroupIdByName($groupName);
319  if (empty($groupId)) {
320  $groupId = $this->addGroup($groupName);
321  $this->addGroupMembership($groupId, $userId);
322  }
323 
324  return array('group_fk'=>$groupId,'group_name'=>$groupName);
325  }
326 
327  public function isAdvisorOrAdmin($userId, $groupId)
328  {
329  $row = $this->dbManager->getSingleRow("SELECT group_perm FROM group_user_member WHERE user_fk=$1 AND group_fk=$2",
330  array($userId, $groupId), __METHOD__);
331  return $row!==false && ($row['group_perm']==self::ADVISOR || $row['group_perm']==self::ADMIN);
332  }
333 
339  public function addGroup($groupName)
340  {
341  if (empty($groupName)) {
342  throw new \Exception(_("Error: Group name must be specified."));
343  }
344 
345  $groupAlreadyExists = $this->dbManager->getSingleRow("SELECT group_pk FROM groups WHERE group_name=$1",
346  array($groupName),
347  __METHOD__.'.gExists');
348  if ($groupAlreadyExists) {
349  throw new \Exception(_("Group already exists. Not added."));
350  }
351 
352  $this->dbManager->insertTableRow('groups', array('group_name'=>$groupName));
353  $groupNowExists = $this->dbManager->getSingleRow("SELECT * FROM groups WHERE group_name=$1",
354  array($groupName),
355  __METHOD__.'.gNowExists');
356  if (!$groupNowExists) {
357  throw new \Exception(_("Failed to create group"));
358  }
359  return $groupNowExists['group_pk'];
360  }
361 
362  public function addGroupMembership($groupId, $userId)
363  {
364  $this->dbManager->insertTableRow('group_user_member',
365  array('group_fk'=>$groupId,'user_fk'=>$userId,'group_perm'=>1));
366  }
367 
372  public function getUserName($userId)
373  {
374  $userRow = $this->dbManager->getSingleRow("SELECT user_name FROM users WHERE user_pk=$1",array($userId),__METHOD__);
375  if (!$userRow) {
376  throw new \Exception('unknown user with id='.$userId);
377  }
378  return $userRow['user_name'];
379  }
380 
385  public function getGroupNameById($groupId)
386  {
387  $groupRow = $this->dbManager->getSingleRow("SELECT group_name FROM groups WHERE group_pk = $1",array($groupId),__METHOD__);
388  if (empty($groupRow)) {
389  throw new \Exception('Error: GroupId ='. $groupId .' not a member of a valid group.');
390  }
391  return $groupRow['group_name'];
392  }
393 
398  public function getUserEmail($userId)
399  {
400  $userRow = $this->dbManager->getSingleRow("SELECT user_email FROM users WHERE user_pk=$1",array($userId),__METHOD__);
401  if (!$userRow) {
402  throw new \Exception('unknown user with id='.$userId);
403  }
404  return $userRow['user_email'];
405  }
406 }
getUserGroupMap($userId)
get array of groups that this user has admin access to
Definition: UserDao.php:100
static getUserId()
Get the current user&#39;s id.
Definition: Auth.php:69
#define PLUGIN_DB_ADMIN
Plugin requires admin level permission on DB.
Definition: libfossology.h:51
getAdminGroupMap($userId, $userLevel=0)
get array of groups that this user has admin access to
Definition: UserDao.php:77
getUserChoices($groupId=null)
Definition: UserDao.php:54
#define PLUGIN_DB_READ
Plugin requires read permission on DB.
Definition: libfossology.h:49
getUserByName($userName)
Definition: UserDao.php:243
getUserByPermission($permission)
Definition: UserDao.php:271
setDefaultGroupMembership($userId, $groupId)
Definition: UserDao.php:280
getGroupIdByName($groupName)
Definition: UserDao.php:261
getGroupNameById($groupId)
Definition: UserDao.php:385
#define PLUGIN_DB_NONE
Plugin requires no DB permission.
Definition: libfossology.h:48
fo_dbManager * dbManager
fo_dbManager object
Definition: process.c:28
deleteGroup($groupId)
Delete a group (for constraint, see http://www.fossology.org/projects/fossology/wiki/GroupsPerms ) ...
Definition: UserDao.php:147
getDeletableAdminGroupMap($userId, $userLevel=0)
get array of groups that this user has admin access to
Definition: UserDao.php:118
static getGroupId()
Get the current user&#39;s group id.
Definition: Auth.php:78
fixDefaultGroup($userId, $groupName)
Definition: UserDao.php:309