FOSSology  4.7.1
Open Source License Compliance by Open Source Software
cyclonedx.php
Go to the documentation of this file.
1 <?php
2 /*
3  SPDX-FileCopyrightText: © 2023 Sushant Kumar(sushantmishra02102002@gmail.com)
4 
5  SPDX-License-Identifier: GPL-2.0-only
6 */
20 namespace Fossology\CycloneDX;
21 
35 
36 include_once(__DIR__ . "/version.php");
37 include_once(__DIR__ . "/reportgenerator.php");
38 
43 class CycloneDXAgent extends Agent
44 {
45  const OUTPUT_FORMAT_KEY = "outputFormat";
46  const DEFAULT_OUTPUT_FORMAT = "cyclonedx_json";
47  const UPLOADS_ADD_KEY = "uploadsAdd";
48 
52  private $additionalUploads = [];
53 
61  protected $citations = [];
66  private $reportutils;
70  private $uploadDao;
74  private $clearingDao;
79  private $licenseDao;
83  protected $dbManager;
87  private $licenseMap;
91  protected $agentNames = AgentRef::AGENT_LIST;
95  protected $uri;
100  private $licensesInDocument = [];
108  private $packageName;
113  private $settings;
114 
115  function __construct()
116  {
117  // deduce the agent name from the command line arguments
118  $args = getopt("", array(
119  self::OUTPUT_FORMAT_KEY.'::',
120  self::UPLOADS_ADD_KEY.'::'
121  ));
122  $agentName = "";
123  if (array_key_exists(self::OUTPUT_FORMAT_KEY, $args)) {
124  $agentName = trim($args[self::OUTPUT_FORMAT_KEY]);
125  }
126  if (empty($agentName)) {
128  }
129  if (array_key_exists(self::UPLOADS_ADD_KEY, $args)) {
130  $uploadsString = $args[self::UPLOADS_ADD_KEY];
131  if (!empty($uploadsString)) {
132  $this->additionalUploads = explode(',', $uploadsString);
133  }
134  }
135 
136  parent::__construct($agentName, AGENT_VERSION, AGENT_REV);
137 
138  $this->uploadDao = $this->container->get('dao.upload');
139  $this->clearingDao = $this->container->get('dao.clearing');
140  $this->licenseDao = $this->container->get('dao.license');
141  $this->dbManager = $this->container->get('db.manager');
142 
143  $this->reportutils = new ReportUtils();
144  $this->reportGenerator = new BomReportGenerator();
145  }
146 
151  function processUploadId($uploadId)
152  {
153  $this->licenseMap = new LicenseMap($this->dbManager, $this->groupId, LicenseMap::REPORT, true);
154 
155  $this->settings = $this->uploadDao->getCyclonedxSettings($uploadId);
156  $this->reportGenerator->applySettings($this->settings);
157 
158  $packageNodes = $this->renderPackage($uploadId);
159 
160  $this->computeUri($uploadId);
161 
162  $this->writeReport($packageNodes, $uploadId);
163  return true;
164  }
165 
171  protected function getUri($fileBase)
172  {
173  if (count($this->additionalUploads) > 0) {
174  $fileName = $fileBase . "multifile" . "_" . strtoupper($this->outputFormat);
175  } else {
176  $fileName = $fileBase. strtoupper($this->outputFormat)."_".$this->packageName;
177  }
178 
179  return $fileName .".json" ;
180  }
181 
186  protected function computeUri($uploadId)
187  {
188  global $SysConf;
189  $upload = $this->uploadDao->getUpload($uploadId);
190  $this->packageName = $upload->getFilename();
191 
192  $fileBase = $SysConf['FOSSOLOGY']['path']."/report/";
193 
194  $this->uri = $this->getUri($fileBase);
195  }
196 
202  protected function renderPackage($uploadId)
203  {
204  global $SysConf;
205  $uploadTreeTableName = $this->uploadDao->getUploadtreeTableName($uploadId);
206  $itemTreeBounds = $this->uploadDao->getParentItemBounds($uploadId, $uploadTreeTableName);
207  $this->heartbeat(0);
208 
209  $filesWithLicenses = $this->reportutils
210  ->getFilesWithLicensesFromClearings($itemTreeBounds, $this->groupId,
211  $this, $this->licensesInDocument);
212  $this->heartbeat(0);
213 
214  $this->reportutils->addClearingStatus($filesWithLicenses, $itemTreeBounds, $this->groupId);
215  $this->heartbeat(0);
216 
217  $this->reportutils->addScannerResults($filesWithLicenses, $itemTreeBounds, $this->groupId, $this->licensesInDocument);
218  $this->heartbeat(0);
219 
220  $this->reportutils->addCopyrightResults($filesWithLicenses, $uploadId);
221  $this->heartbeat(0);
222 
223  $this->citations = [
224  'cite-scanner' => [
225  'timestamp' => date('c'),
226  'attributedTo' => 'tool-fossology-scanners',
227  'expressions' => []
228  ],
229  'cite-analyst' => [
230  'timestamp' => date('c'),
231  'attributedTo' => 'person-fossology-analyst',
232  'expressions' => []
233  ]
234  ];
235 
236  $customLicenseTexts = $this->clearingDao->getMainLicenseReportInfos($uploadId, $this->groupId);
237 
238  $upload = $this->uploadDao->getUpload($uploadId);
239  $components = $this->generateFileComponents($filesWithLicenses, $upload->getTreeTableName(), $uploadId, $itemTreeBounds, $customLicenseTexts);
240 
241  $mainLicenseIds = $this->clearingDao->getMainLicenseIds($uploadId, $this->groupId);
242  $mainLicenses = array();
243  $seenLicenseIds = array();
244  foreach ($mainLicenseIds as $licId) {
245  $reportedLicenseId = $this->licenseMap->getProjectedId($licId);
246  $mainLicObj = $this->licenseDao->getLicenseById($reportedLicenseId, $this->groupId);
247  if ($mainLicObj === null) {
248  continue;
249  }
250 
251  $licensedata = $this->getLicenseDataForCycloneDX($mainLicObj, $licId, $customLicenseTexts);
252  $licensedata['bom-ref'] = 'lic-clearing-main-' . $licId;
253  $licensedata['acknowledgement'] = 'concluded';
254  $this->citations['cite-analyst']['expressions'][] = '$..[?(@.bom-ref=="lic-clearing-main-' . $licId . '")]';
255  $mainLicenses[] = $this->reportGenerator->createLicense($licensedata);
256 
257  $customText = array_key_exists($licId, $customLicenseTexts) ? $customLicenseTexts[$licId] : null;
258  $licText = !empty($customText) ? $customText : $mainLicObj->getText();
259  $reportLicId = $mainLicObj->getId() . "-" . md5($licText);
260  $seenLicenseIds[$reportLicId] = true;
261  }
262 
263  foreach ($filesWithLicenses as $fileNode) {
264  $isConcluded = !empty($fileNode->getConcludedLicenses());
265  $licenseIds = $isConcluded
266  ? $fileNode->getConcludedLicenses()
267  : $fileNode->getScanners();
268  foreach ($licenseIds as $licenseId) {
269  if (array_key_exists($licenseId, $this->licensesInDocument) && !array_key_exists($licenseId, $seenLicenseIds)) {
270  $seenLicenseIds[$licenseId] = true;
271  $licObj = $this->licensesInDocument[$licenseId]->getLicenseObj();
272  $isCustomText = $this->licensesInDocument[$licenseId]->isCustomText();
273  $licensedata = $this->getLicenseDataForCycloneDX($licObj, $licenseId, $customLicenseTexts, $isCustomText);
274  $refPrefix = $isConcluded ? 'clearing' : 'scanner';
275  $licensedata['bom-ref'] = 'lic-' . $refPrefix . '-main-' . $licenseId;
276  $licensedata['acknowledgement'] = $isConcluded ? 'concluded' : 'declared';
277  $this->citations['cite-' . ($isConcluded ? 'analyst' : 'scanner')]['expressions'][] = '$..[?(@.bom-ref=="lic-' . $refPrefix . '-main-' . $licenseId . '")]';
278  $mainLicenses[] = $this->reportGenerator->createLicense($licensedata);
279  }
280  }
281  }
282 
283  $hashes = $this->uploadDao->getUploadHashes($uploadId);
284  $serializedhash = array();
285  $serializedhash[] = $this->reportGenerator->createHash('SHA-1', $hashes['sha1']);
286  $serializedhash[] = $this->reportGenerator->createHash('MD5', $hashes['md5']);
287  // Check if sha256 is not empty
288  if (array_key_exists('sha256', $hashes) && !empty($hashes['sha256'])) {
289  $serializedhash[] = $this->reportGenerator->createHash('SHA-256', $hashes['sha256']);
290  }
291 
292  $allCopyrights = array();
293  foreach ($filesWithLicenses as $fileNode) {
294  $fileCopyrights = $fileNode->getCopyrights();
295  if (!empty($fileCopyrights)) {
296  $allCopyrights = array_merge($allCopyrights, $fileCopyrights);
297  }
298  }
299  $allCopyrights = array_unique($allCopyrights);
300 
301  $reportInfo = $this->uploadDao->getReportInfo($uploadId);
302  $componentVersion = ($reportInfo['ri_version'] ?? '');
303  if ($componentVersion == 'NA') {
304  $componentVersion = '';
305  }
306  $componentId = ($reportInfo['ri_component_id'] ?? '');
307  if ($componentId == 'NA') {
308  $componentId = '';
309  }
310  $componentType = intval($reportInfo['ri_component_type'] ?? 0);
311  $generalAssessment = ($reportInfo['ri_general_assesment'] ?? '');
312  if ($generalAssessment == 'NA') {
313  $generalAssessment = '';
314  }
315 
316  $purl = '';
317  $externalReferences = [];
318  if (!empty($componentId)) {
319  if ($componentType === ComponentType::PURL || $componentType === ComponentType::PACKAGEURL) {
320  $purl = $componentId;
321  } else {
322  $externalReferences[] = [
323  'type' => 'distribution',
324  'url' => $componentId
325  ];
326  }
327  }
328 
329  $maincomponentData = array (
330  'bomref' => strval($uploadId),
331  'type' => 'library',
332  'name' => $upload->getFilename(),
333  'version' => $componentVersion,
334  'hashes' => $serializedhash,
335  'scope' => 'required',
336  'mimeType' => $this->getMimeType($uploadId),
337  'copyright' => implode("\n", $allCopyrights),
338  'description' => $generalAssessment,
339  'purl' => $purl,
340  'externalReferences' => $externalReferences,
341  'licenses' => $mainLicenses
342  );
343  $maincomponent = $this->reportGenerator->createComponent($maincomponentData);
344 
345  $formattedDate = date('Y-m-d\TH:i:s\Z');
346 
347  $finalCitations = [];
348  if (!empty($this->citations['cite-scanner']['expressions'])) {
349  $finalCitations[] = $this->citations['cite-scanner'];
350  }
351  if (!empty($this->citations['cite-analyst']['expressions'])) {
352  $finalCitations[] = $this->citations['cite-analyst'];
353  }
354 
355  $bomdata = array(
356  'timestamp' => $formattedDate,
357  'tool-version' => $SysConf['BUILD']['VERSION'],
358  'maincomponent' => $maincomponent,
359  'components' => $components,
360  'externalReferences' => $externalReferences,
361  'citations' => $finalCitations
362  );
363 
364  return $this->reportGenerator->generateReport($bomdata);
365  }
366 
374  protected function generateFileComponents($filesWithLicenses, $treeTableName, $uploadId, $itemTreeBounds, $customLicenseTexts = array())
375  {
376  /* @var $treeDao TreeDao */
377  $treeDao = $this->container->get('dao.tree');
378 
379  $stateLicenseComment = $this->settings->isLicenseCommentEnabled();
380  $stateWoInfos = $this->settings->isIgnoreFilesWithoutInfo();
381  $stateOsselot = $this->settings->isOsselotExport();
382 
383  $filesProceeded = 0;
384  $lastValue = 0;
385  $components = array();
386  foreach ($filesWithLicenses as $fileId => $licenses) {
387  $filesProceeded += 1;
388  if (($filesProceeded & 2047) == 0) {
389  $this->heartbeat($filesProceeded - $lastValue);
390  $lastValue = $filesProceeded;
391  }
392 
393  if ($stateWoInfos && empty($licenses->getConcludedLicenses()) &&
394  empty($licenses->getScanners()) && empty($licenses->getCopyrights())) {
395  continue;
396  }
397 
398  $hashes = $treeDao->getItemHashes($fileId);
399  $serializedhash = array();
400  $serializedhash[] = $this->reportGenerator->createHash('SHA-1', $hashes['sha1']);
401  $serializedhash[] = $this->reportGenerator->createHash('MD5', $hashes['md5']);
402  // Check if sha256 is not empty
403  if (array_key_exists('sha256', $hashes) && !empty($hashes['sha256'])) {
404  $serializedhash[] = $this->reportGenerator->createHash('SHA-256', $hashes['sha256']);
405  }
406 
407  $fileName = $treeDao->getFullPath($fileId, $treeTableName, 0);
408  $licensesfound = [];
409 
410  if (!empty($licenses->getConcludedLicenses())) {
411  foreach ($licenses->getConcludedLicenses() as $licenseId) {
412  if (array_key_exists($licenseId, $this->licensesInDocument)) {
413  $licObj = $this->licensesInDocument[$licenseId]->getLicenseObj();
414  $isCustomText = $this->licensesInDocument[$licenseId]->isCustomText();
415  $licensedata = $this->getLicenseDataForCycloneDX($licObj, $licenseId, $customLicenseTexts, $isCustomText, $stateOsselot);
416  $licensedata['bom-ref'] = 'lic-clearing-' . $licenseId . '-' . $fileId;
417  $licensedata['acknowledgement'] = 'concluded';
418  $licensesfound[] = $this->reportGenerator->createLicense($licensedata, false);
419  }
420  }
421  } else {
422  foreach ($licenses->getScanners() as $licenseId) {
423  if (array_key_exists($licenseId, $this->licensesInDocument)) {
424  $licObj = $this->licensesInDocument[$licenseId]->getLicenseObj();
425  $isCustomText = $this->licensesInDocument[$licenseId]->isCustomText();
426  $licensedata = $this->getLicenseDataForCycloneDX($licObj, $licenseId, $customLicenseTexts, $isCustomText, $stateOsselot);
427  $licensedata['bom-ref'] = 'lic-scanner-' . $licenseId . '-' . $fileId;
428  $licensedata['acknowledgement'] = 'declared';
429  $licensesfound[] = $this->reportGenerator->createLicense($licensedata, false);
430  }
431  }
432  }
433  if (!empty($fileName)) {
434  $mimeType = $this->getFileMimeType($fileId, $treeTableName);
435  $componentdata = array(
436  'bomref' => $uploadId .'-'. $fileId,
437  'type' => 'file',
438  'name' => $fileName,
439  'hashes' => $serializedhash,
440  'mimeType' => $mimeType,
441  'copyright' => implode("\n", $licenses->getCopyrights()),
442  'licenses' => $licensesfound,
443  'acknowledgements' => implode("\n", $licenses->getAcknowledgements()),
444  'comments' => $stateLicenseComment ? implode("\n", $licenses->getComments()) : ''
445  );
446  $components[] = $this->reportGenerator->createComponent($componentdata);
447  }
448  }
449  $this->heartbeat($filesProceeded - $lastValue);
450  return $components;
451  }
452 
458  protected function writeReport($packageNodes, $uploadId)
459  {
460  $fileBase = dirname($this->uri);
461 
462  if (!is_dir($fileBase)) {
463  mkdir($fileBase, 0777, true);
464  }
465  umask(0133);
466 
467  $contents = json_encode($packageNodes, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
468  // To ensure the file is valid, replace any non-printable characters with a question mark.
469  // 'Non-printable' is ASCII < 0x20 (excluding \r, \n and tab) and 0x7F - 0x9F.
470  $contents = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/u','?',$contents);
471  file_put_contents($this->uri, $contents);
472  $this->updateReportTable($uploadId, $this->jobId, $this->uri);
473  }
474 
481  protected function updateReportTable($uploadId, $jobId, $fileName)
482  {
483  $this->reportutils->updateOrInsertReportgenEntry($uploadId, $jobId, $fileName);
484  }
485 
495  private function getLicenseDataForCycloneDX($licObj, $licenseId, $customLicenseTexts, $isCustomText = false, $includeText = true)
496  {
497  $customText = array_key_exists($licenseId, $customLicenseTexts) ? $customLicenseTexts[$licenseId] : null;
498  $licText = !empty($customText) ? $customText : $licObj->getText();
499 
500  $licensedata = array(
501  'url' => $licObj->getUrl()
502  );
503 
504  if (!empty($customText) || $isCustomText) {
505  if (!empty($customText)) {
506  $prefix = \Fossology\Lib\Data\LicenseRef::SPDXREF_PREFIX;
507  $licensedata['name'] = $prefix . $licObj->getShortName() . '-' . md5($customText);
508  } else {
509  $licensedata['name'] = $licObj->getShortName();
510  }
511  } else {
512  $spdxId = $licObj->getSpdxId();
513  if (!empty($spdxId)) {
514  $licensedata['id'] = $spdxId;
515  } else {
516  $licensedata['name'] = $licObj->getFullName();
517  }
518  }
519 
520  if ($includeText && !empty($licText)) {
521  $licensedata['textContent'] = base64_encode($licText);
522  $licensedata['textContentType'] = 'text/plain';
523  }
524 
525  return $licensedata;
526  }
527 
532  protected function getMimeType($uploadId)
533  {
534  $sql = "SELECT mimetype_name
535  FROM upload u
536  JOIN pfile pf ON u.pfile_fk = pf.pfile_pk
537  JOIN mimetype m ON pf.pfile_mimetypefk = m.mimetype_pk
538  WHERE u.upload_pk = $1";
539 
540  $row = $this->dbManager->getSingleRow($sql, [$uploadId], __METHOD__);
541  return $row['mimetype_name'];
542  }
543 
550  protected function getFileMimeType($fileId, $treeTableName)
551  {
552  $sql = "SELECT m.mimetype_name
553  FROM $treeTableName ut
554  JOIN pfile pf ON ut.pfile_fk = pf.pfile_pk
555  LEFT JOIN mimetype m ON pf.pfile_mimetypefk = m.mimetype_pk
556  WHERE ut.uploadtree_pk = $1";
557 
558  $row = $this->dbManager->getSingleRow($sql, [$fileId], __METHOD__);
559  return $row['mimetype_name'] ?? 'application/octet-stream';
560  }
561 }
562 
563 $agent = new CycloneDXAgent();
564 $agent->scheduler_connect();
565 $agent->run_scheduler_event_loop();
566 $agent->scheduler_disconnect(0);
const OUTPUT_FORMAT_KEY
Argument key for output format.
Definition: cyclonedx.php:45
getFileMimeType($fileId, $treeTableName)
Get the mime type of a file.
Definition: cyclonedx.php:550
writeReport($packageNodes, $uploadId)
Write the report the file and update report table.
Definition: cyclonedx.php:458
updateReportTable($uploadId, $jobId, $fileName)
Update the reportgen table with new report path.
Definition: cyclonedx.php:481
renderPackage($uploadId)
Given an upload id, render the report string.
Definition: cyclonedx.php:202
getMimeType($uploadId)
Get the mime type of the upload.
Definition: cyclonedx.php:532
processUploadId($uploadId)
Given an upload ID, process the items in it.
Definition: cyclonedx.php:151
getUri($fileBase)
Get the URI for the given package.
Definition: cyclonedx.php:171
const DEFAULT_OUTPUT_FORMAT
Default output format.
Definition: cyclonedx.php:46
computeUri($uploadId)
For a given upload, compute the URI.
Definition: cyclonedx.php:186
getLicenseDataForCycloneDX($licObj, $licenseId, $customLicenseTexts, $isCustomText=false, $includeText=true)
Helper to create license data array taking custom text into account.
Definition: cyclonedx.php:495
generateFileComponents($filesWithLicenses, $treeTableName, $uploadId, $itemTreeBounds, $customLicenseTexts=array())
Generate the components by files.
Definition: cyclonedx.php:374
Structure of an Agent with all required parameters.
Definition: Agent.php:41
heartbeat($newProcessed)
Send hear beat to the scheduler.
Definition: Agent.php:203
Wrapper class for license map.
Definition: LicenseMap.php:19
CycloneDX export settings of a user (defaults) or of an upload.
char * trim(char *ptext)
Trimming whitespace.
Definition: fossconfig.c:690
int jobId
The id of the job.
fo_dbManager * dbManager
fo_dbManager object
Definition: process.c:16
FUNCTION char * strtoupper(char *s)
Helper function to upper case a string.
Definition: utils.c:103
Namespace used by CycloneDX agent.