FOSSology  4.4.0
Open Source License Compliance by Open Source Software
AdminLicenseFromCSV.php
1 <?php
2 /*
3  SPDX-FileCopyrightText: © 2008-2013 Hewlett-Packard Development Company, L.P.
4  SPDX-FileCopyrightText: © 2014 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_license_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 License Import",
47  self::MENU_LIST => "Admin::License Admin::License Import",
48  self::REQUIRES_LOGIN => true,
49  self::PERMISSION => Auth::PERM_ADMIN
50  ));
52  $this->licenseCsvImport = $GLOBALS['container']->get('app.license_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['LicenseDBContent']),
58  'maxtime' => intval($this->sysconfig['LicenseDBSleep']),
59  'token' => trim($this->sysconfig['LicenseDBToken'])
60  ];
61 
62  $this->guzzleClient = HttpUtils::getGuzzleClient($SysConf, $this->configuration['uri'], $this->configuration['token']);
63  }
64 
68  public function getFileInputName($apiVersion = ApiVersion::V1)
69  {
70  if ($apiVersion == ApiVersion::V2) {
71  return $this::FILE_INPUT_NAME_V2;
72  } else {
73  return $this::FILE_INPUT_NAME;
74  }
75  }
76 
81  protected function handle(Request $request)
82  {
83  $vars = array();
84  if (!$request->isMethod('POST')) {
85  $vars['licenseDBHealth'] = $this->checkLicenseDBHealth();
86  }
87  if ($request->isMethod('POST')) {
88  if ($request->get('importFrom') === 'licensedb') {
89  $startTime = microtime(true);
90  $vars['message'] = $this->handleLicenseDbImport();
91  $fetchLicenseTime = microtime(true) - $startTime;
92  $this->fileLogger->debug("Fetching License and Check if exist 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,
101  $enclosure)[1];
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'] = true;
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 
125  public function handleLicenseDbImport()
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 && json_last_error() !== JSON_ERROR_NONE) {
140  return $msg . "Error decoding JSON: " . json_last_error_msg() . "\n";
141  } else {
142  return $this->licenseCsvImport->importJsonData($data, $msg);
143  }
144  } catch (RequestException|GuzzleException $e) {
145  return $msg . _('Something Went Wrong, check if host is accessible') . ': ' . $e->getMessage();
146  }
147  }
148 
153  public function handleFileUpload($uploadedFile, $delimiter = ',', $enclosure = '"')
154  {
155  $errMsg = '';
156  if (!($uploadedFile instanceof UploadedFile)) {
157  $errMsg = _("No file selected");
158  } elseif ($uploadedFile->getError() !== UPLOAD_ERR_OK) {
159  $errMsg = $uploadedFile->getErrorMessage();
160  } elseif ($uploadedFile->getSize() == 0 && $uploadedFile->getError() == 0) {
161  $errMsg = _("Larger than upload_max_filesize ") .
162  ini_get(self::KEY_UPLOAD_MAX_FILESIZE);
163  } elseif ($uploadedFile->getClientOriginalExtension() != 'csv'
164  && $uploadedFile->getClientOriginalExtension() != 'json') {
165  $errMsg = _('Invalid file extension ') .
166  $uploadedFile->getClientOriginalExtension() . ' of file ' .
167  $uploadedFile->getClientOriginalName();
168  }
169  if (!empty($errMsg)) {
170  return array(false, $errMsg, 400);
171  }
172  $this->licenseCsvImport->setDelimiter($delimiter);
173  $this->licenseCsvImport->setEnclosure($enclosure);
174 
175  return array(true, $this->licenseCsvImport->handleFile($uploadedFile->getRealPath(), $uploadedFile->getClientOriginalExtension()), 200);
176  }
177 
178 
186  public function checkLicenseDBHealth()
187  {
188 
189  $getHealth = $this->configuration['url'] . $this->configuration['uri'] . "/health";
190  try {
191  $response = $this->guzzleClient->get($getHealth);
192  if ($response->getStatusCode() === 200) {
193  return true;
194  }
195  } catch (RequestException|GuzzleException $e) {
196  return false;
197  }
198 
199  return false;
200  }
201 }
202 
203 register_plugin(new AdminLicenseFromCSV());
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:22
Upload a file from the users computer using the UI.
getFileInputName($apiVersion=ApiVersion::V1)
handleFileUpload($uploadedFile, $delimiter=',', $enclosure='"')
char * trim(char *ptext)
Trimming whitespace.
Definition: fossconfig.c:690
fo_conf * sysconfig