FOSSology  4.5.1
Open Source License Compliance by Open Source Software
AdminObligationFromCSV.php
1 <?php
2 /*
3  SPDX-FileCopyrightText: © 2008-2013 Hewlett-Packard Development Company, L.P.
4  SPDX-FileCopyrightText: © 2014-2017 Siemens AG
5 
6  SPDX-License-Identifier: GPL-2.0-only
7 */
8 
9 namespace Fossology\UI\Page;
10 
16 use GuzzleHttp\Client;
17 use GuzzleHttp\Exception\GuzzleException;
18 use GuzzleHttp\Exception\RequestException;
19 use Symfony\Component\HttpFoundation\File\UploadedFile;
20 use Symfony\Component\HttpFoundation\Request;
21 use Symfony\Component\HttpFoundation\Response;
22 
27 {
28  const NAME = "admin_obligation_from_csv";
29  const KEY_UPLOAD_MAX_FILESIZE = 'upload_max_filesize';
30  const FILE_INPUT_NAME = 'file_input';
31  const FILE_INPUT_NAME_V2 = 'fileInput';
32 
36  private $guzzleClient;
40  private $sysconfig;
41 
42  function __construct()
43  {
44  global $SysConf;
45  parent::__construct(self::NAME, array(
46  self::TITLE => "Admin Obligation Import",
47  self::MENU_LIST => "Admin::Obligation Admin::Obligation Import",
48  self::REQUIRES_LOGIN => true,
49  self::PERMISSION => Auth::PERM_ADMIN
50  ));
52  $this->obligationsCsvImport = $GLOBALS['container']->get('app.obligation_csv_import');
53  $this->sysconfig = $SysConf['SYSCONFIG'];
54  $this->configuration = [
55  'url' => trim($this->sysconfig['LicenseDBURL']),
56  'uri' => trim($this->sysconfig['LicenseDBBaseURL']),
57  'content' => trim($this->sysconfig['LicenseDBContentObligations']),
58  'token' => trim($this->sysconfig['LicenseDBToken'])
59  ];
60 
61  $this->guzzleClient = HttpUtils::getGuzzleClient($SysConf, $this->configuration['uri'], $this->configuration['token']);
62  }
63 
67  public function getFileInputName($apiVersion = ApiVersion::V1)
68  {
69  if ($apiVersion == ApiVersion::V2) {
70  return $this::FILE_INPUT_NAME_V2;
71  } else {
72  return $this::FILE_INPUT_NAME;
73  }
74  }
75 
80  protected function handle(Request $request)
81  {
82  $vars = array();
83  if (!$request->isMethod('POST')) {
84  $getHealth = $this->configuration['url'] . $this->configuration['uri'] . "/health";
85  $vars['licenseDBHealth'] = HttpUtils::checkLicenseDBHealth($getHealth, $this->guzzleClient);
86  }
87  if ($request->isMethod('POST')) {
88  if ($request->get('importFrom') === 'licensedb') {
89  $startTime = microtime(true);
90  $vars['message'] = $this->handleLicenseDbObligationImport();
91  $fetchLicenseTime = microtime(true) - $startTime;
92  $this->fileLogger->debug("Fetching Obligations and Check time took: " . sprintf("%0.3fms", 1000 * $fetchLicenseTime));
93  $this->fileLogger->debug("****************** Message From LicenseDB import [" . date('Y-m-d H:i:s') . "] ******************");
94  $this->fileLogger->debug($vars["message"]);
95  $this->fileLogger->debug("****************** End Message From LicenseDB import ******************");
96  } else {
97  $uploadFile = $request->files->get(self::FILE_INPUT_NAME);
98  $delimiter = $request->get('delimiter') ?: ',';
99  $enclosure = $request->get('enclosure') ?: '"';
100  $vars['message'] = $this->handleFileUpload($uploadFile, $delimiter, $enclosure);
101  }
102  }
103 
104  $vars[self::KEY_UPLOAD_MAX_FILESIZE] = ini_get(self::KEY_UPLOAD_MAX_FILESIZE);
105  $vars['baseUrl'] = $request->getBaseUrl();
106  $vars['license_csv_import'] = false;
107 
108  if (!empty(trim($this->configuration['url']))) {
109  $vars['baseURL'] = !empty($this->configuration['uri']);
110  $vars['authToken'] = !empty($this->configuration['token']);
111  $vars['exportEndpoint'] = !empty($this->configuration['content']);
112  return $this->render("admin_license_from_licensedb.html.twig", $this->mergeWithDefault($vars));
113  } else {
114  return $this->render("admin_license_from_csv.html.twig", $this->mergeWithDefault($vars));
115  }
116  }
117 
126  {
127  $msg = '<br>';
128  $data = null;
129  $finalURL = $this->configuration['url'] . $this->configuration['uri'] . $this->configuration['content'];
130  try {
131  $startTimeReq = microtime(true);
132  $response = $this->guzzleClient->get($finalURL);
133  $fetchLicenseTimeReq = microtime(true) - $startTimeReq;
134  $this->fileLogger->debug("LicenseDB req:' took " . sprintf("%0.3fms", 1000 * $fetchLicenseTimeReq));
135  if ($response->getStatusCode() == 200) {
136  $data = json_decode($response->getBody()->getContents());
137  }
138 
139  if ($data === null) {
140  if (json_last_error() !== JSON_ERROR_NONE) {
141  return $msg . "Error decoding JSON: " . json_last_error_msg() . "\n";
142  }
143  return $msg . "No Obligations Found";
144  }
145  if (empty($data)) {
146  return $msg . "There are no Obligations Present in LicenseDB";
147  }
148  return $this->obligationsCsvImport->importJsonData($data, $msg);
149  } catch (RequestException|GuzzleException $e) {
150  return $msg . _('Something Went Wrong, check if host is accessible') . ': ' . $e->getMessage();
151  }
152  }
153 
158  public function handleFileUpload($uploadedFile, $delimiter = ',', $enclosure = '"', $fromRest = false)
159  {
160  $errMsg = '';
161  if (!($uploadedFile instanceof UploadedFile)) {
162  $errMsg = _("No file selected");
163  } elseif ($uploadedFile->getSize() == 0 && $uploadedFile->getError() == 0) {
164  $errMsg = _("Larger than upload_max_filesize ") . ini_get(self::KEY_UPLOAD_MAX_FILESIZE);
165  } elseif ($uploadedFile->getClientOriginalExtension() != 'csv'
166  && $uploadedFile->getClientOriginalExtension() != 'json') {
167  $errMsg = _('Invalid extension ') .
168  $uploadedFile->getClientOriginalExtension() . ' of file ' .
169  $uploadedFile->getClientOriginalName();
170  }
171  if (!empty($errMsg)) {
172  if ($fromRest) {
173  return array(false, $errMsg, 400);
174  }
175  return $errMsg;
176  }
177  $this->obligationsCsvImport->setDelimiter($delimiter);
178  $this->obligationsCsvImport->setEnclosure($enclosure);
179 
180  return array(true, $this->obligationsCsvImport->handleFile($uploadedFile->getRealPath(), $uploadedFile->getClientOriginalExtension()), 200);
181  }
182 }
183 
184 register_plugin(new AdminObligationFromCSV());
Helper class for Obligation CSV Import.
Contains the constants and helpers for authentication of user.
Definition: Auth.php:24
render($templateName, $vars=null, $headers=null)
static getGuzzleClient(array $SysConf, string $baseUri, string $token="")
Definition: HttpUtils.php:24
static checkLicenseDBHealth(string $getHealth, $guzzleClient)
Definition: HttpUtils.php:61
Upload a file from the users computer using the UI.
handleFileUpload($uploadedFile, $delimiter=',', $enclosure='"', $fromRest = false)
char * trim(char *ptext)
Trimming whitespace.
Definition: fossconfig.c:690
fo_conf * sysconfig