FOSSology  4.7.1
Open Source License Compliance by Open Source Software
LicenseDao.php
1 <?php
2 /*
3  SPDX-FileCopyrightText: © 2014-2018 Siemens AG
4  Author: Andreas Würl
5 
6  SPDX-License-Identifier: GPL-2.0-only
7 */
8 
9 namespace Fossology\Lib\Dao;
10 
20 use Monolog\Logger;
21 
23 {
24  const NO_LICENSE_FOUND = 'No_license_found';
25  const VOID_LICENSE = 'Void';
26 
28  private $dbManager;
30  private $logger;
32  private $candidatePrefix = '*';
33 
34  function __construct(DbManager $dbManager)
35  {
36  $this->dbManager = $dbManager;
37  $this->logger = new Logger(self::class);
38  }
39 
47  function getAgentFileLicenseMatches(ItemTreeBounds $itemTreeBounds, $usageId=LicenseMap::TRIVIAL)
48  {
49  $uploadTreeTableName = $itemTreeBounds->getUploadTreeTableName();
50  $statementName = __METHOD__ . ".$uploadTreeTableName.$usageId";
51  $params = array($itemTreeBounds->getUploadId(), $itemTreeBounds->getLeft(), $itemTreeBounds->getRight());
52  if ($usageId==LicenseMap::TRIVIAL) {
53  $licenseJoin = "license_ref mlr ON license_file.rf_fk = mlr.rf_pk";
54  } else {
55  $params[] = $usageId;
56  $licenseMapCte = LicenseMap::getMappedLicenseRefView('$4');
57  $licenseJoin = "($licenseMapCte) AS mlr ON license_file.rf_fk = mlr.rf_origin";
58  }
59 
60  $this->dbManager->prepare($statementName,
61  "SELECT LFR.rf_shortname AS license_shortname,
62  LFR.rf_spdx_id AS spdx_id,
63  LFR.rf_fullname AS license_fullname,
64  LFR.rf_pk AS license_id,
65  LFR.fl_pk AS license_file_id,
66  LFR.pfile_fk as file_id,
67  LFR.rf_match_pct AS percent_match,
68  AG.agent_name AS agent_name,
69  AG.agent_pk AS agent_id,
70  AG.agent_rev AS agent_revision
71  FROM ( SELECT mlr.rf_fullname, mlr.rf_shortname, mlr.rf_spdx_id, mlr.rf_pk, license_file.fl_pk, license_file.agent_fk, license_file.pfile_fk, license_file.rf_match_pct
72  FROM license_file JOIN $licenseJoin) as LFR
73  INNER JOIN $uploadTreeTableName as UT ON UT.pfile_fk = LFR.pfile_fk
74  INNER JOIN agent as AG ON AG.agent_pk = LFR.agent_fk
75  WHERE AG.agent_enabled='true' and
76  UT.upload_fk=$1 AND UT.lft BETWEEN $2 AND $3
77  ORDER BY license_shortname ASC, percent_match DESC");
78  $result = $this->dbManager->execute($statementName, $params);
79  $matches = array();
80  while ($row = $this->dbManager->fetchArray($result)) {
81  $licenseRef = new LicenseRef(intval($row['license_id']), $row['license_shortname'], $row['license_fullname'], $row['spdx_id']);
82  $agentRef = new AgentRef(intval($row['agent_id']), $row['agent_name'], $row['agent_revision']);
83  $matches[] = new LicenseMatch(intval($row['file_id']), $licenseRef, $agentRef, intval($row['license_file_id']), intval($row['percent_match']));
84  }
85 
86  $this->dbManager->freeResult($result);
87  return $matches;
88  }
89 
90 
97  function getBulkFileLicenseMatches(ItemTreeBounds $itemTreeBounds)
98  {
99  $uploadTreeTableName = $itemTreeBounds->getUploadTreeTableName();
100  $statementName = __METHOD__ . ".$uploadTreeTableName";
101 
102  $this->dbManager->prepare($statementName,
103  "SELECT LF.rf_shortname AS license_shortname,
104  LF.rf_spdx_id AS spdx_id,
105  LF.rf_fullname AS license_fullname,
106  LF.rf_pk AS license_id,
107  LFB.lrb_pk AS license_file_id,
108  LSB.removing AS removing,
109  UT.pfile_fk as file_id
110  FROM license_ref_bulk as LFB
111  INNER JOIN license_set_bulk AS LSB ON LFB.lrb_pk = LSB.lrb_fk
112  INNER JOIN license_ref as LF on LF.rf_pk = LSB.rf_fk
113  INNER JOIN $uploadTreeTableName as UT ON UT.uploadtree_pk = LFB.uploadtree_fk
114  WHERE UT.upload_fk=$1 AND UT.lft BETWEEN $2 and $3
115  ORDER BY license_file_id ASC");
116 
117  $result = $this->dbManager->execute($statementName,
118  array($itemTreeBounds->getUploadId(), $itemTreeBounds->getLeft(), $itemTreeBounds->getRight()));
119 
120  $matches = array();
121 
122  while ($row = $this->dbManager->fetchArray($result)) {
123  $licenseRef = new LicenseRef($row['license_id'], $row['license_shortname'], $row['license_fullname'], $row['spdx_id']);
124  if ($row['removing'] == 'f') {
125  $agentID = 1;
126  $agentName = "bulk addition";
127  } else {
128  $agentID = 2;
129  $agentName = "bulk removal";
130  }
131  $agentRef = new AgentRef($agentID, $agentName, "empty");
132  $matches[] = new LicenseMatch(intval($row['file_id']), $licenseRef, $agentRef, intval($row['license_file_id']));
133  }
134 
135  $this->dbManager->freeResult($result);
136  return $matches;
137  }
138 
142  public function getLicenseRefs($search = null, $orderAscending = true)
143  {
144  if (isset($_SESSION) && array_key_exists('GroupId', $_SESSION)) {
145  $rfTable = 'license_all';
146  $options = array('columns' => array('rf_pk', 'rf_shortname', 'rf_fullname'), 'candidatePrefix' => $this->candidatePrefix);
147  $licenseViewDao = new LicenseViewProxy($_SESSION['GroupId'], $options, $rfTable);
148  $withCte = $licenseViewDao->asCTE();
149  } else {
150  $withCte = '';
151  $rfTable = 'ONLY license_ref';
152  }
153 
154  $searchCondition = $search ? "WHERE rf_shortname ilike $1" : "";
155 
156  $order = $orderAscending ? "ASC" : "DESC";
157  $statementName = __METHOD__ . ($search ? ".search_" . $search : "") . ".order_$order";
158 
159  $this->dbManager->prepare($statementName,
160  $sql = $withCte . " select rf_pk,rf_shortname,rf_spdx_id,rf_fullname from $rfTable $searchCondition order by LOWER(rf_shortname) $order");
161  $result = $this->dbManager->execute($statementName, $search ? array('%' . strtolower($search) . '%') : array());
162  $licenseRefs = array();
163  while ($row = $this->dbManager->fetchArray($result)) {
164  $licenseRefs[] = new LicenseRef(intval($row['rf_pk']), $row['rf_shortname'], $row['rf_fullname'], $row['rf_spdx_id']);
165  }
166  $this->dbManager->freeResult($result);
167  return $licenseRefs;
168  }
169 
170 
174  public function getConclusionLicenseRefs($groupId, $search = null, $orderAscending = true, $exclude=array())
175  {
176  $rfTable = 'license_all';
177  $options = array('columns' => array('rf_pk', 'rf_shortname', 'rf_fullname', 'rf_active', 'rf_spdx_id'),
178  'candidatePrefix' => $this->candidatePrefix);
179  $licenseViewDao = new LicenseViewProxy($groupId, $options, $rfTable);
180  $order = $orderAscending ? "ASC" : "DESC";
181  $statementName = __METHOD__ . ".order_$order";
182  $param = array();
183  /* exclude license with parent, excluded child or selfexcluded */
184  $sql = $licenseViewDao->asCTE()." SELECT rf_pk,rf_shortname,rf_spdx_id,rf_fullname FROM $rfTable
185  WHERE rf_active = 'yes' AND NOT EXISTS (select * from license_map WHERE rf_pk=rf_fk AND rf_fk!=rf_parent)";
186  if ($search) {
187  $param[] = '%' . $search . '%';
188  $statementName .= '.search';
189  $sql .= " AND rf_shortname ilike $1";
190  }
191  if (count($exclude)>0) {
192  // $param[] = $exclude;
193  $tuple = implode(',', $exclude);
194  $statementName .= '.exclude'.$tuple;
195  $sql .= " AND NOT EXISTS (select * from license_map WHERE rf_pk=rf_parent AND rf_fk IN ($tuple))
196  AND rf_pk NOT IN($tuple)";
197  }
198  $this->dbManager->prepare($statementName, "$sql ORDER BY LOWER(rf_shortname) $order");
199  $result = $this->dbManager->execute($statementName, $param);
200  $licenseRefs = array();
201  while ($row = $this->dbManager->fetchArray($result)) {
202  $licenseRefs[] = new LicenseRef(intval($row['rf_pk']), $row['rf_shortname'], $row['rf_fullname'], $row['rf_spdx_id']);
203  }
204  $this->dbManager->freeResult($result);
205  return $licenseRefs;
206  }
207 
208 
212  public function getLicenseArray($groupId = null)
213  {
214  $statementName = __METHOD__;
215  $rfTable = 'license_all';
216  $options = array('columns' => array('rf_pk', 'rf_shortname', 'rf_fullname', 'rf_active'), 'candidatePrefix' => $this->candidatePrefix);
217  if ($groupId === null) {
218  $groupId = (isset($_SESSION) && array_key_exists('GroupId', $_SESSION)) ? $_SESSION['GroupId'] : 0;
219  }
220  $licenseViewDao = new LicenseViewProxy($groupId, $options, $rfTable);
221  $withCte = $licenseViewDao->asCTE();
222 
223  $this->dbManager->prepare($statementName,
224  $withCte . " select rf_pk id,rf_shortname shortname,rf_fullname fullname from $rfTable WHERE rf_active = 'yes' ORDER BY LOWER(rf_shortname)");
225  $result = $this->dbManager->execute($statementName);
226  $licenseRefs = $this->dbManager->fetchAll($result);
227  $this->dbManager->freeResult($result);
228  return $licenseRefs;
229  }
230 
238  public function getActiveLicensesForGroup($groupId)
239  {
240  // $groupId is a literal in the CTE, so the statement name must vary
241  // with it or two different groups collide on one cached statement.
242  $statementName = __METHOD__ . ".$groupId";
243  $rfTable = 'license_all';
244  $viewOptions = array('columns' => array('rf_pk', 'rf_shortname', 'rf_active'), 'candidatePrefix' => $this->candidatePrefix);
245  $licenseViewDao = new LicenseViewProxy($groupId, $viewOptions, $rfTable);
246  $withCte = $licenseViewDao->asCTE();
247 
248  $this->dbManager->prepare($statementName,
249  $withCte . " SELECT rf_pk, rf_shortname FROM $rfTable WHERE rf_active = true ORDER BY LOWER(rf_shortname)");
250  $result = $this->dbManager->execute($statementName);
251  $rows = $this->dbManager->fetchAll($result);
252  $this->dbManager->freeResult($result);
253 
254  $licenses = array();
255  foreach ($rows as $row) {
256  $licenses[$row['rf_pk']] = $row['rf_shortname'];
257  }
258  return $licenses;
259  }
260 
268  public function getLicenseIdPerPfileForAgentId(ItemTreeBounds $itemTreeBounds, $selectedAgentId, $includeSubfolders=true, $nameRange=array())
269  {
270  $uploadTreeTableName = $itemTreeBounds->getUploadTreeTableName();
271  $statementName = __METHOD__ . '.' . $uploadTreeTableName;
272  $param = array($selectedAgentId);
273 
274  if ($includeSubfolders) {
275  $param[] = $itemTreeBounds->getLeft();
276  $param[] = $itemTreeBounds->getRight();
277  $condition = "lft BETWEEN $2 AND $3";
278  $statementName .= ".subfolders";
279  if (!empty($nameRange)) {
280  $condition .= " AND ufile_name BETWEEN $4 and $5";
281  $param[] = $nameRange[0];
282  $param[] = $nameRange[1];
283  $statementName .= ".nameRange";
284  }
285  } else {
286  $param[] = $itemTreeBounds->getItemId();
287  $condition = "realparent = $2";
288  }
289 
290  if ('uploadtree_a' == $uploadTreeTableName) {
291  $param[] = $itemTreeBounds->getUploadId();
292  $condition .= " AND utree.upload_fk=$".count($param);
293  }
294 
295  $sql = "SELECT utree.pfile_fk as pfile_id,
296  license_ref.rf_pk as license_id,
297  rf_match_pct as match_percentage,
298  CAST($1 AS INT) AS agent_id,
299  uploadtree_pk
300  FROM license_file, license_ref, $uploadTreeTableName utree
301  WHERE agent_fk = $1
302  AND license_file.rf_fk = license_ref.rf_pk
303  AND license_file.pfile_fk = utree.pfile_fk
304  AND $condition
305  ORDER BY match_percentage ASC";
306 
307  $this->dbManager->prepare($statementName, $sql);
308  $result = $this->dbManager->execute($statementName, $param);
309  $licensesPerFileId = array();
310  while ($row = $this->dbManager->fetchArray($result)) {
311  $licensesPerFileId[$row['pfile_id']][$row['license_id']] = $row;
312  }
313 
314  $this->dbManager->freeResult($result);
315  return $licensesPerFileId;
316  }
317 
327  public function getLicensesPerFileNameForAgentId(ItemTreeBounds $itemTreeBounds,
328  $selectedAgentIds=null,
329  $includeSubfolders=true,
330  $excluding='',
331  $ignore=false,
332  &$clearingDecisionsForLicList = array(),
333  $includeTreeId=false)
334  {
335  $uploadTreeTableName = $itemTreeBounds->getUploadTreeTableName();
336  $statementName = __METHOD__ . '.' . $uploadTreeTableName;
337  $param = array();
338 
339  $condition = " (ufile_mode & (1<<28)) = 0";
340  if ($includeSubfolders) {
341  $param[] = $itemTreeBounds->getLeft();
342  $param[] = $itemTreeBounds->getRight();
343  $condition .= " AND lft BETWEEN $1 AND $2";
344  $statementName .= ".subfolders";
345  } else {
346  $param[] = $itemTreeBounds->getItemId();
347  $condition .= " AND realparent = $1";
348  }
349 
350  if ('uploadtree_a' == $uploadTreeTableName) {
351  $param[] = $itemTreeBounds->getUploadId();
352  $condition .= " AND upload_fk=$".count($param);
353  }
354 
355  $agentSelect = "";
356  if ($selectedAgentIds !== null) {
357  $statementName .= ".".count($selectedAgentIds)."agents";
358  $agentSelect = "WHERE agent_fk IS NULL";
359  foreach ($selectedAgentIds as $selectedAgentId) {
360  $param[] = $selectedAgentId;
361  $agentSelect .= " OR agent_fk = $".count($param);
362  }
363  }
364 
365  $sql = "
366 SELECT uploadtree_pk, ufile_name, lft, rgt, ufile_mode,
367  rf_shortname, agent_fk
368 FROM (SELECT
369  uploadtree_pk, ufile_name,
370  lft, rgt, ufile_mode, pfile_fk
371  FROM $uploadTreeTableName
372  WHERE $condition) AS subselect1
373 LEFT JOIN (SELECT rf_shortname,pfile_fk,agent_fk
374  FROM license_file, license_ref
375  WHERE rf_fk = rf_pk) AS subselect2
376  ON subselect1.pfile_fk = subselect2.pfile_fk
377 $agentSelect
378 ORDER BY lft asc
379 ";
380 
381  $this->dbManager->prepare($statementName, $sql);
382  $result = $this->dbManager->execute($statementName, $param);
383  $licensesPerFileName = array();
384 
385  $row = $this->dbManager->fetchArray($result);
386  $pathStack = array($row['ufile_name']);
387  $rgtStack = array($row['rgt']);
388  $lastLft = $row['lft'];
389  $path = implode('/', $pathStack);
390  $this->addToLicensesPerFileName($licensesPerFileName, $path, $row,
391  $ignore, $clearingDecisionsForLicList, $includeTreeId);
392  while ($row = $this->dbManager->fetchArray($result)) {
393  if (!empty($excluding) && false!==strpos("/$row[ufile_name]/", $excluding)) {
394  $lastLft = $row['rgt'] + 1;
395  continue;
396  }
397  if ($row['lft'] < $lastLft) {
398  continue;
399  }
400 
401  $this->updateStackState($pathStack, $rgtStack, $lastLft, $row);
402  $path = implode('/', $pathStack);
403  $this->addToLicensesPerFileName($licensesPerFileName, $path, $row,
404  $ignore, $clearingDecisionsForLicList, $includeTreeId);
405  }
406  $this->dbManager->freeResult($result);
407  return array_reverse($licensesPerFileName);
408  }
409 
410  private function updateStackState(&$pathStack, &$rgtStack, &$lastLft, $row)
411  {
412  if ($row['lft'] >= $lastLft) {
413  while (count($rgtStack) > 0 && $row['lft'] > $rgtStack[count($rgtStack)-1]) {
414  array_pop($pathStack);
415  array_pop($rgtStack);
416  }
417  if ($row['lft'] > $lastLft) {
418  $pathStack[] = $row['ufile_name'];
419  $rgtStack[] = $row['rgt'];
420  $lastLft = $row['lft'];
421  }
422  }
423  }
424 
425  private function addToLicensesPerFileName(&$licensesPerFileName, $path, $row,
426  $ignore,
427  &$clearingDecisionsForLicList = array(),
428  $includeTreeId=false)
429  {
430  if (($row['ufile_mode'] & (1 << 29)) == 0) {
431  if ($row['rf_shortname']) {
432  $licensesPerFileName[$path]['scanResults'][] = $row['rf_shortname'];
433  if (array_key_exists($row['uploadtree_pk'], $clearingDecisionsForLicList)) {
434  $licensesPerFileName[$path]['concludedResults'][] = $clearingDecisionsForLicList[$row['uploadtree_pk']];
435  }
436  }
437  } else if (!$ignore) {
438  $licensesPerFileName[$path] = false;
439  }
440  if ($includeTreeId) {
441  $licensesPerFileName[$path]['uploadtree_pk'][] = $row['uploadtree_pk'];
442  }
443  }
444 
450  public function getLicenseHistogram(ItemTreeBounds $itemTreeBounds, $agentId=null)
451  {
452  $uploadTreeTableName = $itemTreeBounds->getUploadTreeTableName();
453  $agentText = $agentId ? (is_array($agentId) ? implode(',', $agentId) : $agentId) : '-';
454  $statementName = __METHOD__ . '.' . $uploadTreeTableName . ".$agentText";
455  $param = array($itemTreeBounds->getUploadId(), $itemTreeBounds->getLeft(), $itemTreeBounds->getRight());
456  $sql = "SELECT rf_shortname AS license_shortname, rf_spdx_id AS spdx_id, rf_pk, count(*) AS count, count(distinct pfile_ref.pfile_fk) as \"unique\"
457  FROM ( SELECT license_ref.rf_shortname, license_ref.rf_spdx_id, license_ref.rf_pk, license_file.fl_pk, license_file.agent_fk, license_file.pfile_fk
458  FROM license_file
459  JOIN license_ref ON license_file.rf_fk = license_ref.rf_pk) AS pfile_ref
460  RIGHT JOIN $uploadTreeTableName UT ON pfile_ref.pfile_fk = UT.pfile_fk";
461  if (is_array($agentId)) {
462  $sql .= ' AND agent_fk=ANY($4)';
463  $param[] = '{' . implode(',', $agentId) . '}';
464  } elseif (!empty($agentId)) {
465  $sql .= ' AND agent_fk=$4';
466  $param[] = $agentId;
467  }
468  $sql .= " WHERE (rf_shortname IS NULL OR rf_shortname NOT IN ('Void')) AND upload_fk=$1
469  AND (UT.lft BETWEEN $2 AND $3) AND UT.ufile_mode&(3<<28)=0
470  GROUP BY license_shortname, spdx_id, rf_pk";
471  $this->dbManager->prepare($statementName, $sql);
472  $result = $this->dbManager->execute($statementName, $param);
473  $assocLicenseHist = array();
474  while ($row = $this->dbManager->fetchArray($result)) {
475  $shortname = empty($row['rf_pk']) ? self::NO_LICENSE_FOUND : $row['license_shortname'];
476  $assocLicenseHist[$shortname] = array(
477  'count' => intval($row['count']),
478  'unique' => intval($row['unique']),
479  'rf_pk' => intval($row['rf_pk']),
480  'spdx_id' => LicenseRef::convertToSpdxId($shortname, $row['spdx_id'])
481  );
482  }
483  $this->dbManager->freeResult($result);
484  return $assocLicenseHist;
485  }
486 
487  public function getLicenseShortnamesContained(ItemTreeBounds $itemTreeBounds, $latestSuccessfulAgentIds=null, $filterLicenses = array('VOID')) //'No_license_found',
488  {
489  $uploadTreeTableName = $itemTreeBounds->getUploadTreeTableName();
490 
491  $noLicenseFoundStmt = empty($filterLicenses) ? "" : " AND rf_shortname NOT IN ("
492  . implode(", ", array_map(function ($name)
493  {
494  return "'" . $name . "'";
495  }, $filterLicenses)) . ")";
496 
497  $statementName = __METHOD__ . '.' . $uploadTreeTableName;
498 
499  $agentFilter = '';
500  if (is_array($latestSuccessfulAgentIds)) {
501  $agentIdSet = "{" . implode(',', $latestSuccessfulAgentIds) . "}";
502  $statementName .= ".$agentIdSet";
503  $agentFilter = " AND agent_fk=ANY('$agentIdSet')";
504  }
505 
506  $this->dbManager->prepare($statementName,
507  "SELECT license_ref.rf_shortname
508  FROM license_file JOIN license_ref ON license_file.rf_fk = license_ref.rf_pk
509  INNER JOIN $uploadTreeTableName uploadTree ON uploadTree.pfile_fk=license_file.pfile_fk
510  WHERE upload_fk=$1
511  AND lft BETWEEN $2 AND $3
512  $noLicenseFoundStmt $agentFilter
513  GROUP BY rf_shortname
514  ORDER BY rf_shortname ASC");
515  $result = $this->dbManager->execute($statementName,
516  array($itemTreeBounds->getUploadId(), $itemTreeBounds->getLeft(), $itemTreeBounds->getRight()));
517 
518  $licenses = array();
519  while ($row = $this->dbManager->fetchArray($result)) {
520  $licenses[] = $row['rf_shortname'];
521  }
522  $this->dbManager->freeResult($result);
523 
524  return $licenses;
525  }
526 
533  private function getLicenseByCondition($condition, $param, $groupId=null)
534  {
535  $extraCondition = "";
536  $row = $this->dbManager->getSingleRow(
537  "SELECT rf_pk, rf_shortname, rf_spdx_id, rf_fullname, rf_text, rf_url, rf_risk, rf_detector_type FROM ONLY license_ref WHERE $condition",
538  $param, __METHOD__ . ".$condition.only");
539  if (false === $row && isset($groupId)) {
540  $userId = (isset($_SESSION) && array_key_exists('UserId', $_SESSION)) ? $_SESSION['UserId'] : 0;
541  $statementName = __METHOD__ . ".$condition";
542  if (!empty($userId)) {
543  $param[] = $userId;
544  $extraCondition = "AND group_fk IN (SELECT group_fk FROM group_user_member WHERE user_fk=$".count($param).")";
545  $statementName .= ".userId";
546  }
547  if (is_int($groupId) && empty($userId)) {
548  $param[] = $groupId;
549  $extraCondition = "AND group_fk=$".count($param);
550  $statementName .= ".groupId";
551  }
552  $row = $this->dbManager->getSingleRow(
553  "SELECT rf_pk, rf_shortname, rf_spdx_id, rf_fullname, rf_text, rf_url, rf_risk, rf_detector_type FROM license_candidate WHERE $condition $extraCondition",
554  $param, $statementName);
555  }
556  if (false === $row) {
557  return null;
558  }
559  return new License(intval($row['rf_pk']), $row['rf_shortname'],
560  $row['rf_fullname'], $row['rf_risk'], $row['rf_text'], $row['rf_url'],
561  $row['rf_detector_type'], $row['rf_spdx_id']);
562  }
563 
569  public function getLicenseById($licenseId, $groupId=null)
570  {
571  return $this->getLicenseByCondition('rf_pk=$1', array($licenseId), $groupId);
572  }
573 
579  public function getLicenseByShortName($licenseShortname, $groupId=null)
580  {
581  return $this->getLicenseByCondition('rf_shortname=$1', array($licenseShortname), $groupId);
582  }
583 
589  public function getLicenseBySpdxId($licenseSpdxId, $groupId=null)
590  {
591  return $this->getLicenseByCondition('rf_spdx_id=$1', array($licenseSpdxId), $groupId);
592  }
593 
606  public function insertBulkLicense($userId, $groupId, $uploadTreeId, $licenseRemovals, $refText, $ignoreIrrelevant=true, $delimiters=null, $scanFindingsOnly=false)
607  {
608  if (strcasecmp($delimiters, "DEFAULT") === 0) {
609  $delimiters = null;
610  } elseif ($delimiters !== null) {
611  $delimiters = StringOperation::replaceUnicodeControlChar($delimiters);
612  }
613  $licenseRefBulkIdResult = $this->dbManager->getSingleRow(
614  "INSERT INTO license_ref_bulk (user_fk, group_fk, uploadtree_fk, rf_text, ignore_irrelevant, bulk_delimiters, scan_findings)
615  VALUES ($1,$2,$3,$4,$5,$6,$7) RETURNING lrb_pk",
616  array($userId, $groupId, $uploadTreeId,
618  $this->dbManager->booleanToDb($ignoreIrrelevant),
619  $delimiters,
620  $this->dbManager->booleanToDb($scanFindingsOnly)),
621  __METHOD__ . '.getLrb'
622  );
623  if ($licenseRefBulkIdResult === false) {
624  return -1;
625  }
626  $bulkId = $licenseRefBulkIdResult['lrb_pk'];
627 
628  $stmt = __METHOD__ . '.insertAction';
629  $this->dbManager->prepare($stmt, "INSERT INTO license_set_bulk (lrb_fk, rf_fk, removing, comment, reportinfo, acknowledgement) VALUES ($1,$2,$3,$4,$5,$6)");
630  foreach ($licenseRemovals as $licenseId=>$removing) {
631  $this->dbManager->execute($stmt, array($bulkId, $licenseId,
632  $this->dbManager->booleanToDb($removing[0]),
636  }
637 
638  return $bulkId ;
639  }
640 
646  public function isNewLicense($newShortname, $groupId)
647  {
648  $licenceViewDao = new LicenseViewProxy($groupId, array('columns' => array('rf_shortname')));
649  $sql = 'SELECT count(*) cnt FROM (' . $licenceViewDao->getDbViewQuery() . ') AS license_all WHERE rf_shortname=$1';
650  $duplicatedRef = $this->dbManager->getSingleRow($sql, array($newShortname), __METHOD__.".$groupId" );
651  return $duplicatedRef['cnt'] == 0;
652  }
653 
660  public function insertLicense($shortname, $refText, $spdxId = null)
661  {
662  $row = $this->dbManager->getSingleRow(
663  "INSERT INTO license_ref (rf_shortname, rf_text, rf_detector_type, rf_spdx_id) VALUES ($1, $2, 2, $3) RETURNING rf_pk",
667  __METHOD__.".addLicense" );
668  return $row["rf_pk"];
669  }
670 
676  public function insertUploadLicense($newShortname, $refText, $groupId, $userId)
677  {
678  $sql = 'INSERT INTO license_candidate (group_fk,rf_shortname,rf_fullname,rf_text,rf_md5,rf_detector_type,rf_user_fk_created) VALUES ($1,$2,$2,$3,md5($3),1,$4) RETURNING rf_pk';
679  $refArray = $this->dbManager->getSingleRow($sql, array($groupId,
681  StringOperation::replaceUnicodeControlChar($refText), $userId), __METHOD__);
682  return $refArray['rf_pk'];
683  }
684 
689  public function getLicenseCount()
690  {
691  $licenseRefTable = $this->dbManager->getSingleRow("SELECT COUNT(*) cnt FROM license_ref WHERE rf_text!=$1", array("License by Nomos."));
692  return intval($licenseRefTable['cnt']);
693  }
694 
704  public function updateCandidate($rf_pk, $shortname, $fullname, $rfText, $url,
705  $rfNotes, $lastmodified, $userIdmodified,
706  $readyformerge, $riskLvl, $spdxId = null)
707  {
708  $marydone = $this->dbManager->booleanToDb($readyformerge);
709  $sql = 'UPDATE license_candidate SET ' .
710  'rf_shortname=$2, rf_fullname=$3, rf_text=$4, rf_url=$5, rf_notes=$6, ' .
711  'rf_lastmodified=$7, rf_user_fk_modified=$8, marydone=$9, rf_risk=$10';
712  $params = array($rf_pk, StringOperation::replaceUnicodeControlChar($shortname),
715  StringOperation::replaceUnicodeControlChar($rfNotes), $lastmodified,
716  $userIdmodified, $marydone, $riskLvl);
717  $statement = __METHOD__;
718  if ($spdxId != null) {
719  $params[] = StringOperation::replaceUnicodeControlChar($spdxId);
720  $sql .= ', rf_spdx_id=$' . count($params);
721  $statement .= ".spdxid";
722  }
723  $sql .= ' WHERE rf_pk=$1';
724  $this->dbManager->getSingleRow($sql, $params, $statement);
725  }
726 
731  public function getLicenseParentById($licenseId, $groupId=null)
732  {
733  return $this->getLicenseByCondition(" rf_pk=(SELECT rf_parent FROM license_map WHERE usage=$1 AND rf_fk=$2 AND rf_fk!=rf_parent)",
734  array(LicenseMap::CONCLUSION,$licenseId), $groupId);
735  }
736 
743  public function getLicenseObligations($licenseLists, $candidate = false)
744  {
745  if (!empty($licenseLists)) {
746  $sql = "";
747  $params = array();
748  $params[] = '{' . implode(',', $licenseLists) . '}';
749  if ($candidate) {
750  $tableName='obligation_candidate_map';
751  $sql = "SELECT ob_pk, ob_topic, ob_text, ob_active, rf_fk, " .
752  "ob_type, ob_classification, ob_comment, " .
753  "rf_shortname, rf_spdx_id FROM obligation_ref " .
754  "JOIN $tableName ON $tableName.ob_fk = obligation_ref.ob_pk " .
755  "JOIN license_ref ON $tableName.rf_fk = license_ref.rf_pk " .
756  "WHERE ob_active='t' AND rf_fk = ANY($1::int[]);";
757  } else {
758  $tableName='obligation_map';
759  $conclusionmapCte = LicenseMap::getMappedLicenseRefView('$2');
760  $sql = "WITH conclusionmap AS (" . $conclusionmapCte . ") " .
761  "SELECT ob_pk, ob_topic, ob_text, ob_active, rf_origin AS rf_fk, " .
762  "ob_type, ob_classification, ob_comment, " .
763  "lr.rf_shortname, lr.rf_spdx_id FROM obligation_ref " .
764  "JOIN $tableName ON $tableName.ob_fk = obligation_ref.ob_pk " .
765  "JOIN conclusionmap ON $tableName.rf_fk = conclusionmap.rf_pk " .
766  "INNER JOIN license_ref lr ON conclusionmap.rf_origin = lr.rf_pk " .
767  "WHERE ob_active='t' AND rf_origin = ANY($1::int[]);";
768  $params[] = LicenseMap::CONCLUSION;
769  }
770  $statementName = __METHOD__.$tableName;
771  $this->dbManager->prepare($statementName, $sql);
772  $result = $this->dbManager->execute($statementName, $params);
773  $ObligationRef = $this->dbManager->fetchAll($result);
774  $this->dbManager->freeResult($result);
775  return $ObligationRef;
776  }
777  }
778 
784  public function getLicenseType($licenseId)
785  {
786  $sql = "SELECT rf_licensetype FROM license_ref WHERE rf_pk = $1;";
787  $result = $this->dbManager->getSingleRow($sql, [$licenseId],
788  __METHOD__ . ".getLicenseType");
789  if (!empty($result)) {
790  return $result["rf_licensetype"];
791  }
792  return null;
793  }
794 }
Wrapper class for license map.
Definition: LicenseMap.php:19
static getMappedLicenseRefView($usageExpr=' $1')
Query to get license map view along with license ref.
Definition: LicenseMap.php:191
getLicenseByCondition($condition, $param, $groupId=null)
Definition: LicenseDao.php:533
getLicenseBySpdxId($licenseSpdxId, $groupId=null)
Definition: LicenseDao.php:589
insertLicense($shortname, $refText, $spdxId=null)
Definition: LicenseDao.php:660
getLicenseHistogram(ItemTreeBounds $itemTreeBounds, $agentId=null)
Definition: LicenseDao.php:450
getLicenseByShortName($licenseShortname, $groupId=null)
Definition: LicenseDao.php:579
getBulkFileLicenseMatches(ItemTreeBounds $itemTreeBounds)
get all the tried bulk recognitions for a single file or uploadtree (currently unused)
Definition: LicenseDao.php:97
getAgentFileLicenseMatches(ItemTreeBounds $itemTreeBounds, $usageId=LicenseMap::TRIVIAL)
get all the licenses for a single file or uploadtree
Definition: LicenseDao.php:47
getLicenseRefs($search=null, $orderAscending=true)
Definition: LicenseDao.php:142
insertUploadLicense($newShortname, $refText, $groupId, $userId)
Definition: LicenseDao.php:676
getLicenseParentById($licenseId, $groupId=null)
Definition: LicenseDao.php:731
getLicenseArray($groupId=null)
Definition: LicenseDao.php:212
insertBulkLicense($userId, $groupId, $uploadTreeId, $licenseRemovals, $refText, $ignoreIrrelevant=true, $delimiters=null, $scanFindingsOnly=false)
Definition: LicenseDao.php:606
getConclusionLicenseRefs($groupId, $search=null, $orderAscending=true, $exclude=array())
Definition: LicenseDao.php:174
getLicensesPerFileNameForAgentId(ItemTreeBounds $itemTreeBounds, $selectedAgentIds=null, $includeSubfolders=true, $excluding='', $ignore=false, &$clearingDecisionsForLicList=array(), $includeTreeId=false)
Definition: LicenseDao.php:327
getLicenseIdPerPfileForAgentId(ItemTreeBounds $itemTreeBounds, $selectedAgentId, $includeSubfolders=true, $nameRange=array())
Definition: LicenseDao.php:268
isNewLicense($newShortname, $groupId)
Definition: LicenseDao.php:646
getLicenseObligations($licenseLists, $candidate=false)
Definition: LicenseDao.php:743
getLicenseById($licenseId, $groupId=null)
Definition: LicenseDao.php:569
updateCandidate($rf_pk, $shortname, $fullname, $rfText, $url, $rfNotes, $lastmodified, $userIdmodified, $readyformerge, $riskLvl, $spdxId=null)
Definition: LicenseDao.php:704
static convertToSpdxId($shortname, $spdxId)
Given a license's shortname and spdx id, give out spdx id to use in reports.
Definition: LicenseRef.php:106
static replaceUnicodeControlChar($input, $replace="")
fo_dbManager * dbManager
fo_dbManager object
Definition: process.c:16