FOSSology  3.2.0rc1
Open Source License Compliance by Open Source Software
DbHelper.php
Go to the documentation of this file.
1 <?php
2 /***************************************************************
3 Copyright (C) 2017 Siemens AG
4 
5 This program is free software; you can redistribute it and/or
6 modify it under the terms of the GNU General Public License
7 version 2 as published by the Free Software Foundation.
8 
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13 
14 You should have received a copy of the GNU General Public License along
15 with this program; if not, write to the Free Software Foundation, Inc.,
16 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  ***************************************************************/
18 
23 namespace Fossology\UI\Api\Helper;
24 
25 require_once dirname(dirname(dirname(dirname(__DIR__)))) .
26  "/lib/php/common-db.php";
27 
38 
43 class DbHelper
44 {
49  private $dbManager;
50 
56  public function __construct(DbManager $dbManager)
57  {
58  $this->dbManager = $dbManager;
59  }
60 
66  public function getDbManager()
67  {
68  return $this->dbManager;
69  }
70 
80  public function getUploads($userId, $uploadId = null)
81  {
82  if ($uploadId == null) {
83  $sql = "SELECT
84 upload.upload_pk, upload.upload_desc, upload.upload_ts, upload.upload_filename,
85 folder.folder_pk, folder.folder_name, pfile.pfile_size, pfile.pfile_sha1
86 FROM upload
87 INNER JOIN folderlist ON folderlist.upload_pk = upload.upload_pk
88 INNER JOIN folder ON folder.folder_pk = folderlist.parent
89 INNER JOIN pfile ON pfile.pfile_pk = upload.pfile_fk
90 WHERE upload.user_fk = $1
91 ORDER BY upload.upload_pk;";
92  $statementName = __METHOD__ . ".getAllUploads";
93  $params = [$userId];
94  } else {
95  $sql = "SELECT
96 upload.upload_pk, upload.upload_desc, upload.upload_ts, upload.upload_filename,
97 folder.folder_pk, folder.folder_name, pfile.pfile_size, pfile.pfile_sha1
98 FROM upload
99 INNER JOIN folderlist ON folderlist.upload_pk = upload.upload_pk
100 INNER JOIN folder ON folder.folder_pk = folderlist.parent
101 INNER JOIN pfile ON pfile.pfile_pk = upload.pfile_fk
102 WHERE upload.user_fk = $1
103 AND upload.upload_pk = $2
104 ORDER BY upload.upload_pk;";
105  $statementName = __METHOD__ . ".getSpecificUpload";
106  $params = [$userId,$uploadId];
107  }
108  $result = $this->dbManager->getRows($sql, $params, $statementName);
109  $uploads = [];
110  foreach ($result as $row) {
111  $upload = new Upload($row["folder_pk"], $row["folder_name"],
112  $row["upload_pk"], $row["upload_desc"], $row["upload_filename"],
113  $row["upload_ts"], $row["pfile_size"], $row["pfile_sha1"]);
114  array_push($uploads, $upload->getArray());
115  }
116  return $uploads;
117  }
118 
125  public function getFilenameFromUploadTree($uploadTreePk)
126  {
127  return $this->dbManager->getSingleRow(
128  'SELECT DISTINCT ufile_name FROM uploadtree
129 WHERE uploadtree_pk=' . pg_escape_string($uploadTreePk))["ufile_name"];
130  }
131 
140  public function doesIdExist($tableName, $idRowName, $id)
141  {
142  return (0 < (intval($this->getDbManager()->getSingleRow("SELECT COUNT(*)
143 FROM $tableName WHERE $idRowName= " . pg_escape_string($id))["count"])));
144  }
145 
151  public function deleteUser($id)
152  {
153  require_once dirname(dirname(__DIR__)) . "/user-del-helper.php";
154  deleteUser($id, $this->getDbManager());
155  }
156 
164  public function getUsers($id = null)
165  {
166  if ($id == null) {
167  $usersSQL = "SELECT user_pk, user_name, user_desc, user_email,
168  email_notify, root_folder_fk, user_perm, user_agent_list FROM users;";
169  $statement = __METHOD__ . ".getAllUsers";
170  } else {
171  $usersSQL = "SELECT user_pk, user_name, user_desc, user_email,
172  email_notify, root_folder_fk, user_perm, user_agent_list FROM users
173  WHERE user_pk = $1;";
174  $statement = __METHOD__ . ".getSpecificUser";
175  }
176  $users = [];
177  if ($id === null) {
178  $result = $result = $this->dbManager->getRows($usersSQL, [], $statement);
179  } else {
180  $result = $result = $this->dbManager->getRows($usersSQL, [$id],
181  $statement);
182  }
183  $currentUser = Auth::getUserId();
184  $userIsAdmin = Auth::isAdmin();
185  foreach ($result as $row) {
186  $user = null;
187  if ($userIsAdmin ||
188  ($row["user_pk"] == $currentUser)) {
189  $user = new User($row["user_pk"], $row["user_name"], $row["user_desc"],
190  $row["user_email"], $row["user_perm"], $row["root_folder_fk"],
191  $row["email_notify"], $row["user_agent_list"]);
192  } else {
193  $user = new User($row["user_pk"], $row["user_name"], $row["user_desc"],
194  null, null, null, null, null);
195  }
196  $users[] = $user->getArray();
197  }
198 
199  return $users;
200  }
201 
215  public function getJobs($id = null, $limit = 0, $page = 1, $uploadId = null)
216  {
217  $jobSQL = "SELECT job_pk, job_queued, job_name, job_upload_fk," .
218  " job_user_fk, job_group_fk FROM job";
219  $totalJobSql = "SELECT count(*) AS cnt FROM job";
220 
221  $filter = "";
222  $pagination = "";
223 
224  $params = [];
225  $statement = __METHOD__ . ".getJobs";
226  $countStatement = __METHOD__ . ".getJobCount";
227  if ($id == null) {
228  if ($uploadId !== null) {
229  $params[] = $uploadId;
230  $filter = "WHERE job_upload_fk = $" . count($params);
231  $statement .= ".withUploadFilter";
232  $countStatement .= ".withUploadFilter";
233  }
234  } else {
235  $params[] = $id;
236  $filter = "WHERE job_pk = $" . count($params);
237  $statement .= ".withJobFilter";
238  $countStatement .= ".withJobFilter";
239  }
240 
241  $result = $this->dbManager->getSingleRow("$totalJobSql $filter;", $params,
242  $countStatement);
243 
244  $totalResult = $result['cnt'];
245 
246  $offset = ($page - 1) * $limit;
247  if ($limit > 0) {
248  $params[] = $limit;
249  $pagination = "LIMIT $" . count($params);
250  $params[] = $offset;
251  $pagination .= " OFFSET $" . count($params);
252  $statement .= ".withLimit";
253  $totalResult = floor($totalResult / $limit) + 1;
254  } else {
255  $totalResult = 1;
256  }
257 
258  $jobs = [];
259  $result = $this->dbManager->getRows("$jobSQL $filter $pagination;", $params,
260  $statement);
261  foreach ($result as $row) {
262  $job = new Job($row["job_pk"]);
263  $job->setName($row["job_name"]);
264  $job->setQueueDate($row["job_queued"]);
265  $job->setUploadId($row["job_upload_fk"]);
266  $job->setUserId($row["job_user_fk"]);
267  $job->setGroupId($row["job_group_fk"]);
268  $jobs[] = $job;
269  }
270  return [$jobs, $totalResult];
271  }
272 
280  public function getTokenKey($tokenId)
281  {
282  $sql = "SELECT token_key, created_on, expire_on, user_fk, active, token_scope " .
283  "FROM personal_access_tokens WHERE pat_pk = $1;";
284  return $this->dbManager->getSingleRow($sql, [$tokenId],
285  __METHOD__ . ".getTokenSecret");
286  }
287 
293  public function invalidateToken($tokenId)
294  {
295  $sql = "UPDATE personal_access_tokens SET active = false WHERE pat_pk = $1;";
296  $this->dbManager->getSingleRow($sql, [$tokenId], __METHOD__ . ".invalidateToken");
297  }
298 
314  public function insertNewTokenKey($userId, $expire, $scope, $name, $key)
315  {
316  if (! $this->checkTokenNameUnique($userId, $name)) {
317  throw new DuplicateTokenNameException(
318  "Already have a token with same name.", 409);
319  }
320  if (! $this->checkTokenKeyUnique($userId, $name)) {
321  throw new DuplicateTokenKeyException();
322  }
323  $sql = "INSERT INTO personal_access_tokens " .
324  "(user_fk, created_on, expire_on, token_scope, token_name, token_key, active) " .
325  "VALUES ($1, NOW(), $2, $3, $4, $5, true) " .
326  "RETURNING pat_pk || '.' || user_fk AS jti, created_on";
327  return $this->dbManager->getSingleRow($sql, [
328  $userId, $expire, $scope, $name, $key
329  ], __METHOD__ . ".insertNewToken");
330  }
331 
340  private function checkTokenNameUnique($userId, $tokenName)
341  {
342  $tokenIsUnique = true;
343  $sql = "SELECT count(*) AS cnt FROM personal_access_tokens " .
344  "WHERE user_fk = $1 AND token_name = $2;";
345  $result = $this->dbManager->getSingleRow($sql, [$userId, $tokenName],
346  __METHOD__ . ".checkTokenNameUnique");
347  if ($result['cnt'] != 0) {
348  $tokenIsUnique = false;
349  }
350  return $tokenIsUnique;
351  }
352 
361  private function checkTokenKeyUnique($userId, $tokenKey)
362  {
363  $tokenIsUnique = true;
364  $sql = "SELECT count(*) AS cnt FROM personal_access_tokens " .
365  "WHERE user_fk = $1 AND token_key = $2;";
366  $result = $this->dbManager->getSingleRow($sql, [$userId, $tokenKey],
367  __METHOD__ . ".checkTokenKeyUnique");
368  if ($result['cnt'] != 0) {
369  $tokenIsUnique = false;
370  }
371  return $tokenIsUnique;
372  }
373 
379  public function getMaxTokenValidity()
380  {
381  $sql = "SELECT conf_value FROM sysconfig WHERE variablename = $1;";
382  $result = $this->dbManager->getSingleRow($sql, ["PATMaxExipre"],
383  __METHOD__ . ".tokenMaxValidFromSysconfig");
384  $validity = 30;
385  if (! empty($result['conf_value'])) {
386  $validity = intval($result['conf_value']);
387  }
388  return $validity;
389  }
390 }
Exception when a token has duplicate name for same user.
Model class to hold Upload info.
Definition: Upload.php:28
checkTokenKeyUnique($userId, $tokenKey)
Definition: DbHelper.php:361
static getUserId()
Get the current user&#39;s id.
Definition: Auth.php:69
static isAdmin()
Check if user is admin.
Definition: Auth.php:87
getFilenameFromUploadTree($uploadTreePk)
Definition: DbHelper.php:125
doesIdExist($tableName, $idRowName, $id)
Definition: DbHelper.php:140
REST api helper classes.
Exception when a token has duplicate key for same user.
insertNewTokenKey($userId, $expire, $scope, $name, $key)
Definition: DbHelper.php:314
__construct(DbManager $dbManager)
Definition: DbHelper.php:56
getUploads($userId, $uploadId=null)
Definition: DbHelper.php:80
checkTokenNameUnique($userId, $tokenName)
Definition: DbHelper.php:340
getJobs($id=null, $limit=0, $page=1, $uploadId=null)
Get the recent jobs.
Definition: DbHelper.php:215
fo_dbManager * dbManager
fo_dbManager object
Definition: process.c:28
Model to hold user information.
Definition: User.php:31
Provides helper methods to access database for REST api.
Definition: DbHelper.php:43